Skip to content

Instantly share code, notes, and snippets.

@jrjames83
Created December 17, 2016 23:05
Show Gist options
  • Save jrjames83/c67cfa98bc0c87c214ed6e23d954767d to your computer and use it in GitHub Desktop.
Save jrjames83/c67cfa98bc0c87c214ed6e23d954767d to your computer and use it in GitHub Desktop.
def draw_lines(img, lines, color=[255, 0, 0], thickness=5):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that shown in P1_example.mp4).
Think about things like separating line segments by their
slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
line vs. the right line. Then, you can average the position of each of
the lines and extrapolate to the top and bottom of the lane.
This function draws `lines` with `color` and `thickness`.
Lines are drawn on the image inplace (mutates the image).
If you want to make the lines semi-transparent, think about combining
this function with the weighted_img() function below
"""
left_slopes = []
left_x = []
left_y = []
right_slopes = []
right_x = []
right_y = []
for line in lines:
for x1,y1,x2,y2 in line:
#print (x1,y1,x2,y2 )
slope = ((y2 - y1) / (x2 - x1)) + .0000001
if line_distance(x1,y1,x2,y2) > 10 and ((y2 - y1) / (x2 - x1)) < 0:
left_slopes.append(slope)
left_x.append(x1)
left_x.append(x2)
left_y.append(y1)
left_y.append(y2)
if line_distance(x1,y1,x2,y2) > 10 and ((y2 - y1) / (x2 - x1)) > 0:
slope = ((y2 - y1) / (x2 - x1)) + .0000001
right_slopes.append(slope)
right_x.append(x1)
right_x.append(x2)
right_y.append(y1)
right_y.append(y2)
left_mean_x = np.nanmean(left_x)
left_mean_y = np.nanmean(left_y)
left_mean_slope = np.nanmean(left_slopes)
right_mean_x = np.nanmean(right_x)
right_mean_y = np.nanmean(right_y)
right_mean_slope = np.nanmean(right_slopes)
#use mean x,y and mean slope to find the y_intercept(b) y = mx + b so b = y - mx
left_y_int = left_mean_y - (left_mean_slope * left_mean_x)
#find associated x1 for y_global_min using (y_global_min = m_avg * x1 + b )
left_x1 = (320 - left_y_int) / left_mean_slope
left_x2 = (540 - left_y_int) / left_mean_slope
cv2.line(img, (int(left_x1),320), (int(left_x2), 540),(255,0,0),10)
right_y_int = right_mean_y - (right_mean_slope * right_mean_x)
#find associated x1 for y_global_min using (y_global_min = m_avg * x1 + b )
right_x1 = (320 - right_y_int) / right_mean_slope
right_x2 = (540 - right_y_int) / right_mean_slope
cv2.line(img, (int(right_x1),320), (int(right_x2), 540),(255,0,0),10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment