Code I wrote in Python utilizing NumPy, OpenCV, etc., for Udacity’s Self-Driving Car course. The flow goes like this:
Each video frame is processed as an image:
- Convert image to grayscale
- Apply a Gaussian blur to the grayscaled image
- Generate an image which only contains edges from the grayscaled image (Canny edge detection algorithm)
- Mask edges image to a region limited to where the camera would be positioned (a triangle in the middle)
- Determine coordinates of lines from the masked image (Hough transform algorithm)
- Calculate min ys and max ys from lines
- Separate lines by slope, into left lines and right lines
- Calculate mean slope and intercept of left and right lines
- Calculate extrapolated line for each left and right lines
- Draw semi-transparent lines onto original image
Extrapolate lines:
Repeat for each video frame
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.
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
# Importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
# 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
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!
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 hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns the hough lines.
"""
return cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
def draw_hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap, color, thickness):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn.
"""
lines = hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap)
line_img = np.zeros((*img.shape, 3), dtype=np.uint8)
draw_lines(line_img, lines, color, thickness)
return line_img
def calculate_slope(x1, y1, x2, y2):
return (y2 - y1) / (x2 - x1)
def calculate_intercept(x1, y1, x2, y2):
return y1 - ((y2 - y1) / (x2 - x1)) * x1
def calculate_y(slope, x, intercept):
return (slope * x) + intercept
def calculate_x(slope, intercept, y):
return (y - intercept) / slope
def y_min_max(lines, max_height):
if lines is None or len(lines) == 0:
return (None, None)
y_min = max_height
y_max = 0
for line in lines:
for _x1, y1, _x2, y2 in line:
y_min = min(y_min, y1)
y_min = min(y_min, y2)
y_max = max(y_max, y1)
y_max = max(y_max, y2)
return (y_min, y_max)
# h , w
# (540, 960, 3)
def draw_extraoplated_lines(image, lines, left_line_color=[255, 0, 0], right_line_color=[255, 0, 0], thickness=2):
line_image = np.zeros((*image.shape, 3), dtype=np.uint8)
if len(lines) == 0:
return line_image
left_slopes = []
left_intercepts = []
right_slopes = []
right_intercepts = []
y_min, y_max = y_min_max(lines, image.shape[0])
for line in lines:
for x1, y1, x2, y2 in line:
slope = calculate_slope(x1, y1, x2, y2)
intercept = calculate_intercept(x1, y1, x2, y2)
if -1.0 < slope < -0.5 and x2 < image.shape[1] / 2: # left lane line
left_slopes.append(slope)
left_intercepts.append(intercept)
elif 0.30 < slope < 1.0 and x2 > image.shape[1] / 2: # right lane line
right_slopes.append(slope)
right_intercepts.append(intercept)
if len(left_slopes) > 0:
left_avg_slope = np.mean(left_slopes, axis=0)
left_avg_intercept = np.mean(left_intercepts, axis=0)
x1 = int(round(calculate_x(left_avg_slope, left_avg_intercept, y_max)))
x2 = int(round(calculate_x(left_avg_slope, left_avg_intercept, y_min)))
cv2.line(line_image, (x1, y_max), (x2, y_min), left_line_color, thickness) # Draw the left extrapolated line
if len(right_slopes) > 0:
right_avg_slope = np.mean(right_slopes, axis=0)
right_avg_intercept = np.mean(right_intercepts, axis=0)
x1 = int(round(calculate_x(right_avg_slope, right_avg_intercept, y_max)))
x2 = int(round(calculate_x(right_avg_slope, right_avg_intercept, y_min)))
cv2.line(line_image, (x1, y_max), (x2, y_min), right_line_color, thickness) # Draw the right extrapolated line
return line_image
# 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, β, λ)
def process_image(image, region, params):
# Grayscale
grascale_image = grayscale(image)
# Gaussian blur
blurred_image = gaussian_blur(grascale_image, params['gaussian_kernel_size'])
# Canny
canny_image = canny(blurred_image, params['canny_low_threshold'], params['canny_high_threshold'])
# Mask the image
masked_image = region_of_interest(canny_image, region)
# Hough
lines = hough_lines(masked_image, params['hough_rho'], params['hough_theta'], params['hough_threshold'], params['hough_min_line_len'], params['hough_max_line_gap'])
# Draw extrapolated lines
extrapolated_image = draw_extraoplated_lines(masked_image, lines, params['left_line_color'], params['right_line_color'], params['line_thickness'])
# Merge the Hough image with the original image
result = weighted_img(extrapolated_image, image)
return result
import glob
params = {
'gaussian_kernel_size': 5,
'canny_low_threshold': 50,
'canny_high_threshold': 150,
'hough_rho': 2,
'hough_theta': np.pi / 180,
'hough_threshold': 15,
'hough_min_line_len': 40,
'hough_max_line_gap': 20,
'left_line_color': [255, 0, 0],
'right_line_color': [255, 0, 0],
'line_thickness': 6
}
fig = plt.figure(figsize=(20, 8))
test_image_paths = glob.glob('test_images/*.jpg')
test_image_results = [None]*len(test_image_paths)
for index, test_image_path in enumerate(test_image_paths):
image = mpimg.imread(test_image_path)
image_shape = image.shape # (540, 960, 3)
region = np.array([[(120, image_shape[0]), (400, 340), (540, 340), (960, image_shape[0])]], dtype=np.int32)
test_image_results[index] = process_image(image, region, params)
fig.add_subplot(2, 3, index + 1)
plt.imshow(test_image_results[index])
Broken lines don’t work because their max X is not the true max X. Need to calculate the max X. Refer to diagram for help.
run your solution on all test_images and make copies into the test_images directory).
# 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 …
params = {
'gaussian_kernel_size': 5,
'canny_low_threshold': 50,
'canny_high_threshold': 150,
'hough_rho': 2,
'hough_theta': np.pi / 180,
'hough_threshold': 15,
'hough_min_line_len': 40,
'hough_max_line_gap': 20,
'left_line_color': [255, 0, 0],
'right_line_color': [255, 0, 0],
'line_thickness': 6
}
region = np.array([[(120, image_shape[0]), (400, 340), (540, 340), (960, image_shape[0])]], dtype=np.int32)
func = lambda img: process_image(img, region, params)
white_output = 'white.mp4'
clip1 = VideoFileClip("solidWhiteRight.mp4")
white_clip = clip1.fl_image(func) #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.
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output))
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!
params = {
'gaussian_kernel_size': 5,
'canny_low_threshold': 50,
'canny_high_threshold': 150,
'hough_rho': 2,
'hough_theta': np.pi / 180,
'hough_threshold': 15,
'hough_min_line_len': 40,
'hough_max_line_gap': 20,
'left_line_color': [255, 0, 0],
'right_line_color': [255, 0, 0],
'line_thickness': 6
}
region = np.array([[(120, image_shape[0]), (400, 340), (540, 340), (960, image_shape[0])]], dtype=np.int32)
func = lambda img: process_image(img, region, params)
yellow_output = 'yellow.mp4'
clip2 = VideoFileClip('solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(func)
%time yellow_clip.write_videofile(yellow_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(yellow_output))
Reflections
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!
To improve my algorithim, I cound look into smoothing the extrapolated line somehow. Perhaps something which considers the last n previous lines?
Also, I wonder how these techniques are applied to the final product? For example, Python, NumPy and OpenCV are great for learning and prototyping. However, I wonder if the final product should be writted in C or using some specialized GPU-based hardware? CUDA? Or something NVidia makes?
params = {
'gaussian_kernel_size': 5,
'canny_low_threshold': 50,
'canny_high_threshold': 150,
'hough_rho': 2,
'hough_theta': np.pi / 180,
'hough_threshold': 15,
'hough_min_line_len': 40,
'hough_max_line_gap': 20,
'left_line_color': [255, 0, 0],
'right_line_color': [255, 0, 0],
'line_thickness': 6
}
region = np.array([[(120, image_shape[0]), (400, 340), (540, 340), (960, image_shape[0])]], dtype=np.int32)
func = lambda img: process_image(img, region, params)
challenge_output = 'extra.mp4'
clip2 = VideoFileClip('challenge.mp4')
challenge_clip = clip2.fl_image(func)
%time challenge_clip.write_videofile(challenge_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output))