我正在尝试查找具有红色轮廓的特定轮廓。以下是我在此图像上尝试的代码 :
import numpy as npimport cv2image = cv2.imread('C:/Users/htc/Desktop/image.png')original = image.copy()image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)lower = np.array([0,50,50], dtype="uint8")upper = np.array([10, 255,255], 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]print(len(cnts))# 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()
我得到的轮廓长度是14,这是不正确的。正确的输出应该是3。我哪里做错了?
回答:
如果你能注意到,由于你的掩模图像中有断开之处,导致检测到了许多轮廓。为了纠正这一点(如果你只需要计数),你可以在查找轮廓之前对获得的掩模图像进行膨胀处理,如下所示。
mask = cv2.inRange(image, lower, upper)# Dilating the maskkernel = np.ones((3, 3), dtype=np.uint8)mask = cv2.dilate(mask, kernel, iterations=2)# Find contourscnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)