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 colour 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
import math
import os
%matplotlib inline

Define Constants and Global Variables


In [2]:
"""GLOBALS"""

"""Define color selection criteria"""
# define range of yellow color in HSV
#lower_yellow = np.array([55,60,180], dtype=np.uint8)
#upper_yellow = np.array([100,255,255], dtype=np.uint8)

#yellow_hsv_threshold_low = [yellow_low_hue, yellow_low_sat, yellow_low_val]

#lower_white = np.array([0,0,210], dtype=np.uint8)
#upper_white = np.array([255,8,255], dtype=np.uint8)

# Yellow Low HSV
yellow_low_hue = 55
yellow_low_sat = 60
yellow_low_val = 180

# Yellow High HSV
yellow_high_hue = 100
yellow_high_sat = 255
yellow_high_val = 255

# White High HSV
white_low_hue = 0
white_low_sat = 0
white_low_val = 210

# White High HSV
white_high_hue = 255
white_high_sat = 8
white_high_val = 255

# When apply colour mask, lets only weight the areas we suspect to see the lanes
X_COL_OFFSET = 60
Y_COL_OFFSET = 90



"""Canny Edge"""
low_threshold=50
high_threshold=100

"""Masking"""
X_CENTRE_OFFSET = 40
Y_CENTRE_OFFSET = 50

"""Hough Lines"""
# Define the Hough transform parameters and apply
rho = 2              # distance resolution in pixels of the Hough grid
theta = np.pi/180    # angular resolution in radians of the Hough grid
threshold = 18       # minimum number of votes (intersections in Hough grid cell)
min_line_len = 50    # minimum number of pixels making up a line
max_line_gap = 20    # maximum gap in pixels between connectable line segments

"""Line fitting"""
MIN_SLOPE = 0.45
MAX_SLOPE = 0.82

"""Plotting graphs on or off"""
PLOT_ON = 1

#prev_x_right = None
#prev_x_left = None

# the lenght of the arry for the running average to smooth lanes and catch outliers
RM_LENGTH = 15

g_array_rm_left_x1 =  []
g_array_rm_left_x2 =  []

g_array_rm_right_x1 =  []
g_array_rm_right_x2 =  []

Read in an Image


In [3]:
#reading in an image
def read_image(image_path):
    """ Reads image from image_path and returns image """
    return mpimg.imread(image_path)

#printing out some stats and plotting
def read_and_print_image(image):
    print('This image is:', type(image), 'with dimensions:', image.shape)
    plt.imshow(image)  # if you wanted to show a single colour channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')

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 colour 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 colour 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]:
### TODO: Test function
def colour_mask(img,mask,t1_low,t1_high,t2_low,t2_high):
    """Creates mask on a colour iamge and retunrs colour mask.
    Mask is used to highlight on region of interest for white or yellow lines"""
    # Convert RGB to HSV
    hsv = cv2.cvtColor(mask, cv2.COLOR_RGB2HSV)

    # Threshold the HSV image to get only the colours within the threshold
    mask1 = cv2.inRange(hsv, t1_low, t1_high)
    mask2 = cv2.inRange(hsv, t2_low, t2_high)

    # Bitwise-AND mask and original image
    img_mask1 = cv2.bitwise_and(img,img, mask=mask1)
    img_mask2 = cv2.bitwise_or(img,img, mask=mask2)

    # Combine the two masks
    combined_mask = cv2.addWeighted(img_mask1,1,img_mask2,1,0)
    if PLOT_ON == 1:
        plt.figure()
        plt.title('Combined Yellow & White Mask')
        plt.imshow(combined_mask)
        
    # return combined mask on original image with weighting 
    return cv2.addWeighted(img,0.8,combined_mask,1,0)


def grayscale(img):
    """Applies the Grayscale transform
    This will return an image with only one colour 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"""
    # Define our parameters for Canny and apply
    # Default low_threshold = 50
    # Default high_threshold = 150
    return cv2.Canny(img, low_threshold, high_threshold)

def gaussian_blur(img, kernel_size=5):
    """Applies a Gaussian Noise kernel"""
    # Default size of 5
    return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)

