findContours returns 具有重复点的轮廓

findContours returns contour with duplicate points

OpenCV 的 findContours 有时 return 的结果不好

代码片段试图在边缘图像中找到最大的轮廓。

在 "bad" 示例中,似乎轮廓的大多数顶点都是不必要的重复。这会导致后续错误的 contourArea 和 pointPolygonTest 行为。

import cv2
import imutils
from scipy import misc

edges = misc.imread('edges3.png')

cnts = cv2.findContours(edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
sorted_cnts = sorted(cnts, key = lambda c:cv2.arcLength(c,True), reverse = True)
largest_cnt = sorted_cnts[0]

print("Largest contour area",cv2.contourArea(largest_cnt))
print("Largest contour arc length",cv2.arcLength(largest_cnt,True))
print("Largest contour num of vertx",len(largest_cnt))

错误 代码输出:

Largest contour area 14.0
Largest contour arc length 2639.200133085251
Largest contour num of vertx 667

代码输出:

Largest contour area 95534.0
Largest contour arc length 1321.8721450567245
Largest contour num of vertx 340

所附的两张照片几乎完全相同,结果应该return 相似。然而,第一个return是一个面积很小的轮廓,与第二个相比,弧长和顶点数增加了一倍。

我无法在评论中上传图片。有没有可能你的边缘检测有问题,有一些小的开口?结果是 top 正在计算边缘旁边的区域并通过打开打破。而底部是在计算整个图像?蓝色区域表示实际计数的区域。因为边缘检测有中断,所以这个区域实际上很小。边缘在几个点上部分失败是很常见的。

如果假设有一些像素中断(你的线不连续),这个假设的结果符合你的描述

一个。面积很小,

乙。将弧长和顶点数加倍

C。有些点是重复的,因为它们在同一条线上。

处理这个开口是使用形态学膨胀或凸包来缩小间隙。