I have this code I am trying to wrap my head around that detect plant Crop-row using segmentation and HoughLine method.
I understand the segmentation and the HoughLineP part very well. But I get stuck on how to merge the lines outputted from the HoughLineP method.
My Question are
- Why would we want to merge the lines detected by HoughlinesP method
- What are the possible way to merge this line.. a link to any material would be greatly appreciated
I stumble on a similar question stackoverflow but there wasn't much explanation just bunch of code
without the merging part here is the output of the HoughlineP on the test image test_image
HoughLineP method
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)
m_lines = merge_lines(lines)
for line in m_lines:
x1, y1, x2, y2 = line.astype(int)
cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
return image
#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]
print(clusters)
print(merged_lines)
return merged_lines
I understand how the slope and intercept was obtain in the merging function.. but the rest of the code I don't understand.