def region_of_interest(img, x_offset, y_offset):
    """
    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.
    """
    
    # First define four points to form a polygon    
    imshape = img.shape
    vertices = np.array([[(0,imshape[0]),
                          (imshape[1]/2-x_offset, imshape[0]/2+y_offset),
                          (imshape[1]/2+x_offset, imshape[0]/2+y_offset),
                          (imshape[1],imshape[0])]],
                            dtype=np.int32)
    
    #define a blank mask to start with
    mask = np.zeros_like(img)   
    
    #defining a 3 channel or 1 channel colour 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_colour = (255,) * channel_count
    else:
        ignore_mask_colour = 255
        
    #filling pixels inside the polygon defined by "vertices" with the fill colour    
    cv2.fillPoly(mask, vertices, ignore_mask_colour)
    
    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image

def reject_outliers(data, m = 2.):
    """
    Rejects any outliers within a data set greater than two standard deviations
    """
    data_arr = np.array(data)
    d = np.abs(abs(data_arr) - np.median(abs(data_arr)))
    mdev = np.median(d)
    s = d/mdev if mdev else 0.
    data_arr[s<m]
    return data_arr.tolist()


def fit_poly(points):
    """
    Fits a polynomial curve to two points
    """
    a,b = np.polyfit(points[:,0],points[:,1],deg=1)    
    return a,b

def get_previous_pt(lane):
    """
    Given the left or right lane, 
    return the points from the previous image
    used to draw the lane
    """
    if(lane == "left"):
        if (len(g_array_rm_left_x1)>0):
            return g_array_rm_left_x1[0], g_array_rm_left_x2[0]
    elif(lane == "right"):
        if (len(g_array_rm_right_x1)>0):
            return g_array_rm_right_x1[0], g_array_rm_right_x2[0]
    return None, None

# given a data set x, calculate the running mean over N points in the array
def running_mean(x): 
    """
    Given a dataset, calculate and return the running mean
    """
    N = len(x)
    if N > 0: 
        cumsum = np.cumsum(np.insert(x, 0, 0))
        rm = (cumsum[N:] - cumsum[:-N]) / N
    else:
        rm = None
    return rm
    

def get_lane_points(slopes, intercepts, ymin, ymax, lane):
    """
    find the extrapolated points for a lane given the slope
    and y intercept
    """
    prev_x1, prev_x2 = get_previous_pt(lane)
    
    if len(np.array(slopes))>0:
        slope = np.average(reject_outliers(np.array(slopes), m = 2.))
        intercept = np.average(reject_outliers(np.array(intercepts), m = 2.))

        if slope!=0:
            y1= ymin
            x1= int((ymin-intercept)/slope)
            y2= ymax
            x2= int((ymax-intercept)/slope)        
    else:
        # if there are no lines use the previous line 
        x1 = prev_x1
        x2 = prev_x2
    
    return x1, x2

def draw_lines(img, lines, colour=[255, 0, 0], thickness=10):
    """
    Iterate over the output line segment, extrapolate to map out the full extent of the lane
    
    Separate line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
    line vs. the right line

    Average the position of each of the lines
    
    Extrapolate to the top and bottom of the lane.
    
    This function draws `lines` with `colour` and `thickness`.    
    Lines are drawn on the image inplace (mutates the image) with transparency.
    """
    global g_array_rm_left_x1, g_array_rm_left_x2, g_array_rm_right_x1, g_array_rm_right_x2
    if lines is None:
        return img
    
    # get image size and create blank to draw lanes on
    imshape = img.shape
    lanes_image = np.copy(img)*0
    
    left_slopes = []
    left_intercepts = []
    
    right_slopes = []
    right_intercepts = []
    
    ymax = imshape[0]
    ymin = lanes_image.shape[0]
    
    # TODO: seperate y heights for left and right lane
    #ymin_left = lanes_image.shape[0]
    #ymin_right = lanes_image.shape[0]
    for line in lines:
        for x1,y1,x2,y2 in line:
            slope, yint = np.polyfit((x1, x2), (y1, y2), 1)
            ymin = min(ymin, y1, y2)
            # We want to seperate positive slopes and negative slopes
            # First we calculate the slope
            if MIN_SLOPE < slope < MAX_SLOPE:
                left_slopes.append(slope)
                left_intercepts.append(yint)
                #ymin_left = min(ymin_left, y1, y2)
            elif -MIN_SLOPE > slope > -MAX_SLOPE:
                right_slopes.append(slope)
                right_intercepts.append(yint)
                #ymin_right = min(ymin_right, y1, y2)
                

    # for the left and right lanes
    # remove outliers
    # then take the average slope and yint
    # check that values exist 
    # if not use previous
    

    # draw left lane, 
    # obtain the average x1,x2 given list of slopes
    no_of_slopes = len(np.array(left_slopes))
    if (no_of_slopes > 0):
        x1,x2 = get_lane_points(left_slopes, left_intercepts, ymin, ymax, "left")
        # insert the new x values into average list
        g_array_rm_left_x1.insert(0, x1)
        g_array_rm_left_x2.insert(0, x2)
        
        # check if points are outliers, if so remove them
        g_array_rm_left_x1 = reject_outliers(np.array(g_array_rm_left_x1), m = 2.)
        g_array_rm_left_x2 = reject_outliers(np.array(g_array_rm_left_x2), m = 2.)
        
        # if the running average list is too long, cull it
        if len(g_array_rm_left_x1) > RM_LENGTH:
            g_array_rm_left_x1.pop(RM_LENGTH-1)
        
        if len(g_array_rm_left_x2) > RM_LENGTH:
            g_array_rm_left_x2.pop(RM_LENGTH-1)
    # save the left values      
    l_rm_x1 = running_mean(g_array_rm_left_x1)
    l_rm_x2 = running_mean(g_array_rm_left_x2)
    
    # draw left lane
    if l_rm_x1 is not None and l_rm_x1>0:
        if l_rm_x2 is not None and l_rm_x2>0:
            cv2.line(lanes_image, (l_rm_x1, ymin), (l_rm_x2, ymax), colour, thickness)
        
    # draw right lane
    
    no_of_slopes = len(np.array(right_slopes))
    if (no_of_slopes>0):
        x1,x2 = get_lane_points(right_slopes, right_intercepts, ymin, ymax, "right")
        # insert the new x values into average list
        g_array_rm_right_x1.insert(0, x1)
        g_array_rm_right_x2.insert(0, x2)
        
        # check if points are outliers, if so remove it
        g_array_rm_right_x1 = reject_outliers(np.array(g_array_rm_right_x1), m = 2.)
        g_array_rm_right_x2 = reject_outliers(np.array(g_array_rm_right_x2), m = 2.)
        
        # if the running average list is too long, cull it
        if len(g_array_rm_right_x1) > RM_LENGTH:
            g_array_rm_right_x1.pop(RM_LENGTH-1)

        if len(g_array_rm_right_x2) > RM_LENGTH:
            g_array_rm_right_x2.pop(RM_LENGTH-1)

    r_rm_x1 = running_mean(g_array_rm_right_x1)
    r_rm_x2 = running_mean(g_array_rm_right_x2)
    
    # draw right lane
    if r_rm_x1 is not None and r_rm_x1>0:
        if r_rm_x2 is not None and r_rm_x2>0:
            cv2.line(lanes_image, (r_rm_x1, ymin), (r_rm_x2, ymax), colour, thickness)
    
    # draw in polygon between the points
    #define a blank mask to start with
    #mask = np.zeros_like(img, np.uint8)
    #lanes_vertices = np.array([ [r_rm_x1,ymin], [r_rm_x2,ymax], [l_rm_x1,ymin], [l_rm_x2,ymax] ], np.int32)
    
    
    ## TODO: Fills a polygon in between the two lines, the colour is not working
    #lanes_mask = cv2.fillPoly(mask, [lanes_vertices], 1 )
    #color = np.array((60,0,255))
    #lanes_mask = cv2.fillPoly( mask, [lanes_vertices], True, (0,0,255)
    #lane_filled = cv2.addWeighted(lanes_mask, 0.3, lanes_image, 1, 0)
    
    return cv2.addWeighted(img, 1, lanes_image, 0.7, 0)
   

def hough_lines(img, rho=2, theta=np.pi/180, threshold=18, min_line_len=50, max_line_gap=20):
    """
    `img` should be the output of a Canny transform.
        
    Returns an image with hough lines drawn.
    """    
    return cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)

# 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

Let the pipeline work on the images in the directory "test_images"
Make sure the pipeline works well on these images before you try the videos.


In [11]:
os.listdir("test_images/")
image_list = [read_image('test_images/'+i) for i in os.listdir('test_images/')]

Build a Lane Finding Pipeline

The pipeline for the lane detection is as follows:

  1. Read image and convert to gray scale
  2. Perform Gaussian smoothing
  3. Perform Canny Edge detection on image
  4. Apply mask to image to get region of interest
  5. Perform Hough transform on image and obtain dominant line segments
  6. Extraporlate line segments and draw in lane lines
  7. Overlay line image with original image to compare result
  8. Save as new image

