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.
In [2]:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
In [3]:
#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) #call as plt.imshow(gray, cmap='gray') to show a grayscaled image
Out[3]:
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 [22]:
import math
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
you should call plt.imshow(gray, cmap='gray')"""
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, color=[255, 0, 0], thickness=2):
"""
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), color, thickness)
def dist(x1,x2,y1,y2):
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
# Global variable, param w and b updated through time
global_w_left = -1
global_b_left = 1
global_w_right = 1
global_b_right = 1
Global_First_Frame = True # for video test, when it is the first frame, we need to initilize param w and b
def fit_lines(img, lines, slope_th=0.5, line_len_ratio=0.08, alpha_w=0.1, alpha_b=0.1):
global global_w_left
global global_b_left
global global_w_right
global global_b_right
global Global_First_Frame
# define the position parameters
ysize = img.shape[0]
xsize = img.shape[1]
y_bottom = ysize-1
x_left = xsize*0.5
x_right = xsize*0.5
length_th = line_len_ratio*ysize
# assign the lines to left and right according to their positions
left_lines_x = []
left_lines_y = []
left_len = 0
right_lines_x = []
right_lines_y = []
right_len = 0
for line in lines:
x1 = line[0][0]
y1 = line[0][1]
x2 = line[0][2]
y2 = line[0][3]
if x1<x_left and x2<x_left:
slope = (y2-y1)/(x2-x1)
if slope < -abs(slope_th): # note the origin is on the left top
left_lines_x.append(x1)
left_lines_x.append(x2)
left_lines_y.append(y1)
left_lines_y.append(y2)
left_len += dist(x1,x2,y1,y2)
elif x1>x_right and x2>x_right:
slope = (y2-y1)/(x2-x1)
if slope > abs(slope_th):
right_lines_x.append(x1)
right_lines_x.append(x2)
right_lines_y.append(y1)
right_lines_y.append(y2)
right_len += dist(x1,x2,y1,y2)
# define the top positions of the lines
#y_top_left = min(left_lines_y)
#y_top_right = min(right_lines_y)
y_top_left = ysize/2+50
y_top_right = ysize/2+50
#
left_line = np.array([[0,0,0,0]])
right_line = np.array([[0,0,0,0]])
# fit the left points with line
if Global_First_Frame == True:
z = np.polyfit(left_lines_x, left_lines_y, 1) # y=z[0]x+z[1] --> x=(y-z[1])/z[0]
global_w_left = z[1]
global_b_left = z[0]
elif left_len>length_th:
z = np.polyfit(left_lines_x, left_lines_y, 1) # y=z[0]x+z[1] --> x=(y-z[1])/z[0]
if z[0]<-abs(slope_th):
global_w_left = (1-alpha_w)*global_w_left + alpha_w*z[1] # adapt w
global_b_left = (1-alpha_b)*global_b_left + alpha_b*z[0] # adapt b
left_line[0][0] = (y_top_left-global_w_left)/global_b_left
left_line[0][1] = y_top_left
left_line[0][2] = (y_bottom-global_w_left)/global_b_left
left_line[0][3] = y_bottom
# fit the right points with line
# print(right_lines_x)
if Global_First_Frame == True:
z = np.polyfit(right_lines_x, right_lines_y, 1) # y=z[0]x+z[1] --> x=(y-z[1])/z[0]
global_w_right = z[1]
global_b_right = z[0]
elif right_len>length_th:
z = np.polyfit(right_lines_x, right_lines_y, 1) # y=z[0]x+z[1] --> x=(y-z[1])/z[0]
if z[0]>abs(slope_th):
global_w_right = (1-alpha_w)*global_w_right + alpha_w*z[1] # adapt w
global_b_right = (1-alpha_b)*global_b_right + alpha_b*z[0] # adapt w
right_line[0][0] =(y_top_left-global_w_right)/global_b_right
right_line[0][1] = y_top_right
right_line[0][2] = (y_bottom-global_w_right)/global_b_right
right_line[0][3] = y_bottom
#
Global_First_Frame = False
return left_line, right_line
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`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)
left_line, right_line = fit_lines(img, lines)
line_img = np.zeros((*img.shape, 3), dtype=np.uint8)
draw_lines(line_img, np.array([left_line, right_line]), thickness=5)
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 [19]:
import os
imgdir = "test_images/"
os.listdir(imgdir)
for filename in os.listdir(imgdir):
img = mpimg.imread(os.path.join(imgdir, filename))
plt.figure()
plt.imshow(img)
#
gray = grayscale(img)
blur = gaussian_blur(gray, 3)
edge = canny(blur, 50, 130)
#
ysize = img.shape[0]
xsize = img.shape[1]
vertices = np.array([[(xsize*0.13,ysize*0.9),(xsize*0.87, ysize*0.9), (xsize/2+20, ysize/2+40), (xsize/2-20, ysize/2+40)]], dtype=np.int32)
roi_edge = region_of_interest(edge, vertices)
plt.figure()
plt.imshow(roi_edge, cmap='gray')
#
rho = 1 # distance resolution in pixels of the Hough grid
theta = 1*np.pi/180 # angular resolution in radians of the Hough grid
threshold = 15 # minimum number of votes (intersections in Hough grid cell)
min_line_len = 20 #minimum number of pixels making up a line
max_line_gap = 20 # maximum gap in pixels between connectable line segments
Global_First_Frame = True
line_img = hough_lines(roi_edge, rho, theta, threshold, min_line_len, max_line_gap)
#
result_img = weighted_img(line_img, img, α=0.8, β=1., λ=0.)
plt.figure()
plt.imshow(result_img)
run your solution on all test_images and make copies into the test_images directory).
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(img):
# 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)
gray = grayscale(img)
blur = gaussian_blur(gray, 3)
edge = canny(blur, 50, 130)
# plt.figure()
# plt.imshow(edge, cmap='gray')
#
ysize = img.shape[0]
xsize = img.shape[1]
vertices = np.array([[(xsize*0.13,ysize*0.9),(xsize*0.87, ysize*0.9), (xsize/2+20, ysize/2+40), (xsize/2-20, ysize/2+40)]], dtype=np.int32)
roi_edge = region_of_interest(edge, vertices)
# plt.figure()
# plt.imshow(roi_edge, cmap='gray')
#
rho = 1 # distance resolution in pixels of the Hough grid
theta = 1*np.pi/180 # angular resolution in radians of the Hough grid
threshold = 10 # minimum number of votes (intersections in Hough grid cell)
min_line_len = 15 #minimum number of pixels making up a line
max_line_gap = 25 # maximum gap in pixels between connectable line segments
line_img = hough_lines(roi_edge, rho, theta, threshold, min_line_len, max_line_gap)
#
result = weighted_img(line_img, img, α=0.8, β=1., λ=0.)
# plt.figure()
# plt.imshow(result)
return result
Let's try the one with the solid white lane on the right first ...
In [9]:
white_output = 'white.mp4'
clip1 = VideoFileClip("solidWhiteRight.mp4")
Global_First_Frame = True
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 [11]:
yellow_output = 'yellow.mp4'
clip2 = VideoFileClip('solidYellowLeft.mp4')
Global_First_Frame = True
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)
In [12]:
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(yellow_output))
Out[12]:
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!
Reflections: Here, I use the traditional image processing methods to detect the lines. The pipeline is Grayscale --> Gaussian Blur --> Canny Edge Detection --> ROI --> Hough Transform Line Detection --> Fit Lines With Slope. The fore stages should guarantee that all lines be detected, and the later stages should remove the noise as much as possibile. It is useful in simple situations. But when in more complex scenes such as occlusions, bent roads, snowy or rainy weather, there will be more noises which may lead to failure. I imagine the temporal infomation can help to reduce the noisy and overcome the occlusions to make the detection more smooth temporally. Besides, there are too many hyperparameters here, which limits the generation ability of the methods. I think the data-driven machine learning method or other adaptive can solve it.
In [23]:
challenge_output = 'extra.mp4'
clip2 = VideoFileClip('challenge.mp4')
Global_First_Frame = True
# myclip = VideoFileClip("challenge.mp4").subclip(4, 5)
challenge_clip = clip2.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)
In [24]:
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output))
Out[24]:
In [ ]:
In [ ]: