[英]How to set the binary mask in OpenCV python correctly?
I have an image img. 我有一张图片img。 I also have a mask with value 255 at all the places where I want to retain the pixel values of img are 0 at all other places.
我还想在所有要保留img像素值的所有地方都设置一个值为255的蒙版。
I want to use these two images viz. 我想使用这两个图像,即。 the mask and img such that I create a matrix with original img values at places where the mask is 255, and the value -1 at all places where mask is 0.
遮罩和img,这样我就可以在遮罩为255的地方创建一个具有原始img值的矩阵,并在遮罩为0的所有地方创建一个值为-1的矩阵。
So, far, I have written this: 到目前为止,我已经写了:
maskedImg = cv2.bitwise_and(img, mask)
but the maskedImg has 0 at all the places where the mask has 0. How can I get the value -1 instead of 0 at all the other places using a fast bitwise operation? 但是maskedImg在掩码为0的所有位置都为0。如何使用快速按位运算在所有其他位置获得值-1而不是0?
I don't know what is your image's dtype. 我不知道您的图片的DType是什么。 Default is np.uint8, so you cann't set -1 on the result, it underflows to
-1 + 256 = 255
. 默认值为np.uint8,因此您无法在结果上设置-1,它的下溢为
-1 + 256 = 255
。 That is to say, if the dtype is np.uint8
, you cann't set it to negative value. 也就是说,如果
np.uint8
为np.uint8
,则不能将其设置为负值。
If you want to set to -1, you should change the dtype
. 如果要设置为-1,则应更改
dtype
。
#masked = cv2.bitwise_and(img, mask).astype(np.int32)
masked = np.int32(img)
masked[mask==0] = -1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.