Self-Driving Car Engineer Nanodegree

Project: Finding Lane Lines on the Road


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.

In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the rubric points for this project.


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

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.

Import Packages


In [1]:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline

Read in an Image


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')


This image is: <class 'numpy.ndarray'> with dimesions: (540, 960, 3)
Out[2]:
<matplotlib.image.AxesImage at 0x7f41d601c9e8>

Ideas for Lane Detection Pipeline

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!

Helper Functions

Below are some helper functions to help get you started. They should look familiar from the lesson!


In [10]:
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
    (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, draw_lane_ceil=.4, color=[255, 0, 0], thickness=4):
    # aim: getting extrapolated average lane lines from lane fragments we got through hough transform
    # -> get intercepts of the extrapolated hough lines
    
    lane_y_region=1-draw_lane_ceil # using the complement as parameter as it is more understandable (40% from the bottom up are "drawable")
    
    left_bottom_intercepts = []
    right_bottom_intercepts = []
    left_top_intercepts = []
    right_top_intercepts = []
    
    imshape = img.shape    
    
    for line in lines:
        for x1,y1,x2,y2 in line:
            # calc slope for lines for further calculations + decide whether line should be right or left
            slope = (y2-y1)/(x2-x1) # y=m*x+b => b=y-m*x -> x=(y-b)/m y=
            
            intercept = y2-slope*x2
            intercept_bottom = (imshape[0] - intercept)/slope
            intercept_top = (imshape[0]*.6 - intercept)/slope
            if abs(slope) > 0.2 and abs(slope) < 10: # rule out too horizontal/vertical lines
                if slope < 0:
                    left_bottom_intercepts.append(intercept_bottom)
                    left_top_intercepts.append(intercept_top)
                else:
                    right_bottom_intercepts.append(intercept_bottom)
                    right_top_intercepts.append(intercept_top)
                    
    # average intercepts to eliminate double hough lines on around thick lines and merge multiple lane fragments
    avg_left_bottom_intercept = round(np.average(left_bottom_intercepts))
    avg_right_bottom_intercept = round(np.average(right_bottom_intercepts))
    
    avg_left_top_intercept = round(np.average(left_top_intercepts))
    avg_right_top_intercept = round(np.average(right_top_intercepts))

    # draw lines in between the intercepts
    if not np.isnan(avg_left_bottom_intercept) and not np.isnan(avg_left_top_intercept):
        cv2.line(img,
                 (int(avg_left_bottom_intercept), int(imshape[0])),
                 (int(avg_left_top_intercept), int(imshape[0]*lane_y_region)), color, thickness)
    if not np.isnan(avg_right_bottom_intercept) and not np.isnan(avg_right_top_intercept):
        cv2.line(img,
                 (int(avg_right_bottom_intercept), int(imshape[0])),
                 (int(avg_right_top_intercept), int(imshape[0]*lane_y_region)), color, thickness)

