OpenCV : Python equivalent of `setTo` in C++

橙三吉。 提交于 2020-02-03 23:18:41

问题


What is the python equivalent of Mat::setTo in C++ ?

What I'm trying to do is to set value by mask:

Mat img;
...
img.setTo(0, mask);

Update:

Here is possible solution:

#set by mask area to zero
img= np.random.rand(200, 200, 3) * 255
img= img.astype(np.uint8)
mask = np.zeros((200, 200), np.uint8)
mask[10:100, 60:140] = 255
inv_mask= cv2.bitwise_not(mask)
n_channels= img.shape[2]
for i in range(0,n_channels):
    img[..., i]= img[..., i] * (inv_mask/255)

#to set arbitary value
img= np.random.rand(200, 200, 3) * 255
img= img.astype(np.uint8)
mask= np.zeros((200,200), np.uint8)
mask[10:100, 60:140]= 255
mask_bool= np.where(mask > 0)
value= 120
img[mask_bool]= value

回答1:


You can simply use img[mask > 0] = 0 which is the python equivalent of img.setTo(0, mask);




回答2:


opencv in python uses numpy as backend (more specifically numpy.ndarray) for images. This means you can do the following:

import numpy
img = numpy.zeros((256, 256, 3))  # This initializes a color image as an array full of zeros

Then if i wish to set the third channel as 1 all I have to do is:

img[:, :, 2:3] = 1

Therefore if Mask has the same dimensions as my third channel i can use it to set the third channel:

img[:, :, 2:3] = mask

edited after comment: in case you simply wish to set pixels of image to zeros using a mask a simple image * mask should suffice. make sure mask has same number of dimensions as image.

edit #2: Yeah that might work, but if the shape of your mask is the only issue, i would use mask[:, :, numpy.newaxis] to add a dimension and then multiply with image.

btw numpy.newaxis is same as using mask[:,:,None].



来源:https://stackoverflow.com/questions/41829511/opencv-python-equivalent-of-setto-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!