我有一个这样的图像,它有多个塞子,有些线断了。为了连接这条折线,我使用了如下形态操作:
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
最佳答案
createFastLineDetector
来检测每行。 初始化线路检测器
我们将使用
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.82
,y1=78.90
,x2=90.89
和y2=120.78
分别。 计算斜率
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
比较坡度
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()
if not equal_arrays:
neighbor_slope = calculate_slope(neighbor_line[0])
neighbor
到current
和current
到neighbor
。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)
结果
可能的问题但是,为什么不能连接以下部分?
回答
好吧,红色虚线的斜率不相等。因此,我无法连接它们。
可能的问题您为什么不使用
dilate
和erode
方法?如here所示回答
我试过了,但结果并不令人满意。
关于python - 如何连接侵 eclipse 和膨胀无法连接的虚线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63727525/