In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip "raw-lines-example.mp4" (also contained in this repository) to see what the output should look like after using the helper functions below.
Once you have a result that looks roughly like "raw-lines-example.mp4", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.
Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the "play" button above) to display the image.
Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the "Kernel" menu above and selecting "Restart & Clear Output".
The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.
Run the cell below to import some packages. If you get an import error
for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, see this forum post for more troubleshooting tips.
In [1]:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
In [2]:
#reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dimesions:', image.shape)
#plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')
plt.imshow(image,cmap='gray')
Out[2]:
In [3]:
#whos
#%reset
Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:
cv2.inRange()
for color selection
cv2.fillPoly()
for regions selection
cv2.line()
to draw lines on an image given endpoints
cv2.addWeighted()
to coadd / overlay two images
cv2.cvtColor()
to grayscale or change color
cv2.imwrite()
to output images to file
cv2.bitwise_and()
to apply a mask to an image
Check out the OpenCV documentation to learn about these and discover even more awesome functionality!
Below are some helper functions to help get you started. They should look familiar from the lesson!
In [13]:
import math
import code
from itertools import cycle
class Line_with_info:
def __init__(self, x1, y1,x2,y2):
self.x1 = x1
self.y1 = y1
self.x2=x2
self.y2=y2
self.slope=(self.y2-self.y1)/(self.x2-self.x1)
self.slope_angle=math.atan(self.slope)
def get_line(self):
points_data=[[self.x1,self.y1,self.x2,self.y2]];
#code.interact(local=locals())
#Use raise SystemExit
return points_data
def get_slope(self):
return self.slope
def get_slope_angle(self):
return self.slope_angle
def get_distance(x1,y1,x2,y2):
return math.sqrt(math.pow((x2-x1),2)+math.pow((y2-y1,2)))
def get_slope(x1,y1,x2,y2):
return abs(math.atan(abs((y2-y1))/abs((x2-x1))))
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def draw_lines(img, lines,y_min=350,y_max=550, color=[255, 0, 0], thickness=12,theta_tolerance_deg=3,angle_upper_limit_deg=40,angle_lower_limit=25):
"""
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
"""
#for line in lines:
#for x1,y1,x2,y2 in line:
#cv2.line(img, (x1, y1), (x2, y2), [0,255,0], thickness)
#Angle tolerance used to divide lines into groups
theta_tolerance=math.radians(theta_tolerance_deg)
#Angule limits of the lanes (absolute)
angle_upper_limit=math.radians(40)
angle_lower_limit=math.radians(25)
#Wrap lines in objects and sort them
lines_objects=[]
for line in lines:
for x1,y1,x2,y2 in line:
g=Line_with_info(x1,y1,x2,y2)
lines_objects.append(Line_with_info(x1,y1,x2,y2))
#print("Slope %s"%math.degrees(g.get_slope()))
#print("Coordinates %s,%s,%s,%s"%(x1,y1,x2,y2))
sorted_lines=sorted(lines_objects, key=lambda Line_with_info: Line_with_info.get_slope_angle())
#Initialize vars
first_lane_group=[]
second_lane_group=[]
sorted_left_lane=[]
sorted_right_lane=[]
first_group_done=False
second_group_done=False
bnd_x_min_left=0
bnd_x_max_left=0
bnd_x_min_right=0
bnd_x_max_right=0
Left_lane_used=False
Right_lane_used=False
#Divide lanes into two groups based on slope
for i,asc_line in enumerate(sorted_lines[:-1]):
if not(first_group_done):
if (abs(sorted_lines[i+1].slope_angle-asc_line.slope_angle)<theta_tolerance):
first_lane_group.append(asc_line)
first_lane_group.append(sorted_lines[i+1])
#print("avg_slope_1 %s"%asc_line.slope_angle)
#print("avg_slope_2 %s"%sorted_lines[i+1].slope_angle)
#print("Coordinates 1 %s,%s,%s,%s"%(asc_line.x1,asc_line.y1,asc_line.x2,asc_line.y2))
#print("Coordinates 2 %s,%s,%s,%s"%(sorted_lines[i+1].x1,sorted_lines[i+1].y1,sorted_lines[i+1].x2,sorted_lines[i+1].y2))
else:
#print("Pass")
if (len(first_lane_group)>0):
#print("Done first group")
first_group_done=True
elif not(second_group_done):
if (abs(sorted_lines[i+1].slope_angle-asc_line.slope_angle)<theta_tolerance):
second_lane_group.append(asc_line)
second_lane_group.append(sorted_lines[i+1])
#print("avg_slope_1 %s"%asc_line.slope_angle)
#print("avg_slope_2 %s"%sorted_lines[i+1].slope_angle)
#print("Coordinates 1 %s,%s,%s,%s"%(asc_line.x1,asc_line.y1,asc_line.x2,asc_line.y2))
#print("Coordinates 2 %s,%s,%s,%s"%(sorted_lines[i+1].x1,sorted_lines[i+1].y1,sorted_lines[i+1].x2,sorted_lines[i+1].y2))
else:
#print("Pass")
if (len(second_lane_group)>0):
#print("Done Second group")
second_group_done=True
#Sort lines in groups
sorted_first_lines=sorted(first_lane_group, key=lambda Line_with_info: Line_with_info.x1)
sorted_second_lines=sorted(second_lane_group, key=lambda Line_with_info: Line_with_info.x1)
#Identify left-lane group and right lane group
if (len(first_lane_group)>0):
avg_slope_1=sum(fst_lane_grp.get_slope() for fst_lane_grp in first_lane_group)/float(len(first_lane_group))
if (avg_slope_1<0):
sorted_left_lane=first_lane_group
else:
sorted_right_lane=first_lane_group
if (len(sorted_left_lane)>0):
if (len(second_lane_group)>0):
sorted_right_lane=sorted_second_lines
#Average slopes and position. Use linear extrapolation to draw a line across
if (len(sorted_left_lane)>0):
#print("first_lane_group")
avg_slope_left=sum(left_lane_grp.get_slope() for left_lane_grp in sorted_left_lane)/float(len(sorted_left_lane))
gh=math.atan(avg_slope_left)
if (abs(gh)>angle_upper_limit)or(abs(gh)<angle_lower_limit):
cv2.line(img, (draw_lines.prev_coord_left[0], y_max), (draw_lines.prev_coord_left[1], y_min), color, thickness)
else:
avg_x1_left=sum(left_lane_grp.x1 for left_lane_grp in sorted_left_lane)/float(len(sorted_left_lane))
avg_y1_left=sum(left_lane_grp.y1 for left_lane_grp in sorted_left_lane)/float(len(sorted_left_lane))
if (abs(avg_slope_left)<0.0001):
bnd_x_min_left=y_min
bnd_x_max_left=y_max
else:
bnd_x_min_left=-(1/avg_slope_left)*(avg_y1_left-y_min)+avg_x1_left
bnd_x_max_left=-(1/avg_slope_left)*(avg_y1_left-y_max)+avg_x1_left
#print("avg_slope_1 %s"%avg_slope_1)
#print("avg_x1_1 %s"%avg_x1_1)
#print("avg_y1_1 %s"%avg_y1_1)
#gh=math.degrees(math.atan(avg_slope_left))
#print("Angle Left %s"%gh)
Left_lane_used=True
cv2.line(img, (int(bnd_x_max_left), y_max), (int(bnd_x_min_left), y_min), color, thickness)
else:
#print("Left from memory")
cv2.line(img, (draw_lines.prev_coord_left[0], y_max), (draw_lines.prev_coord_left[1], y_min), color, thickness)
#Average slopes and position. Use linear extrapolation to draw a line across
if (len(sorted_right_lane)>0):
#print("second_lane_group")
avg_slope_right=sum(right_lane_grp.get_slope() for right_lane_grp in sorted_right_lane)/float(len(sorted_right_lane))
gh=math.atan(avg_slope_right)
if (abs(gh)>angle_upper_limit)or(abs(gh)<angle_lower_limit):
cv2.line(img, (draw_lines.prev_coord_right[0], y_max), (draw_lines.prev_coord_right[1], y_min), color, thickness)
else:
avg_x1_right=sum(right_lane_grp.x1 for right_lane_grp in sorted_right_lane)/float(len(sorted_right_lane))
avg_y1_right=sum(right_lane_grp.y1 for right_lane_grp in sorted_right_lane)/float(len(sorted_right_lane))
if (abs(avg_slope_right)<0.0001):
bnd_x_min_right=y_min
bnd_x_max_right=y_max
else:
bnd_x_min_right=-(1/avg_slope_right)*(avg_y1_right-y_min)+avg_x1_right
bnd_x_max_right=-(1/avg_slope_right)*(avg_y1_right-y_max)+avg_x1_right
#print("avg_slope_2 %s"%avg_slope_2)
#print("avg_x1_2 %s"%avg_x1_2)
#print("avg_y1_2 %s"%avg_y1_2)
#print("Angle Right %s"%gh)
Right_lane_used=True
cv2.line(img, (int(bnd_x_max_right), y_max), (int(bnd_x_min_right), y_min), color, thickness)
else:
#print("Right from memory")
cv2.line(img, (draw_lines.prev_coord_right[0], y_max), (draw_lines.prev_coord_right[1], y_min), color, thickness)
#Decide weather to update memory lanes or not
if (len(sorted_left_lane)>0)and Left_lane_used:
draw_lines.prev_slope_left=avg_slope_left
draw_lines.prev_coord_left=[int(bnd_x_max_left),int(bnd_x_min_left)]
if (len(sorted_right_lane)>0) and Right_lane_used:
draw_lines.prev_slope_right=avg_slope_right
draw_lines.prev_coord_right=[int(bnd_x_max_right),int(bnd_x_min_right)]
draw_lines.prev_coord_left=[0,0]
draw_lines.prev_coord_right=[0,0]
draw_lines.prev_slope_left=0
draw_lines.prev_slope_right=0
draw_lines.counter=0
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap,y_min=350,y_max=550):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn.
"""
lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
#Step6:
draw_lines(line_img, lines,y_min,y_max)
return line_img
# Python 3 has support for cool math symbols.
def weighted_img(img, initial_img, α=0.8, β=1., λ=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * α + img * β + λ
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, α, img, β, λ)
In [14]:
import os
os.listdir("test_images/")
Out[14]:
run your solution on all test_images and make copies into the test_images directory).
In [15]:
import math
# TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images directory.
#Step1: Graying
image = mpimg.imread('test_images/solidWhiteRight.jpg')
image_gray_unfiltered=grayscale(image)
#Step2: Filteration
imshape=image_gray_unfiltered.shape
kernel_size = 5
blur_gray = gaussian_blur(image_gray_unfiltered,kernel_size)
#Step3: Edge detection
low_threshold = 50
high_threshold = 120
edges = canny(blur_gray, low_threshold, high_threshold) #returns array edges same size of image_gray
#Step4: Region masking
low_y_limit=320
vertices = np.array([[(50,imshape[0]),(450, low_y_limit), (500, low_y_limit), (imshape[1],imshape[0])]], dtype=np.int32)
masked_edges=region_of_interest(edges,vertices)
#Step5: Line detection
rho = 1 # distance resolution in pixels of the Hough grid
theta = np.pi/180 # angular resolution in radians of the Hough grid
threshold = 15 # minimum number of votes (intersections in Hough grid cell)
min_line_length = 40 #minimum number of pixels making up a line
max_line_gap = 10 # maximum gap in pixels between connectable line segments
line_image=hough_lines(masked_edges,rho, theta, threshold,min_line_length,max_line_gap,low_y_limit,imshape[0])
#Displaying
color_edges = np.dstack((edges, edges, edges))
lines_edges = weighted_img(line_image, color_edges, 0.8, 1, 0)
f, axarr = plt.subplots(2,figsize=(15,15))
axarr[0].imshow(image, cmap='gray')
axarr[1].imshow(lines_edges)
Out[15]:
You know what's cooler than drawing lanes over images? Drawing lanes over video!
We can test our solution on two provided videos:
solidWhiteRight.mp4
solidYellowLeft.mp4
Note: if you get an import error
when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, check out this forum post for more troubleshooting tips.
If you get an error that looks like this:
NeedDownloadError: Need ffmpeg exe.
You can download it by calling:
imageio.plugins.ffmpeg.download()
Follow the instructions in the error message and check out this forum post for more troubleshooting tips across operating systems.
In [7]:
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
In [8]:
def process_image(image):
# NOTE: The output you return should be a color image (3 channel) for processing video below
# TODO: put your pipeline here,
# you should return the final output (image with lines are drawn on lanes)
image_gray_unfiltered=grayscale(image)
kernel_size = 5
blur_gray = gaussian_blur(image_gray_unfiltered,kernel_size)
low_threshold = 50
high_threshold = 120
edges = canny(blur_gray, low_threshold, high_threshold) #returns array edges same size of image_gray
masked_edges=region_of_interest(edges,vertices)
rho = 1 # distance resolution in pixels of the Hough grid
theta = np.pi/180 # angular resolution in radians of the Hough grid
threshold = 15 # minimum number of votes (intersections in Hough grid cell)
min_line_length = 40 #minimum number of pixels making up a line
max_line_gap = 10 # maximum gap in pixels between connectable line segments
line_image=hough_lines(masked_edges,rho, theta, threshold,min_line_length,max_line_gap)
color_edges = np.dstack((edges, edges, edges))
lines_edges = weighted_img(line_image, image, 0.8, 1, 0)
return lines_edges
Let's try the one with the solid white lane on the right first ...
In [9]:
white_output = 'solidWhiteRight-Result.mp4'
clip1 = VideoFileClip("solidWhiteRight.mp4")
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
%time white_clip.write_videofile(white_output, audio=False)
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.
In [10]:
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output))
Out[10]:
At this point, if you were successful you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. Modify your draw_lines function accordingly and try re-running your pipeline.
Now for the one with the solid yellow lane on the left. This one's more tricky!
In [27]:
yellow_output = 'solidYellowLeft-Result.mp4'
clip2 = VideoFileClip('solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)
In [28]:
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(yellow_output))
Out[28]:
Congratulations on finding the lane lines! As the final step in this project, we would like you to share your thoughts on your lane finding pipeline... specifically, how could you imagine making your algorithm better / more robust? Where will your current algorithm be likely to fail?
Please add your thoughts below, and if you're up for making your pipeline more robust, be sure to scroll down and check out the optional challenge video below!
In [11]:
challenge_output = 'extra.mp4'
clip2 = VideoFileClip('challenge.mp4')
challenge_clip = clip2.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)
In [12]:
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output))
Out[12]:
In [ ]: