我正在尝试通过执行精明的边缘检测来提取图像的一部分。我已经成功地创建了该对象的掩码。但是,当我对原始图像执行bitwise_and操作以提取前景部分时,会出现以下错误。OpenCV Error: Assertion failed ((mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1)) in cv::binary_op, file C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp, line 241
Traceback (most recent call last):
File "C:\Users\Boudhayan Dev\Desktop\extraction.py", line 37, in
new_image = cv2.bitwise_and(img_rgb,img_rgb,mask=mask)
cv2.error: C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:241: error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function cv::binary_op
我的代码如下-import cv2
import numpy as np
img_rgb = cv2.imread("3.jpg")
cv2.namedWindow("Original Image",cv2.WINDOW_NORMAL)
img = cv2.cvtColor(img_rgb,cv2.COLOR_RGB2HSV)
img = cv2.bilateralFilter(img,9,105,105)
r,g,b=cv2.split(img)
equalize1= cv2.equalizeHist(r)
equalize2= cv2.equalizeHist(g)
equalize3= cv2.equalizeHist(b)
equalize=cv2.merge((r,g,b))
equalize = cv2.cvtColor(equalize,cv2.COLOR_RGB2GRAY)
ret,thresh_image = cv2.threshold(equalize,0,255,cv2.THRESH_OTSU+cv2.THRESH_BINARY)
equalize= cv2.equalizeHist(thresh_image)
canny_image = cv2.Canny(equalize,250,255)
canny_image = cv2.convertScaleAbs(canny_image)
kernel = np.ones((3,3), np.uint8)
dilated_image = cv2.dilate(canny_image,kernel,iterations=1)
new,contours, hierarchy = cv2.findContours(dilated_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours= sorted(contours, key = cv2.contourArea, reverse = True)[:10]
c=contours[0]
print(cv2.contourArea(c))
final = cv2.drawContours(img, [c], -1, (255,0, 0), 3)
mask = np.zeros(img_rgb.shape,np.uint8)
new_image = cv2.drawContours(mask,[c],0,255,-1,)
new_image = cv2.bitwise_and(img_rgb,img_rgb,mask=mask)
cv2.namedWindow("new",cv2.WINDOW_NORMAL)
cv2.imshow("new",new_image)
cv2.imshow("Original Image",img)
cv2.waitKey()
注意:-如果我尝试用图像的灰度版本执行bitwise_and,则代码可以正常工作。但是,RGB、HSV或任何其他颜色空间都会导致上述错误。
请帮忙。
编辑1-
有问题的图像是这样的-
编辑2-
下面是使用Numpy方法后的结果。如您所见,提取的图像与橙色的大小相同,但它不包含橙色,而是包含遮罩本身。
编辑3-@DanMašek和@lightalchemist,我终于可以提取任何前景图像。
谢谢你