2

我正在尝试使用 opencv bitwise-not 在图像上应用掩码。如果我在灰度模式下同时读取原始图像和蒙版图像,我能够实现此结果,但它不适用于 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'

4

1 回答 1

1

正如错误提示的那样,问题实际上是蒙版形状。从文档

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

label的是3通道图片,不兼容;这就是灰度工作的原因,但由于您Mask.png实际上是黑白图像,您应该毫无顾虑地去做:

label = cv2.imread("Mask.png", cv2.IMREAD_GREYSCALE)
于 2019-05-29T13:56:38.753 回答