找不到正确的轮廓数

can't find right numbers of contours count

我正在尝试查找具有红色轮廓的特定轮廓。下面是代码,我正在尝试这张图片 :

import numpy as np
import cv2

image = 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 contours
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Extract contours depending on OpenCV version
cnts = 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。我哪里做错了?

只需要在开头添加一个步骤,将图片模糊一点。

image = cv2.GaussianBlur(image, (3, 3), 0, 0, cv2.BORDER_DEFAULT)

如果您能注意到,您的蒙版图像中存在中断,因此检测到许多轮廓。要纠正这个问题(如果你只想要计数),你可以在找到轮廓之前扩大获得的蒙版图像,如下所示。

mask = cv2.inRange(image, lower, upper)

# Dilating the mask
kernel = np.ones((3, 3), dtype=np.uint8)
mask = cv2.dilate(mask, kernel, iterations=2)

# Find contours
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)