我试图根据下图AutoCAD绘图中显示的黄色轮廓检测轮廓数量。
import numpy as npimport cv2image = cv2.imread('C:/Users/htc/Desktop/capture.png')original = image.copy()image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)lower = np.array([0, 208, 94], dtype="uint8")upper = np.array([179, 255, 232], dtype="uint8")mask = cv2.inRange(image, lower, upper)# Find contourscnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# Extract contours depending on OpenCV versioncnts = cnts[0] if len(cnts) == 2 else cnts[1]# Iterate through contours and filter by the number of vertices for c in cnts: perimeter = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.04 * perimeter, True) if len(approx) > 5: cv2.drawContours(original, [c], -1, (36, 255, 12), -1)cv2.imshow('mask', mask)cv2.imshow('original', original)cv2.waitKey()
我期望的输出是检测到这两个轮廓圆圈,但没有实现。有人能帮我指出我哪里做错了么?
输出
回答:
黄色与其他颜色具有不同的色调值。你可以使用第一个通道(色调),其值范围是10:15
lower = np.array([10, 0, 0], dtype="uint8") upper = np.array([15, 255, 255], dtype="uint8")
色调通道指示图像的“颜色”,请参考此处。你可以显示色调通道
hue = image[:,:,0]cv2.imshow('hue', hue)
它几乎是黑色的。让我们“重新调整”其值:
cv2.imshow('hue', (hue-np.min(hue))/(np.max(hue)-np.min(hue))*255)
使用MS Paint找到“白色区域”的范围后,我发现它是
170-255
,并且np.max(hue) = 15, np.min(hue) = 0
,所以原始范围是10-15
。
这就是我如何得到lower
和upper
中的数值的。由于你只关心颜色,其他通道设置为0,0
对于lower
,和255,255
对于upper