问题
I am trying to apply mask on an image using opencv bitwise-not. I am able to achieve this result if I read both original and mask image in Greyscale mode, but it doesn't work on 3 channel images.
I have read this thread OpenCV Python Error: error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function cv::binary_op but my problem isn't shapes of arrays or mask not being in uint8 format.
import cv2
import numpy as np
img = cv2.imread("Original.png") # original image, shape 544,480,3, dtype uint8
label = cv2.imread("Mask.png") # black and white mask,shape 544,480,3, dtype uint 8
shape = img.shape # 544,480,3
black_background = np.zeros(shape=shape, dtype=np.uint8)
result = cv2.bitwise_not(img,black_background,mask=label) # this is where error occurs
cv2.imwrite("masked.png",result)
I expect the output to be original image masked with label, I get error core
OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:245: error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op'
回答1:
As the error hints, the problem actually is the mask shape. From the docs:
mask – optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.
Your label
is a 3-channel image, which is incompatible; that's the reason why the greyscale was working, but since your Mask.png
actually is a black and white image you should go for it without any worries:
label = cv2.imread("Mask.png", cv2.IMREAD_GREYSCALE)
来源:https://stackoverflow.com/questions/56361919/opencv4-0-0-python-error-215assertion-failed-mtype-cv-8u-mtype