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

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

我正在尝试使用 opencv 按位非在图像上应用蒙版。如果我在灰度模式下同时读取原始图像和蒙版图像,我能够实现这个结果,但它不适用于 3 通道图像。

我已阅读此主题,但我的问题不是数组形状或掩码不是 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'

正如错误提示,问题实际上是面具形状。来自 docs:

mask – optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.

您的 label 是 3 通道图像,不兼容;这就是灰度工作的原因,但由于您的 Mask.png 实际上是黑白图像,您应该放心地使用它:

label = cv2.imread("Mask.png", cv2.IMREAD_GREYSCALE)