【问题标题】:Join lines to create closed contours using OpenCV使用 OpenCV 连接线以创建闭合轮廓
【发布时间】:2022-04-24 00:13:08
【问题描述】:

我有以下图片:

而且我想加入所有这些“绿色”线性像素来创建边界框轮廓 - 这是否可以通过 opencv 实现?

谢谢

【问题讨论】:

  • 关闭运算符(多次使用)可能会解决问题。它也会影响其他领域,所以它可能不是你想要的。我不太了解 OpenCV,但我想它可以做到这一点。
  • 我已经尝试过这个 Stefan 并且不幸的是似乎对我不起作用。谢谢
  • 另一种方法是使用霍夫变换来检测线条。在这里您将获得检测到的线的截距和斜率。
  • This 可以帮忙吗?

标签: python opencv image-processing contour


【解决方案1】:

我清理了给定的图像并使用以下内容作为输入:

输入图片

执行阈值并找到轮廓:

th = cv2.threshold(img, 150, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(th , cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

现在是有趣的部分!

  • 对于每个轮廓,找到极值点。这些是轮廓的top-mostbottom-mostright-mostleft-most点.
  • 比较一个轮廓的每个极值点与每个其他轮廓的距离
  • 在欧几里得距离最小的点之间画一条线。

代码:

for i in range(len(cnts)):
    min_dist = max(img.shape[0], img.shape[1])
    cl = []
    
    ci = cnts[i]
    ci_left = tuple(ci[ci[:, :, 0].argmin()][0])
    ci_right = tuple(ci[ci[:, :, 0].argmax()][0])
    ci_top = tuple(ci[ci[:, :, 1].argmin()][0])
    ci_bottom = tuple(ci[ci[:, :, 1].argmax()][0])
    ci_list = [ci_bottom, ci_left, ci_right, ci_top]
    
    for j in range(i + 1, len(cnts)):
        cj = cnts[j]
        cj_left = tuple(cj[cj[:, :, 0].argmin()][0])
        cj_right = tuple(cj[cj[:, :, 0].argmax()][0])
        cj_top = tuple(cj[cj[:, :, 1].argmin()][0])
        cj_bottom = tuple(cj[cj[:, :, 1].argmax()][0])
        cj_list = [cj_bottom, cj_left, cj_right, cj_top]
        
        for pt1 in ci_list:
            for pt2 in cj_list:
                dist = int(np.linalg.norm(np.array(pt1) - np.array(pt2)))     #dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
                if dist < min_dist:
                    min_dist = dist             
                    cl = []
                    cl.append([pt1, pt2, min_dist])
    if len(cl) > 0:
        cv2.line(img1, cl[0][0], cl[0][1], (255, 255, 255), thickness = 5)

输出图像:

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2021-07-26
    • 2011-10-03
    • 1970-01-01
    • 2014-11-20
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多