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.
Your output should look something like this (above) after detecting line segments using the helper functions below
Your goal is to connect/average/extrapolate line segments to get output like this
In [1]:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import glob
import scipy.misc
import cv2
from math import isinf, isnan
%matplotlib inline
from os import chdir; chdir('../')
from lib.image_processing import *
In [2]:
image = mpimg.imread('assets/img/_raw_solidWhiteRight.jpg')
print('This image is:', type(image), 'with dimesions:', image.shape)
plt.imshow(image)
Out[2]:
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 [4]:
image_file = 'processed_solidWhiteCurve.jpg'
raw_image = mpimg.imread('assets/img/_raw_solidWhiteRight.jpg')
imshape = raw_image.shape
plt.imshow(raw_image)
imshape
Out[4]:
In [5]:
this_image = grayscale(raw_image)
plt.imshow(this_image, cmap='gray')
Out[5]:
In [6]:
this_image = gaussian_blur(this_image, kernel_size=7)
plt.imshow(this_image, cmap='gray')
Out[6]:
In [7]:
this_image = canny(this_image, low_threshold=50, high_threshold=100)
plt.imshow(this_image, cmap='gray')
Out[7]:
In [8]:
mask_vertices = np.array([[raw_image.shape[1]*0, raw_image.shape[0]*1],
[raw_image.shape[1]*0.45, raw_image.shape[0]*0.62],
[raw_image.shape[1]*0.55, raw_image.shape[0]*0.62],
[raw_image.shape[1]*1, raw_image.shape[0]*1]],
dtype=np.int32)
this_image = region_of_interest(this_image, vertices=[mask_vertices])
plt.imshow(this_image, cmap='gray')
Out[8]:
In [9]:
lines = cv2.HoughLinesP(this_image,2,np.pi/180,10,
np.array([]),
minLineLength=20,
maxLineGap=5)
lines.shape
Out[9]:
In [10]:
# flatten image tensor
lines = lines.reshape((lines.shape[0], lines.shape[2]))
lines.shape
Out[10]:
In [11]:
y_min = min(lines[:,1].min(),lines[:,3].min())
y_max = imshape[0]
y_min, y_max
Out[11]:
In [12]:
slopes = calculate_slopes(lines)
slopes
Out[12]:
In [13]:
lines_l, lines_r = split_on_side(lines,slopes)
slopes_l, slopes_r = split_on_side(slopes,slopes)
print(lines_l)
print(lines_r)
print(slopes_l)
print(slopes_r)
In [14]:
avg_slope_l = slopes_l.mean()
avg_slope_r = slopes_r.mean()
avg_intercept_l = calculate_intercept(lines_l, avg_slope_l)
avg_intercept_r = calculate_intercept(lines_r, avg_slope_r)
avg_slope_l, avg_slope_r, avg_intercept_l, avg_intercept_r
Out[14]:
In [15]:
lane_line_l = slope_intercept_to_two_points(avg_slope_l, avg_intercept_l, y_min, y_max)
lane_line_r = slope_intercept_to_two_points(avg_slope_r, avg_intercept_r, y_min, y_max)
lane_line_l, lane_line_r
Out[15]:
In [16]:
this_image = np.zeros(this_image.shape, dtype=np.uint8)
draw_line(this_image, lane_line_l)
draw_line(this_image, lane_line_r)
plt.imshow(this_image, cmap='gray')
Out[16]:
In [17]:
this_image = np.dstack([this_image,np.dstack([np.zeros_like(this_image)]*(raw_image.shape[-1]-1))])
plt.imshow(this_image, cmap='gray')
Out[17]:
In [18]:
plt.imshow(weighted_img(this_image, raw_image))
Out[18]:
In [19]:
import os
[image for image in os.listdir("assets/img/") if '_raw_' in image]
Out[19]:
run your solution on all test_images and make copies into the test_images directory).
In [21]:
plt.figure(figsize=(20,20))
plt.imshow(
process_image(
mpimg.imread('assets/img/_raw_solidWhiteRight.jpg')))
Out[21]:
In [22]:
images = glob.glob('../assets/img/*')
plt.figure(figsize=(20,20))
i = 1
for raw_image in images:
if 'raw_' in raw_image:
proc_image = raw_image.replace('_raw_', 'processed_')
this_image = mpimg.imread(raw_image)
this_image_output = process_image(this_image)
scipy.misc.imsave(proc_image, this_image_output)
plt.subplot(1,6,images.index(raw_image)+1)
plt.imshow(this_image_output, cmap='gray')
In [ ]:
from moviepy import ima
In [27]:
from imageio import plugins
plugins.ffmpeg.download()
In [23]:
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
Let's try the one with the solid white lane on the right first ...
In [24]:
white_output = '../assets/videos/processed_solidWhiteRight.mp4'
clip1 = VideoFileClip("../assets/videos/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.
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 [25]:
yellow_output = '../assets/videos/processed_solidYellowLeft.mp4'
clip2 = VideoFileClip('../assets/videos/solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)
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!
My original algorithm is a little jumpy. I wanted to keep it as simple as possible. I didn't want to be hard coding handling for edge cases. Considering this, I am satisfied with the pipeline that I have developed. I do think that with machine learning techniques we will be able to decrease the jumpiness.
I also note that we are searching for lines. It would be better to be able to handle curvature. Perhaps some sort of kernelized hough transform.
My second approach was to split the lines on side and take the mean slope and intercept per side. This works well for all the videos included.
In [26]:
challenge_output = '../assets/videos/processed_challenge.mp4'
clip2 = VideoFileClip('../assets/videos/challenge.mp4')
challenge_clip = clip2.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)
In [ ]: