'How to merge nearby Lines in HoughlineP opencv

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


Solution 1:[1]

I did this by sorting the list of hough lines by angle first. Then, I would iterate through the sorted list and evaluate/average rho to a given pre-set rho-tolerance. When the angle changes more than a pre-set given theta-tolerance, then I would restart the rho-tolerance evaluation. When implmenting the function, look out for angles greater than 90 which produce a negative rho, in your tolerance analysis. The function ultimately takes a list of lines, a rho-tolerance and a theta-tolerance as inputs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ediaz