Build the pipeline and run your solution on all test_images. Make copies into the test_images_output 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 [12]:
# TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images directory.


def draw_lanes_on(image):
    #Thresholds for yellow and white lanes to create weight colour image
    yellow_hsv_threshold_low = np.array([yellow_low_hue, yellow_low_sat, yellow_low_val], dtype=np.uint8)
    yellow_hsv_threshold_high = np.array([yellow_high_hue, yellow_high_sat, yellow_high_val], dtype=np.uint8)
    white_hsv_threshold_low =  np.array([white_low_hue, white_low_sat, white_low_val], dtype=np.uint8)
    white_hsv_threshold_high =  np.array([white_high_hue, white_high_sat, white_high_val], dtype=np.uint8)
    
    # Mask edges image to get region of interest
    polygon_mask_for_colours = region_of_interest(image, X_COL_OFFSET, Y_COL_OFFSET)
    if PLOT_ON == 1:
        plt.figure()
        plt.title('Polygon mask for colour weights')
        plt.imshow(polygon_mask_for_colours)
        
    # Weight the original image with yellow and white
    colour_weighted_image = colour_mask(image, polygon_mask_for_colours,
                                        yellow_hsv_threshold_low,yellow_hsv_threshold_high,
                                        white_hsv_threshold_low,white_hsv_threshold_high)
    
    if PLOT_ON == 1:
        plt.figure()
        plt.title('Colour weighted image')
        plt.imshow(colour_weighted_image)
        
    # Grayscale the image
    gray_image = grayscale(colour_weighted_image)
    if PLOT_ON == 1:
        plt.figure()
        plt.title('Image After Gray Scale')
        plt.imshow(gray_image, cmap="gray")
    
    # Filter the image  
    filtered_image = gaussian_blur(gray_image)
    if PLOT_ON == 1:
        plt.figure()
        plt.title('Image After Filtering')
        plt.imshow(filtered_image, cmap="gray")
    
    # Apply Canny Edge detection
    edges_image = canny(filtered_image, low_threshold, high_threshold)
    if PLOT_ON == 1:
        plt.figure()
        plt.title('Image after Canny Edge Dection')
        plt.imshow(edges_image)

    # Mask edges image to get region of interest
    masked_edges_image = region_of_interest(edges_image, X_CENTRE_OFFSET, Y_CENTRE_OFFSET)
    if PLOT_ON == 1:
        plt.figure()
        plt.title('Edges Image After Masking')
        plt.imshow(masked_edges_image)
    
    lines = hough_lines(masked_edges_image, rho, theta, threshold, min_line_len, max_line_gap)

    
    # save a copy of processed image to file
    #cv2.imwrite("processed_image.jpg", lanes_image)
    lanes_image = draw_lines(image, lines)
    if PLOT_ON == 1:
        plt.figure()
        plt.title('Image after Canny Edge Dection')
        plt.imshow(lanes_image)
        
    
    return lanes_image

plt.imshow(draw_lanes_on(image_list[0]))


Out[12]:
<matplotlib.image.AxesImage at 0x1bcfa745b00>

Test Pipeline on Example Images


In [ ]:
PLOT_ON = 0
for i in range(0, len(image_list)):
    draw_lanes_on(image_list[i])

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 [ ]:
import imageio
imageio.plugins.ffmpeg.download() #needed for my windows install

# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML

In [ ]:
def process_image(image):
    # NOTE: The output you return should be a colour image (3 channel) for processing video below
    # TODO: put your pipeline here,
    # you should return the final output (image where lines are drawn on lanes)
    return draw_lanes_on(image)

# test process_image 
process_image(image_list[0])

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


In [ ]:
white_output = 'test_videos_output/solidWhiteRight.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
PLOT_ON = 0
##clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4").subclip(7,8)
clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4")
white_clip = clip1.fl_image(draw_lanes_on) #NOTE: this function expects colour 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 [ ]:
HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(white_output))

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 [ ]:
yellow_output = 'test_videos_output/solidYellowLeft.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(25,26)
##PLOT_ON = 0
clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)

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

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 [ ]:
challenge_output = 'test_videos_output/challenge.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
PLOT_ON = 0
#clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(3,4)
clip3 = VideoFileClip('test_videos/challenge.mp4')
challenge_clip = clip3.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)

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

In [ ]: