OpenCV Masking Image - error: (-215) (mtype == 0 |

2020-07-13 10:29发布

问题:

I am trying to subtract the background from an image using a mask and OpenCV's bitwise_and. However, I get the following error:

error: C:\ci\opencv_1512684736357\work\modules\core\src\arithm.cpp:241: error: (-215) (mtype == 0 || mtype == 1) && _mask.sameSize(*psrc1) in function cv::binary_op

My code looks like this:

mask = get_mask() #function that returns a mask (boolean)

#conversion of the mask
mask = mask.astype('int')
mask[mask == 0] = 255
mask[mask == 1] = 0

fg_masked = cv2.bitwise_and(img, img, mask=mask)

A question here on StackOverflow (OpenCV Python Error: error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function cv::binary_op) that addresses the same error indicates an issue with a potential shape mismatch. However, checking both the shape of my mask and my image it appears to me that they match, yielding:

mask.shape
OUT: (100, 83)

img.shape
OUT: (100, 83, 3)

I am using Python v3 and OpenCV v2

回答1:

The problem is not a shape mismatch... it is failing in the first part of the assert:

mtype == 0 || mtype == 1

It says that the type of the mask (mtype) should be either 0 or 1, i.e. CV_8U and CV_8S respectively.

You are using:

mask = mask.astype('int')

That means type CV_32S or 4 in the enum value.

Solution:

You can use np.uint8 or np.int8 assuming that you have done import numpy as np



标签: python opencv