我正在编写代码,无法使用功能cv2.findContours,因为它有任何问题。请遵循代码:
import cv2
import matplotlib.pyplot as plt
import numpy as np
lower1 = np.array([0,118,0])
upper1 = np.array([120,198,166])
lower2 = np.array([45,0,0])
upper2 = np.array([70,255,255])
kernelOpen = np.ones((7,7))
kernelClose = np.ones((20,20))
img = cv2.imread ('inco.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask1 = cv2.inRange(hsv, lower1, upper1)
res1 = cv2.bitwise_not(img, img, mask = mask1)
cv2.imwrite('resultado_bitwise_not.png', res1)
img1 = cv2.imread ('resultado_bitwise_not.png')
hsv2 = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
mask2 = cv2.inRange(hsv2, lower2, upper2)
res2 = cv2.bitwise_and(img1, img1, mask = mask2)
cv2.imwrite('resultado_final.png', res2)
mask3 = cv2.morphologyEx (res2, cv2.MORPH_OPEN, kernelOpen)
mask4 = cv2.morphologyEx (mask3, cv2.MORPH_CLOSE, kernelClose)
_, conts, h = cv2.findContours(mask4, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, conts, -1,(0,255,0),3)
cv2.imwrite('mask4.png',mask4)
错误:
_, conts, h = cv2.findContours(mask4, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
error: OpenCV(3.4.1) C:\projects\opencv-python\opencv\modules\imgproc\src\contours.cpp:199: error: (-210) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function cvStartFindContours_Impl
答案 0 :(得分:0)
错误明确指出“ FindContours仅支持CV_8UC1图像”。您试图在findContours函数的输入字段中强制使用不是二进制图像(CV_8UC1)的图像(mask4)。您的inRange函数在代码的两个区域都创建了一个二进制映像。但是稍后,当您对rgb图像使用bitwise_and和bitwise_not运算符时,输出更改为不再是二进制的图像。请查看此example,以了解在二进制图像和彩色图像之间进行按位运算时会发生什么。这是所有问题的根源。尝试清除此冲突,您的代码将起作用。
答案 1 :(得分:0)
正如Arun Kumar所说,您应该将二进制图像(0和1)传递给函数cv2.findContours()
。
图像mask2
是从行mask2 = cv2.inRange(hsv2, lower2, upper2)
获得后应该处理的图像。它是二进制图像。可以进行以下更改以获得所需的结果:
mask2 = cv2.inRange(hsv2, lower2, upper2)
#--- replacing res2 with mask2 ---
mask3 = cv2.morphologyEx (mask2, cv2.MORPH_OPEN, kernelOpen)
mask4 = cv2.morphologyEx (mask3, cv2.MORPH_CLOSE, kernelClose)
_, conts, h = cv2.findContours(mask4, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, conts, -1,(0,255,0),3)
#--- you must write img not mask4 to see the contours on the original image---
cv2.imwrite('mask4.png', img)
如果您只想要被遮罩的部分:
res2 = cv2.bitwise_and(img1, img1, mask = mask4)
cv2.imwrite('resultado_final.png', res2)
答案 2 :(得分:0)
您可以在将cv2.findContours
与以下命令一起使用之前转换您的输入图像:
import numpy as np
import cv2
new_image = np.uint8(old_image) # convert to uint8
然后:
_, conts, h = cv2.findContours(new_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)