met*_*met 5 python opencv image-processing
我有一个像这样的图像,有多个塞子,并且有些线条已损坏。为了连接这条断线,我使用了如下的形态学操作:
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))
Run Code Online (Sandbox Code Playgroud)
但这并没有连接我的断线。如何连接线路而不影响其他线路?
图像
换行符是图像中心两条小线之间的换行符。只有不连续部分没有圆角端部。
应用形态学运算
createFastLineDetector检测每条线。初始化线检测器
我们将使用ximgproc库来检测线条。
import cv2
img = cv2.imread("lines.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
d = cv2.ximgproc.createFastLineDetector()
lines = d.detect(gray)
Run Code Online (Sandbox Code Playgroud)
lines变量分别返回类似的值,例如[[14.82, 78.90, 90.89, 120.78]]where x1=14.82、y1=78.90、。x2=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
Run Code Online (Sandbox Code Playgroud)
比较坡度
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()
Run Code Online (Sandbox Code Playgroud)
if not equal_arrays:
neighbor_slope = calculate_slope(neighbor_line[0])
Run Code Online (Sandbox Code Playgroud)
neighbor到current到。
currentneighborif 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)
Run Code Online (Sandbox Code Playgroud)
结果
可能的问题但是为什么您无法连接以下部件?
回答
嗯,红色虚线的斜率不相等。因此我无法连接它们。
可能的问题为什么不使用dilateanderode方法?如这里所示
回答
我尝试过,但结果并不令人满意。