用cv2在python中连接角点的线

2024-10-03 00:24:38 发布

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

我正在寻找在手绘图像like this上连接角的线条。我用哈里斯角点检测来找到图像的角点。接下来,我将用线条连接所有的角点,并遍历这些点,看看它们是否与原始图像中的像素相匹配,并为每一行像素覆盖设置一个阈值,以说明什么是连接角点的正确线。Image of connected lines。它起作用了。。。但速度很慢。有更好的方法吗?或者我应该用不同的方法?(霍夫线不会工作,因为可能会有曲线,我只想要连接角落的线条。在

for i in c_corners: #corners thru harris and coorected with subpix
    x1,y1 = i.ravel()
    for k in c_corners:
        x2,y2 = k.ravel()
        if x1 != x2 and y1 != y2: #ignore vertical lines 
            linePoints = line_points(x1,y1, x2,y2) # function to get line pnts
            totalLinePoints = len(linePoints)
            coverPoints = 0

########## This is where I think the slow down is happening and could be optimized

            for m in originalImage: #image is dialated to help detection
                for n in linePoints:
                    match = np.all(m == n)
                    if match == True:
                        coverPoints += 1 
            print("Line Cover = ", (coverPoints/totalLinePoints))
            if (coverPoints/totalLinePoints) > .65:
                good_lines.append([x1,y1,x2,y2])

感谢您的帮助,谢谢!在


Tags: andin图像forif线条linesx1
1条回答
网友
1楼 · 发布于 2024-10-03 00:24:38

我最初的方法是创建一个空白图像并在其上绘制每一行,然后使用cv2.bitwise_and()与二进制(放大)图像一起计算有多少像素是一致的,如果它们满足阈值,则在原始图像上绘制这些线。然而,设置像素数的阈值会使小行受到惩罚。一个更好的指标应该是正确匹配与错误匹配的数量之比(我现在意识到这正是您实际在做的)。此外,这是一个更稳健的扩张和线的厚度,你选择绘制你的线。在

但是,您所使用的一般方法对于绘图中的问题不是很可靠,因为许多绘制的曲线可能会碰到一条线段,因此,像这条这样的合成线可能很容易拟合不属于它们的直线。您可以在我的代码输出中看到此问题:

Marked lines between edges

我只是硬编码了一些角落的估计,然后从那里开始。注意使用itertools来帮助创建所有可能的点对来定义线段。在

import cv2
import numpy as np
import itertools

img = cv2.imread('drawing.png')
bin_inv = cv2.bitwise_not(img) # flip image colors
bin_inv = cv2.cvtColor(bin_inv, cv2.COLOR_BGR2GRAY) # make one channel
bin_inv = cv2.dilate(bin_inv, np.ones((5,5)))

corners = ((517, 170),
    (438, 316),
    (574, 315),
    (444, 436),
    (586, 436))

lines = itertools.combinations(corners,2) # create all possible lines
line_img = np.ones_like(img)*255 # white image to draw line markings on
for line in lines: # loop through each line
    bin_line = np.zeros_like(bin_inv) # create a matrix to draw the line in
    start, end = line # grab endpoints
    cv2.line(bin_line, start, end, color=255, thickness=5) # draw line
    conj = (bin_inv/255 + bin_line/255) # create agreement image
    n_agree = np.sum(conj==2)
    n_wrong = np.sum(conj==1)
    if n_agree/n_wrong > .05: # high agreements vs disagreements
        cv2.line(line_img, start, end, color=[0,200,0], thickness=5) # draw onto original img

# combine the identified lines with the image
marked_img = cv2.addWeighted(img, .5, line_img, .5, 1)
cv2.imwrite('marked.png', marked_img)

我尝试了很多不同的设置(玩厚度,膨胀,不同的比例,等等),但没有得到虚假的较长的线出现。它非常适合原始的黑色像素,所以我不确定如果你使用这种方法,你将如何摆脱它。它有一条右上角的曲线,还有它穿过的中线,右下角的曲线,这条曲线有点倾向于这个方向。不管怎样,这只需要两秒钟就可以运行,所以至少比您当前的代码快。在

相关问题 更多 >