本文介绍了OpenCV(4.0.0) Python 错误:(-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) &&_mask.sameSize(*psrc1) 在函数 'cv::binary_op' 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我已阅读此线程 OpenCV Python 错误:错误:(-215) (mtype == CV_8U || mtype == CV_8S) &&_mask.sameSize(*psrc1) 在函数 cv::binary_op 中,但我的问题不是数组的形状或掩码不是 uint8 格式.

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'

推荐答案

根据错误提示,问题实际上是遮罩形状.来自文档:

As the error hints, the problem actually is the mask shape. From the docs:

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

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

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)

这篇关于OpenCV(4.0.0) Python 错误:(-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) &&_mask.sameSize(*psrc1) 在函数 'cv::binary_op' 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 10:41