How to merge nearby Lines in HoughlineP opencv

十年热恋 提交于 2021-01-29 14:58:18

问题


I am trying to detect crop-rows using Segmentation and HoughLines and I have a script from github that I am trying to modify.

A merging function was applied after the HoughLines to merge lines that are close to each other based on distance

But I don't seems to understand the reason for that.

from what I can tell multiple lines where detected for individual crop-row even after varying the HoughLine parameters. So merging the lines was a way to optimize the result of the HoughLine process.

def draw_lines(image,mask):
    mask = mask*255
    mask = cv2.GaussianBlur(mask,(5,5),1)
    mask = cv2.Canny(mask.astype(np.uint8),80,255)
    lines = cv2.HoughLinesP(mask,1,np.pi / 180,threshold=50,
                        minLineLength=50,maxLineGap=250)
    lines = np.squeeze(lines, axis=1)
    
    for line in lines:
        x1, y1, x2, y2 = line.astype(int)
        cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
    
    return image

image result from Houghline method test_1, test_2

.

Here is the merging function

##merge lines that are near to each other based on distance
from numpy.polynomial import polynomial as P
def merge_lines(lines):
    clusters =  []
    idx = []
    total_lines = len(lines)
    if total_lines < 30:
        distance_threshold = 20
    elif total_lines <75:
        distance_threshold = 15
    elif total_lines<120:
        distance_threshold = 10
    else:
        distance_threshold = 7
    for i,line in enumerate(lines):
        x1,y1,x2,y2 = line
        if [x1,y1,x2,y2] in idx:
            continue
        parameters = P.polyfit((x1, x2),(y1, y2), 1)
        slope = parameters[0]#(y2-y1)/(x2-x1+0.001)
        intercept = parameters[1]#((y2+y1) - slope *(x2+x1))/2
        a = -slope
        b = 1
        c = -intercept
        d = np.sqrt(a**2+b**2)
        cluster = [line]
    for d_line in lines[i+1:]:
        x,y,xo,yo= d_line
        mid_x = (x+xo)/2
        mid_y = (y+yo)/2
        distance = np.abs(a*mid_x+b*mid_y+c)/d
        if distance < distance_threshold:
            cluster.append(d_line)
            idx.append(d_line.tolist())
    clusters.append(np.array(cluster))
    merged_lines = [np.mean(cluster, axis=0) for cluster in clusters]
    return merged_lines

来源:https://stackoverflow.com/questions/65708420/how-to-merge-nearby-lines-in-houghlinep-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!