【问题标题】:can't find right numbers of contours count找不到正确的轮廓数
【发布时间】:2021-10-29 05:21:34
【问题描述】:

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

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。我在哪里做错了?

【问题讨论】:

  • 您的“轮廓”已断开连接,因此您最终会得到许多连接的组件,即许多轮廓

标签: python numpy opencv machine-learning contour


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    只需在开头添加一个步骤,使图片稍微模糊。

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

    【讨论】:

    • 感谢您的回答,但它没有显示赖特计数
    猜你喜欢
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2021-09-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    相关资源
    最近更新 更多