'Group lines with similar slope and y-intercept

In python I am using hough lines to detect lines on an image. It is working pretty well to detect lines, but the source image is hand drawn producing many straight lines over each line segment. I would like to combine lines with similar slope and y intercept to recreate the overall structure of image. I know I can change the hough line parameters (threshold, min_length, max_gap,) to make longer straighter lines but I would like to keep the granular output of the hough line function and remake the structure with the outputted lines

Hough lines of the image looks like this

My current output is a dict with start/end points of lines, slope and y-intercept:

{'slope': -2.0, 'start': (438, 317), 'yintercept': 167.0, 'end': (457, 279)}
{'slope': -8.0, 'start': (580, 414), 'yintercept': 1442.0, 'end': (582, 398)}
{'slope': -5.333333333333333, 'start': (438, 375), 'yintercept': 
{'slope': -1.5, 'start': (492, 215), 'yintercept': 142.5, 'end': (502, 200)}
{'slope': 0.0, 'start': (524, 316), 'yintercept': 152.0, 'end': (536, 316)}
{'slope': 3.0, 'start': (533, 238), 'yintercept': -232.0, 'end': (527, 220)}
{'slope': -1.9142857142857144, 'start': (450, 292), 'yintercept': 164.37142857142857, 'end': (485, 225)}
{'slope': 0.0, 'start': (467, 317), 'yintercept': 153.0, 'end': (523, 317)}

There are 40 lines in the original output but I would like to combine into just 6 lines.

My questions:

  1. What is the best method to groupby both slope and y-intercept?
  2. How do I group by line that are similar and not exact?

I am able to group by exact slope:

grouper = itemgetter("slope")
    result = []
    for key, grp in groupby(sorted(line_dict, key = grouper), grouper):
        result.append(list(grp))

Any help with this is appreciated.



Solution 1:[1]

you can use -

norm = np.linalg.norm(b, ord=2, axis=1) 
#b = array of start and end of lines 
# axis 1 = row
print(norm)

and check if norm is in range or below certain threshold

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 user18083011