OpenCV(4.0.0)Python错误:(-215:声明失败)(mtype == CV_8U || mtype == CV_8S)&& _mask.sameSize(* psrc1)在函数'cv :: binary_op'

时间:2019-05-29 13:36:14

标签: python python-3.x opencv bitwise-not

我正在尝试使用opencv按位非在图像上应用遮罩。如果我在灰度模式下同时读取原始图像和蒙版图像,则可以实现此结果,但不适用于3通道图像。

我已经阅读了该线程OpenCV Python Error: error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function cv::binary_op,但是我的问题不是数组的形状或掩码不是uint8格式。

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)

我希望输出是带有标签遮盖的原始图像,我得到了错误核心

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 个答案:

答案 0 :(得分:0)

如错误提示所示,问题实际上出在掩模形状上。来自docs

  

mask –可选的操作掩码,8位单通道数组,用于指定要更改的输出数组的元素。

您的label是3通道图像,不兼容;这就是为什么灰度有效的原因,但是由于您的Mask.png实际上是黑白图像,因此您应该毫无顾虑地追求它:

label = cv2.imread("Mask.png", cv2.IMREAD_GREYSCALE)
相关问题