In this project the aim is detect lane lines in images using Python and OpenCV. OpenCV means "Open-Source Computer Vision", which is a package that has many useful tools for analyzing images.
Frist, we need to import some packages.
### importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
Helper Functions
The helper methods below are used in the final pipeline.
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_BGR2GRAY)
# 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, color=(255, 0, 0), thickness=7):
"""
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 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, dtype=np.uint8)
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, β, λ)
## Use this m = (Y2 - Y1) / (X2 - X1) equation to organize lines by their slope.
def separate_lines(lines):
""" Use the array of hough lines and separates them by positive and negative slope.
The y-axis is inverted in matplotlib, so the calculated positive slopes will be right
lane lines and negative slopes will be left lanes. """
right = []
left = []
for x1,y1,x2,y2 in lines[:, 0]:
m = (float(y2) - y1) / (x2 - x1)
if m >= 0:
right.append([x1,y1,x2,y2,m])
else:
left.append([x1,y1,x2,y2,m])
return right, left
def extrapolate(x1, y1, x2, y2, length):
""" Takes line endpoints and extroplates them by a specfic length"""
line_len = np.sqrt((x1 - x2)**2 + (y1 - y2)**2)
x = x2 + (x2 - x1) / line_len * length
y = y2 + (y2 - y1) / line_len * length
return x, y
def line_outliers(data, cutoff, thresh=0.08):
"""Line outliers should e removed. For example, flat lines or lines
deviate too much from the mean"""
data = np.array(data)
data = data[(data[:, 4] >= cutoff[0]) & (data[:, 4] <= cutoff[1])]
m = np.mean(data[:, 4], axis=0)
return data[(data[:, 4] <= m+thresh) & (data[:, 4] >= m-thresh)]
def lines_mean(lines):
"""Mean of all Hough lines and extends them"""
lines = np.array(lines)[:, :4]
x1,y1,x2,y2 = np.mean(lines, axis=0)
x1e, y1e = extrapolate(x1,y1,x2,y2, -1000)
x2e, y2e = extrapolate(x1,y1,x2,y2, 1000)
line = np.array([[x1e,y1e,x2e,y2e]])
return np.array([line], dtype=np.int32)
Pipeline
def pipeline(image):
# Params for region of interest
bot_left = [80, 540]
bot_right = [980, 540]
apex_right = [510, 315]
apex_left = [450, 315]
v = [np.array([bot_left, bot_right, apex_right, apex_left], dtype=np.int32)]
# Gray scale, Gaussian smoothing, edge detection and mask region of interest
gray = grayscale(image)
blur = gaussian_blur(gray, 7)
edge = canny(blur, 50, 125)
mask = region_of_interest(edge, v)
# Hough Lines and separate by postite and negative slope
lines = cv2.HoughLinesP(mask, 0.8, np.pi/180, 25, np.array([]), minLineLength=50, maxLineGap=200)
right_lines, left_lines = separate_lines(lines)
right = line_outliers(right_lines, cutoff=(0.45, 0.75))
right = lines_mean(right)
left = line_outliers(left_lines, cutoff=(-0.85, -0.6))
left = lines_mean(left)
lines = np.concatenate((right, left))
# Draw lines
line_img = np.copy((image)*0)
draw_lines(line_img, lines, thickness=10)
# Return final image
line_img = region_of_interest(line_img, v)
final = weighted_img(line_img, image)
return final
The pipeline plugged into MoviePy:
## Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip, ImageClip
from IPython.display import HTML
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)
result = pipeline(image)
return result
white_output = 'final.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 final.mp4
[MoviePy] Writing video final.mp4
[MoviePy] Done.
[MoviePy] >>>> Video ready: final.mp4
CPU times: user 2.8 s, sys: 678 ms, total: 3.47 s
Wall time: 3.27 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.
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!
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
[MoviePy] Done.
[MoviePy] >>>> Video ready: yellow.mp4
CPU times: user 8.98 s, sys: 1.97 s, total: 10.9 s
Wall time: 9.67 s
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(yellow_output))
Optional Challenge
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
[MoviePy] Done.
[MoviePy] >>>> Video ready: extra.mp4
CPU times: user 6.59 s, sys: 1.46 s, total: 8.05 s
Wall time: 8.35 s
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output))
In order to make the algorithm more robust use a a color mask that will highlights the whites and yellows in the frame.
def merge_prev(line, prev):
""" Extra Challenge: Reduces jitter and missed lines by averaging previous
frame line with current frame line. """
if prev != None:
line = np.concatenate((line[0], prev[0]))
x1,y1,x2,y2 = np.mean(line, axis=0)
line = np.array([[[x1,y1,x2,y2]]], dtype=np.int32)
return line
else:
return line
Adding a global variable for the line from the prior frame. In this will be averaged with the current frame to prevent jitterying on the video footage.
Final version of the pypeline for the optional challenge:
global right_prev
global left_prev
right_prev = None
left_prev = None
def pipeline(image, preview=False):
global right_prev
global left_prev
bot_left = [250, 660]
bot_right = [1100, 660]
apex_right = [725, 440]
apex_left = [580, 440]
v = [np.array([bot_left, bot_right, apex_right, apex_left], dtype=np.int32)]
### Added a color mask to deal with shaded region
color_low = np.array([187,187,0])
color_high = np.array([255,255,255])
color_mask = cv2.inRange(image, color_low, color_high)
gray = grayscale(image)
blur = gaussian_blur(gray, 3)
blur = weighted_img(blur, color_mask)
edge = cv2.Canny(blur, 100, 300)
mask = region_of_interest(edge, v)
lines = cv2.HoughLinesP(mask, 0.5, np.pi/180, 10, np.array([]), minLineLength=90, maxLineGap=200)
right_lines, left_lines = separate_lines(lines)
right = line_outliers(right_lines, cutoff=(0.45, 0.75))
right = lines_mean(right)
right = merge_prev(right, right_prev)
right_prev = right
left = line_outliers(left_lines, cutoff=(-1.1, -0.2))
left = lines_mean(left)
left = merge_prev(left, left_prev)
left_prev = left
lines = np.concatenate((right, left))
line_img = np.copy((image)*0)
draw_lines(line_img, lines, thickness=10)
line_img = region_of_interest(line_img, v)
final = weighted_img(line_img, image)
return final
challenge_output = 'extra_final.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_final.mp4
[MoviePy] Writing video extra_final.mp4
[MoviePy] Done.
[MoviePy] >>>> Video ready: extra_final.mp4
CPU times: user 5.74 s, sys: 1.51 s, total: 7.25 s
Wall time: 7.65 s
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output))