我有下一个二进制掩码:
如您所见,曲线端点之间存在小间隙。我如何连接它们,而不连接接近/平行的轮廓
我最终得到了代码:
import cv2
import numpy as np
import random
def pointDist(a, b):
return np.linalg.norm(np.subtract(a, b))
img = cv2.imread('mask.png')
img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
contours, _ = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = list( map(lambda c: cv2.approxPolyDP(c, 4, True), contours) )
points = [ (i, tuple(pt)) for i, c in enumerate(contours) for [pt] in c ]
nearestContoursPoints = []
checkedContours = set()
for i, c in enumerate(contours):
checkedContours.add(i)
color = (random.randint(120, 255), random.randint(120, 255), random.randint(120, 255))
cv2.drawContours(img, [c], -1, color, 2)
pts = [pt[1] for pt in points if pt[0] not in checkedContours]
if not pts: break
for [pt] in c:
nearest = min(pts, key=lambda b: pointDist(pt, b))
if pointDist(pt, nearest) <= 15:
cv2.line(img, tuple(pt), tuple(nearest), (0, 0, 255), 3)
cv2.imshow('', img)
这段代码几乎完美地解决了这个问题,但没有考虑点是否是曲线的端点
经过多次尝试,我终于找到了在最近的点之间具有最锐角的轮廓点。唉,通用解决方案不起作用,您需要选择平滑级别
我将此函数应用于图像,如下所示:
然后,我将点分组为簇(可选步骤,这将加快处理速度):
最后,我介绍了以下在组中选择点对的算法:
接下来的任务是检查轮廓的兼容性,这样小球就不会粘在一起,这不适用于原始问题
我希望这个解决方案能帮助其他人
相关问题 更多 >
编程相关推荐