OpenCV(4.0.0) Python Error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op'

我怕爱的太早我们不能终老 提交于 2021-02-10 16:27:17

问题


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

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