def draw_lines_e(img, lines, color=[255, 0, 0], thickness=4):
    """
    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_lines = []
    right_lines = []
    
    for line in lines:
        for x1,y1,x2,y2 in line:
            slope = (y2-y1)/(x2-x1) # y=m*x+b => b=y-m*x -> 
            intercept = y2-slope*x2
            line=np.append(line, slope)
            line = np.append(line, intercept)
            if abs(slope) > 0.2 and abs(slope) < 10: # rule out too horizontal lines
                if slope > 0 and x2 > 550: #positive slope should be marked green (I expected this to mark the left lanes but it marked the lanes on the right -> Maybe x2 and x1 and y2 and y1 are in the wrong order))
                    right_lines.append(line)
                elif slope < 0 and x1 < 400:
                    left_lines.append(line)
    
    # cut-off the line below a y value of:
    y_cutoff = 320
    
    left_avg_slope, left_avg_intercept = find_avg_slope_and_intercept(left_lines)
    if not math.isnan(left_avg_slope) and math.isnan(left_avg_intercept):
        left_bottom_intercept = int(np.rint((539-left_avg_intercept)/left_avg_slope)) # y=mx+b -> y=539 539=mx+b -> x=(539-b)/m
        #calculate x values of the lines at the y cutoff
        # y=mx+b -> x=(y-b)/m
        left_x_cutoff=int(np.rint((y_cutoff-left_avg_intercept)/left_avg_slope))
        cv2.line(img, (left_bottom_intercept, 539), (left_x_cutoff, y_cutoff), [0, 255, 0], thickness)
    
    right_avg_slope, right_avg_intercept = find_avg_slope_and_intercept(right_lines)
    if not math.isnan(left_avg_slope) and math.isnan(left_avg_intercept):
        right_bottom_intercept = int(np.rint((539-right_avg_intercept)/right_avg_slope))
        right_x_cutoff=int(np.rint((y_cutoff-right_avg_intercept)/right_avg_slope))
        cv2.line(img, (right_bottom_intercept, 539), (right_x_cutoff, y_cutoff), [0, 0, 255], thickness)
    


def find_avg_slope_and_intercept(lines):    
    slopes=[]
    intercepts=[]
    for line in lines:
        x1= line[0]
        y1= line[1]
        x2= line[2]
        y2= line[3]
        slope = line[4]
        intercept = line[5]
        #for x1,y1,x2,y2, slope, intercept in line:
        slopes.append(slope)
        intercepts.append(intercept)
    avg_slope = []
    avg_intercept = []
    if slopes and intercepts:
        avg_slope = np.average(slopes)
        avg_intercept = np.average(intercepts)
        if math.isnan(avg_slope) or math.isnan(avg_intercept):
            #print("Returning NAN!!!")
            return float('NaN'), float('NaN')
    return avg_slope, avg_intercept

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)
    
    line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
    if lines is not None:
        draw_lines(line_img, lines)
    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, β, λ)

Test Images

Build your pipeline to work on the images in the directory "test_images"
You should make sure your pipeline works well on these images before you try the videos.


In [20]:
import os
test_img_dir = ("test_images/")

test_images = os.listdir(test_img_dir)
print(test_images)


['solidYellowCurve2.jpg', 'whiteCarLaneSwitch.jpg', 'solidWhiteCurve.jpg', 'solidYellowLeft.jpg', 'generated', 'solidYellowCurve.jpg', 'solidWhiteRight.jpg']

Build a Lane Finding Pipeline

Build the pipeline and run your solution on all test_images. Make copies into the test_images directory, and you can use the images in your writeup report.

Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.


In [22]:
# TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images directory.

#test_img_dir = test_img_dir + "generated/"
print("test image dir: " + test_img_dir)


def process_image(test_img_dir, img):
    # read in original image
    ori_image = mpimg.imread(os.path.join(test_img_dir, img))
    
    #convert to HSV colorspace for color filtering
    image = cv2.cvtColor(ori_image, cv2.COLOR_RGB2HSV)
    
    #select white and yellow only get the lane lines
    sensitivity = 50
    lower_white = np.array([0,0,255-sensitivity])
    upper_white = np.array([255,sensitivity,255])
    lower_yellow = np.array([20, 120, 100])
    upper_yellow = np.array([50, 170, 255])
    white = cv2.inRange(image, lower_white, upper_white)
    yellow = cv2.inRange(image, lower_yellow, upper_yellow)
    white_yellow = white + yellow

    # apply the mask to the image
    image = cv2.bitwise_and(image,image, mask= white_yellow)
    image=cv2.cvtColor(image, cv2.COLOR_HSV2RGB)
    
    # output directory for generated images
    output_dir = "generated/" + iteration + "/"
    if not os.path.exists(test_img_dir + output_dir):
        os.makedirs(test_img_dir + output_dir)
    
    # convert to grayscale
    gray = grayscale(image)
    plt.imsave(test_img_dir + output_dir + img + "_grayscale_" + iteration + ".png", gray, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    # apply gaussian blurring
    blurred_img = gaussian_blur(gray, 7)
    plt.imsave(test_img_dir + output_dir + img +  "_blurred_" + iteration + ".png", blurred_img, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    # canny edge detection
    canny_img = canny(blurred_img, 50, 150)
    plt.imsave(test_img_dir + output_dir +  img + "_canny_" + iteration + ".png", canny_img, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    # region of interest
    imshape = canny_img.shape
    vertices = np.array([[(.51 *imshape[1], .6*imshape[0]),(.49*imshape[1], .6*imshape[0]), (0, imshape[0]), (imshape[1],imshape[0])]], dtype=np.int32)
    masked_img = region_of_interest(canny_img, vertices)
    plt.imsave(test_img_dir + output_dir + img +  "_masked_" + iteration + ".png", masked_img, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)
    
    # hugh lines
    rho = 1
    theta = 1 * np.pi/180
    threshold = 40 #40
    min_line_len = 150 #150
    max_line_gap = 130  #130
    hough_img = hough_lines(masked_img, rho, theta, threshold, min_line_len, max_line_gap)
    plt.imsave(test_img_dir + output_dir + img + "_hough_" + iteration + ".png", masked_img, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    #def weighted_img(img, initial_img, α=0.8, β=1., λ=0.)
    result = weighted_img(hough_img, ori_image, α=0.8, β=1., λ=0.)
    plt.imsave(test_img_dir + output_dir + img + "_final_" + iteration + ".png", result, vmin=None, vmax=None, cmap=None, format='png', origin=None, dpi=100)
    plt.imshow(result)
    
iteration = "10"
print(test_images)
gen_ex = (img for img in test_images if os.path.isfile(os.path.join(test_img_dir, img)))
for img in gen_ex:
    process_image(test_img_dir, img)


test image dir: test_images/
['solidYellowCurve2.jpg', 'whiteCarLaneSwitch.jpg', 'solidWhiteCurve.jpg', 'solidYellowLeft.jpg', 'generated', 'solidYellowCurve.jpg', 'solidWhiteRight.jpg']

In [ ]:

Test on Videos

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 [25]:
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML

In [29]:
def process_image(ori_image):
    image = cv2.cvtColor(ori_image, cv2.COLOR_RGB2HSV)
    image = gaussian_blur(image, 3)
    plt.imshow(image, cmap='gray')
    
    #select white and yellow only get the lane lines
    sensitivity = 50
    lower_white = np.array([0,0,255-sensitivity])
    upper_white = np.array([255,sensitivity,255])
    lower_yellow = np.array([20, 120, 100])
    upper_yellow = np.array([50, 170, 255])
    white = cv2.inRange(image, lower_white, upper_white)
    yellow = cv2.inRange(image, lower_yellow, upper_yellow)
    white_yellow = white + yellow
    

    image = cv2.bitwise_and(image,image, mask= white_yellow)
    image=cv2.cvtColor(image, cv2.COLOR_HSV2RGB)
    # convert to grayscale
    gray = grayscale(image)

    # apply gaussian blurring
    blurred_img = gaussian_blur(gray, 7)

    # canny edge detection
    canny_img = canny(blurred_img, 50, 150)

    # region of interest
    imshape = canny_img.shape
    #vertices = np.array([[(0,imshape[0]),(450, 320), (490, 320), (imshape[1],imshape[0])]], dtype=np.int32)
    vertices = np.array([[(.51 *imshape[1], .6*imshape[0]),(.49*imshape[1], .6*imshape[0]), (0, imshape[0]), (imshape[1],imshape[0])]], dtype=np.int32)
    masked_img = region_of_interest(canny_img, vertices)
    
    # hugh lines
    #hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap)
    rho = 1
    theta = 1 * np.pi/180
    threshold = 30 #40
    min_line_len = 5 #150
    max_line_gap = 3  #130
    hough_img = hough_lines(masked_img, rho, theta, threshold, min_line_len, max_line_gap)

    #def weighted_img(img, initial_img, α=0.8, β=1., λ=0.)
    result = weighted_img(hough_img, ori_image, α=0.8, β=1., λ=0.)
    return result

def process_image2(image):
       
    # convert to grayscale
    gray = grayscale(image)
    #plt.imsave(test_img_dir + output_dir + img + "_grayscale_" + iteration + ".png", gray, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    # apply gaussian blurring
    blurred_img = gaussian_blur(gray, 7)
    #plt.imsave(test_img_dir + output_dir + img +  "_blurred_" + iteration + ".png", blurred_img, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    # canny edge detection
    canny_img = canny(blurred_img, 50, 150)
    #plt.imsave(test_img_dir + output_dir +  img + "_canny_" + iteration + ".png", canny_img, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    # region of interest5shape
    vertices = np.array([[(.51 *imshape[1], .58*imshape[0]),(.49*imshape[1], .58*imshape[0]), (0, imshape[0]), (imshape[1],imshape[0])]], dtype=np.int32)
    masked_img = region_of_interest(canny_img, vertices)
    #plt.imsave(test_img_dir + output_dir + img +  "_masked_" + iteration + ".png", masked_img, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    # hugh lines
    #hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap)
    rho = 1
    theta = 1 * np.pi/180
    threshold = 40 #40
    min_line_len = 20 #150
    max_line_gap = 10 #130
    hough_img = hough_lines(masked_img, rho, theta, threshold, min_line_len, max_line_gap)
    #plt.imsave(test_img_dir + output_dir + img + "_hough_" + iteration + ".png", masked_img, vmin=None, vmax=None, cmap='gray', format='png', origin=None, dpi=100)

    #def weighted_img(img, initial_img, α=0.8, β=1., λ=0.)
    result = weighted_img(hough_img, image, α=0.8, β=1., λ=0.)
    return result

Let's try the one with the solid white lane on the right first ...


In [30]:
white_output = 'white.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)


[MoviePy] >>>> Building video white.mp4
[MoviePy] Writing video white.mp4
100%|█████████▉| 221/222 [00:12<00:00, 17.45it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: white.mp4 

CPU times: user 35.1 s, sys: 300 ms, total: 35.4 s
Wall time: 13.4 s

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 [31]:
HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(white_output))


Out[31]:

Improve the draw_lines() function

At this point, if you were successful with making the pipeline and tuning parameters, 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. As mentioned previously, 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".

Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.

Now for the one with the solid yellow lane on the left. This one's more tricky!


In [33]:
yellow_output = 'yellow.mp4'
clip2 = VideoFileClip('solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)


[MoviePy] >>>> Building video yellow.mp4
[MoviePy] Writing video yellow.mp4
100%|█████████▉| 681/682 [00:41<00:00, 16.25it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: yellow.mp4 

CPU times: user 1min 49s, sys: 760 ms, total: 1min 50s
Wall time: 42.6 s

In [34]:
HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(yellow_output))


Out[34]:

Writeup and Submission

If you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a link to the writeup template file.

Optional Challenge

Try your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!


In [32]:
challenge_output = 'extra.mp4'
clip2 = VideoFileClip('challenge.mp4')
challenge_clip = clip2.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)


[MoviePy] >>>> Building video extra.mp4
[MoviePy] Writing video extra.mp4
100%|██████████| 251/251 [00:23<00:00, 10.52it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: extra.mp4 

CPU times: user 53.7 s, sys: 610 ms, total: 54.3 s
Wall time: 25.3 s

In [35]:
HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(challenge_output))


Out[35]: