如何连接因侵蚀和膨胀而无法连接的虚线?

2024-04-18 02:51:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的图像,有多个塞子,一些线断了。为了连接这条虚线,我使用了如下形态学操作:

import cv2
import numpy as np

img = cv2.imread('sample.png', cv2.IMREAD_GRAYSCALE)
morph = cv2.morphologyEx(im, cv2.MORPH_CLOSE, np.ones((10,10),np.uint8))

但这并没有连接我的断线。如何连接线路而不影响其他线路

img

换行符是图像中心两条小线之间的换行符。只有不连续的部分没有圆角

image

应用形态学运算

applied morphological operation


Tags: sample图像importnumpyimgpngasnp
1条回答
网友
1楼 · 发布于 2024-04-18 02:51:09
    1. 您可以使用createFastLineDetector来检测每一行

    1. 计算当前线和相邻线的坡度

    1. 如果当前线和相邻线的坡度相同,则绘制线

初始化线路检测器


我们将使用ximgproc库来检测行

import cv2

img = cv2.imread("lines.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
d = cv2.ximgproc.createFastLineDetector()
lines = d.detect(gray)
  • lines变量分别返回类似的值,如[[14.82, 78.90, 90.89, 120.78]]其中x1=14.82y1=78.90x2=90.89y2=120.78

计算坡度


  • 直线的斜率通过以下公式计算:m=(y2-y1)/(x2-x1

  • 对于给定的直线对象,获取坐标并返回坡度

  • def calculate_slope(line_object):
        x_point1 = line_object[0]
        y_point1 = line_object[1]
        x_point2 = line_object[2]
        y_point2 = line_object[3]
    
        m = abs((y_point2 - y_point1) / (x_point2 - x_point1))
        m = float("{:.2f}".format(m))
        return m
    

比较坡度


    1. 检查线条是否相等。如果点相等,则表示它们是同一条线
    • for current_line in lines:
           current_slope = calculate_slope(current_line[0])
      
           for neighbor_line in lines:
               current_x1 = int(current_line[0][0])
               current_y1 = int(current_line[0][1])
               current_x2 = int(current_line[0][2])
               current_y2 = int(current_line[0][3])
      
               compare_lines = current_line == neighbor_line[0]
               equal_arrays = compare_lines.all()
      
    1. 如果直线不相等,请计算相邻直线的坡度。
      if not equal_arrays:
          neighbor_slope = calculate_slope(neighbor_line[0])
      
    1. 如果坡度相等,则绘制直线。从neighborcurrentcurrentneighbor
      if abs(current_slope - neighbor_slope) < 1e-3:
          neighbor_x1 = int(neighbor_line[0][0])
          neighbor_y1 = int(neighbor_line[0][1])
          neighbor_x2 = int(neighbor_line[0][2])
          neighbor_y2 = int(neighbor_line[0][3])
      
          cv2.line(img,
                   pt1=(neighbor_x1, neighbor_y1),
                   pt2=(current_x2, current_y2),
                   color=(255, 255, 255),
                   thickness=3)
          cv2.line(img,
                   pt1=(current_x1, current_y1),
                   pt2=(neighbor_x2, neighbor_y2),
                   color=(255, 255, 255),
                   thickness=3)
      

结果


enter image description here

可能的问题但为什么不能连接以下部分

enter image description here

回答

红色虚线的斜率不相等。因此我无法连接它们

可能的问题为什么不使用dilateerode方法?如图here

回答

我试过了,但结果不令人满意

相关问题 更多 >