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

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.


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

In [82]:
#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[82]:
<matplotlib.image.AxesImage at 0x7f8355097860>

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 [83]:
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, color, thickness):
    """
    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([]), min_line_len, max_line_gap)
    line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
    color = [255,0,0]
    thickness = 5
    draw_lines(line_img, lines, color, thickness)
    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, β, λ)

In [84]:
## Test on Images

##Now you should 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 [85]:
import os
os.listdir("test_images/")


Out[85]:
['solidYellowCurve.jpg',
 'whiteCarLaneSwitch.jpg',
 'challenge.jpg',
 'solidYellowCurve2.jpg',
 'solidYellowLeft.jpg',
 'solidWhiteRight.jpg',
 'solidWhiteCurve.jpg']

In [86]:
# run your solution on all test_images and make copies into the test_images directory).

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

def calculate_hough_lines(image):
    # make gray    
    gray = grayscale(image)

    # find edges with Canny algorithm
    kernel_size = 3
    blur_gray = gaussian_blur(gray, kernel_size)

    # Define our parameters for Canny and apply
    low_threshold = 90
    high_threshold = 200
    edges = canny(blur_gray, low_threshold, high_threshold) 

    # Next we'll create a masked edges image using cv2.fillPoly()
    mask = np.zeros_like(edges)   
    ignore_mask_color = 255  

    # This time we are defining a four sided polygon to mask
    imshape = image.shape
    
    bottom_horizontal_margin = 50
    top_center_length = 30
    top_margin = 330
    
    vertices = np.array([[
        (bottom_horizontal_margin,imshape[0]),
        (imshape[1]/2-top_center_length, top_margin), 
        (imshape[1]/2+top_center_length, top_margin), 
        (imshape[1]-bottom_horizontal_margin,imshape[0])
    ]], dtype=np.int32)
    masked_edges = region_of_interest(edges, vertices)

    ## Detect continuous line
    # Define the Hough transform parameters
    # Make a blank the same size as our image to draw on
    rho = 1 # distance resolution in pixels of the Hough grid
    theta = np.pi/45 # angular resolution in radians of the Hough grid
    threshold = 25     # minimum number of votes (intersections in Hough grid cell)
    min_line_length = 20 # minimum number of pixels making up a line
    max_line_gap = 30    # maximum gap in pixels between connectable line segments

    #lines = hough_lines(masked_edges, rho, theta, threshold, min_line_length, max_line_gap)
    lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
    return lines

def calculate_hough_lines_challenge(image):
    # make gray    
    gray = grayscale(image)

    # find edges with Canny algorithm
    kernel_size = 13
    blur_gray = gaussian_blur(gray, kernel_size)

    # Define our parameters for Canny and apply
    low_threshold = 230
    high_threshold = 70
    edges = canny(blur_gray, low_threshold, high_threshold) 

    # Next we'll create a masked edges image using cv2.fillPoly()
    mask = np.zeros_like(edges)   
    ignore_mask_color = 255  

    # This time we are defining a four sided polygon to mask
    imshape = image.shape
    
    bottom_horizontal_margin = 70
    bottom_margin = 70
    top_center_length = 30
    top_margin = 420
    
    vertices = np.array([[
        (bottom_horizontal_margin,imshape[0] - bottom_margin),
        (imshape[1]/2-top_center_length, top_margin), 
        (imshape[1]/2+top_center_length, top_margin), 
        (imshape[1]-bottom_horizontal_margin,imshape[0] - bottom_margin)
    ]], dtype=np.int32)
    masked_edges = region_of_interest(edges, vertices)
    
    ## Detect continuous line
    # Define the Hough transform parameters
    # Make a blank the same size as our image to draw on
    rho = 1 # distance resolution in pixels of the Hough grid
    theta = np.pi/45 # angular resolution in radians of the Hough grid
    threshold = 25     # minimum number of votes (intersections in Hough grid cell)
    min_line_length = 20 # minimum number of pixels making up a line
    max_line_gap = 30    # maximum gap in pixels between connectable line segments

    #lines = hough_lines(masked_edges, rho, theta, threshold, min_line_length, max_line_gap)
    lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)    
    return lines

def draw_hough_lines(image, lines):
    line_image = np.copy(image)*0 # creating a blank to draw lines on

    color = [255,0,0]
    thickness = 5
    draw_lines(line_image, lines, color, thickness)

    # Draw the lines on the original image
    lines_edges = weighted_img(image, line_image, 0.8, 1, 0)
    return lines_edges

def draw_hough_lines_average(img, lines, color, thickness):
    left_lane_x = []
    left_lane_y = []
    right_lane_x = []
    right_lane_y = []
    
    for line in lines:
        for x1,y1,x2,y2 in line:
            to_right_lane = belongs_to_right_lane(x1, y1, x2, y2)
            if (to_right_lane):
                right_lane_x.append(x1)
                right_lane_x.append(x2)
                right_lane_y.append(y1)
                right_lane_y.append(y2)
            elif (not to_right_lane):
                left_lane_x.append(x1)
                left_lane_x.append(x2)
                left_lane_y.append(y1)
                left_lane_y.append(y2)
                
    if (len(left_lane_x) == 0 
        or len(left_lane_y) == 0
        or len(right_lane_x) == 0
        or len(right_lane_y) == 0):
        return
    
    # y = a + bx
    # x = (y - a) / b
                
    # Find solution for best fit line
    left_lane_a, left_lane_b = best_fit(left_lane_x, left_lane_y)
    right_lane_a, right_lane_b = best_fit(right_lane_x, right_lane_y)
    
    if (left_lane_b == 0 or right_lane_b == 0):
        return

    # Find common maximum coordinates
    all_y = left_lane_y + right_lane_y
    max_y = max(all_y)
    min_y = min(all_y)

    #left line
    x1 = int((min_y - left_lane_a) / left_lane_b)
    y1 = min_y
    x2 = int((max_y - left_lane_a) / left_lane_b)
    y2 = max_y
    cv2.line(img, (x1, y1), (x2, y2), color, thickness)
    
    #right line
    x1 = int((min_y - right_lane_a) / right_lane_b)
    y1 = min_y
    x2 = int((max_y - right_lane_a) / right_lane_b)
    y2 = max_y
    cv2.line(img, (x1, y1), (x2, y2), color, thickness)
    
def belongs_to_right_lane(x1, y1, x2, y2):
    return ((y2-y1)/(x2-x1)) > 0

# Function to solve y = a + bx
# From http://stackoverflow.com/questions/22239691/code-for-line-of-best-fit-of-a-scatter-plot-in-python
def best_fit(X, Y):
    xbar = sum(X)/len(X)
    ybar = sum(Y)/len(Y)
    n = len(X)

    numer = sum(xi*yi for xi,yi in zip(X, Y)) - n * xbar * ybar
    denum = sum(xi**2 for xi in X) - n * xbar**2

    b = numer / denum
    a = ybar - b * xbar

    #print('best fit line: y = {:.2f} + {:.2f}x'.format(a, b))

    return a, b

def detect_lines(image):
    hough_lines = calculate_hough_lines(image)
    line_image = np.copy(image)*0 # creating a blank to draw lines on

    color = [255,0,0]
    thickness = 5
    draw_lines(line_image, hough_lines, color, thickness)

    # Draw the lines on the original image
    return weighted_img(image, line_image, 0.8, 1, 0)

def detect_lines_average(image):
    hough_lines = calculate_hough_lines(image)
    line_image = np.copy(image)*0 # creating a blank to draw lines on

    color = [255,0,0]
    thickness = 5
    draw_hough_lines_average(line_image, hough_lines, color, thickness)

    # Draw the lines on the original image
    return weighted_img(image, line_image, 0.8, 1, 0)

def detect_lines_challenge(image):
    hough_lines = calculate_hough_lines_challenge(image)
    line_image = np.copy(image)*0 # creating a blank to draw lines on

    color = [255,0,0]
    thickness = 5
    draw_hough_lines_average(line_image, hough_lines, color, thickness)

    # Draw the lines on the original image
    return weighted_img(image, line_image, 0.8, 1, 0)

# print image
# image = mpimg.imread('test_images/challenge.jpg')
# lines_image = detect_lines_challenge(image)
# plt.imshow(lines_image)
# mpimg.imsave('test_images/challenge_detected.jpg', np.asarray(lines_image),format='jpg')

def process_all_test_images():
    test_images = os.listdir("test_images/")
    for test_image in test_images:
        
        image = mpimg.imread("test_images/" + test_image)
        
        lines_image = detect_lines(image)
        
        output = "test_images/lines_detected_" + test_image
        mpimg.imsave(output, np.asarray(lines_image),format='jpg')
        
process_all_test_images()



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

In [89]:
def process_image(image):
    return detect_lines_average(image)

def process_image_challenge(image):
    return detect_lines_challenge(image)

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


In [90]:
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
  0%|          | 0/222 [00:00<?, ?it/s]
  3%|▎         | 6/222 [00:00<00:03, 54.36it/s]
  6%|▌         | 13/222 [00:00<00:03, 58.22it/s]
  9%|▉         | 20/222 [00:00<00:03, 61.11it/s]
 12%|█▏        | 27/222 [00:00<00:03, 62.68it/s]
 16%|█▌        | 35/222 [00:00<00:02, 65.19it/s]
 19%|█▉        | 43/222 [00:00<00:02, 66.28it/s]
 23%|██▎       | 50/222 [00:00<00:03, 49.53it/s]
 25%|██▌       | 56/222 [00:01<00:03, 44.32it/s]
 27%|██▋       | 61/222 [00:01<00:03, 40.68it/s]
 30%|██▉       | 66/222 [00:01<00:04, 35.78it/s]
 32%|███▏      | 70/222 [00:01<00:04, 35.48it/s]
 33%|███▎      | 74/222 [00:01<00:04, 32.63it/s]
 35%|███▌      | 78/222 [00:01<00:04, 32.30it/s]
 37%|███▋      | 82/222 [00:01<00:04, 30.27it/s]
 39%|███▊      | 86/222 [00:02<00:04, 30.65it/s]
 41%|████      | 90/222 [00:02<00:04, 29.62it/s]
 42%|████▏     | 94/222 [00:02<00:04, 30.61it/s]
 44%|████▍     | 98/222 [00:02<00:03, 31.28it/s]
 46%|████▌     | 102/222 [00:02<00:03, 31.29it/s]
 48%|████▊     | 106/222 [00:02<00:03, 30.94it/s]
 50%|████▉     | 110/222 [00:02<00:03, 28.28it/s]
 51%|█████     | 113/222 [00:02<00:03, 27.30it/s]
Exception in thread Thread-7:
Traceback (most recent call last):
  File "/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/tqdm/_tqdm.py", line 103, in run
    for instance in self.tqdm_cls._instances:
  File "/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/_weakrefset.py", line 60, in __iter__
    for itemref in self.data:
RuntimeError: Set changed size during iteration

100%|█████████▉| 221/222 [00:06<00:00, 34.60it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: white.mp4 

CPU times: user 5.01 s, sys: 212 ms, total: 5.22 s
Wall time: 7.33 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 [91]:
HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(white_output))


Out[91]:

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 [92]:
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:20<00:00, 33.38it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: yellow.mp4 

CPU times: user 15.6 s, sys: 508 ms, total: 16.1 s
Wall time: 21.5 s

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


Out[93]:

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!

Thoughts

My current implementation cannot achieve to follow the lane lines all the time. It seems that finding the perfect parameters for all the steps is really complicated and they might also change for different scenarios like fog, bad weather, etc.

One solution could be to use machine learning in order to find those parameters instead of a human having to pick and try. Also the machine could generate different values for different scenarios.

We could also try to discard lines or slopes that diverge too much from the average for every lane using a gausiann bell distribution, so that we could handle little imperfections in the road and lanes without disturbing the main lane.

The clipping could be improved by processing first the image at a hight level abstraction and remove concepts like sky, vegetation, etc.

The current algorithm will fail:

  • The contrast of the image changes
  • There are obstructions in the view like traffic or road works
  • There is a curve or a corner
  • Another lane intersects with the expected one due to road works or old road marks
  • Changing lanes

Submission

If you're satisfied with your video outputs it's time to submit! Submit this ipython notebook for review.

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 [101]:
challenge_output = 'extra.mp4'
clip2 = VideoFileClip('challenge.mp4')
challenge_clip = clip2.fl_image(process_image_challenge)
%time challenge_clip.write_videofile(challenge_output, audio=False)


[MoviePy] >>>> Building video extra.mp4
[MoviePy] Writing video extra.mp4



  0%|          | 0/251 [00:00<?, ?it/s]



  2%|▏         | 4/251 [00:00<00:07, 34.59it/s]



  3%|▎         | 8/251 [00:00<00:06, 34.80it/s]



  5%|▍         | 12/251 [00:00<00:06, 34.98it/s]



  6%|▋         | 16/251 [00:00<00:06, 34.51it/s]



  8%|▊         | 20/251 [00:00<00:06, 35.21it/s]



 10%|▉         | 24/251 [00:00<00:06, 35.91it/s]



 11%|█         | 28/251 [00:00<00:06, 36.52it/s]



 13%|█▎        | 32/251 [00:00<00:05, 36.94it/s]



 14%|█▍        | 36/251 [00:00<00:05, 36.80it/s]



 16%|█▌        | 40/251 [00:01<00:05, 36.41it/s]



 18%|█▊        | 44/251 [00:01<00:05, 35.90it/s]



 19%|█▉        | 48/251 [00:01<00:07, 26.05it/s]



 20%|██        | 51/251 [00:01<00:08, 22.50it/s]



 22%|██▏       | 54/251 [00:01<00:10, 19.13it/s]



 23%|██▎       | 57/251 [00:02<00:10, 18.80it/s]



 24%|██▍       | 60/251 [00:02<00:10, 17.65it/s]



 25%|██▍       | 62/251 [00:02<00:12, 15.14it/s]



 25%|██▌       | 64/251 [00:02<00:13, 14.30it/s]



 26%|██▋       | 66/251 [00:02<00:12, 15.15it/s]



 27%|██▋       | 68/251 [00:02<00:11, 15.93it/s]



 28%|██▊       | 70/251 [00:02<00:11, 15.88it/s]



 29%|██▊       | 72/251 [00:03<00:12, 14.26it/s]



 29%|██▉       | 74/251 [00:03<00:13, 13.17it/s]



 30%|███       | 76/251 [00:03<00:13, 13.24it/s]



 31%|███       | 78/251 [00:03<00:13, 12.93it/s]



 32%|███▏      | 80/251 [00:03<00:13, 13.08it/s]



 33%|███▎      | 82/251 [00:03<00:12, 13.98it/s]



 33%|███▎      | 84/251 [00:03<00:11, 14.30it/s]



 34%|███▍      | 86/251 [00:04<00:11, 14.84it/s]



 35%|███▌      | 88/251 [00:04<00:10, 15.72it/s]



 36%|███▌      | 90/251 [00:04<00:09, 16.59it/s]



 37%|███▋      | 92/251 [00:04<00:10, 15.05it/s]



 37%|███▋      | 94/251 [00:04<00:10, 15.39it/s]



 38%|███▊      | 96/251 [00:04<00:10, 15.17it/s]



 39%|███▉      | 98/251 [00:04<00:10, 15.06it/s]



 40%|███▉      | 100/251 [00:05<00:10, 14.73it/s]



 41%|████      | 102/251 [00:05<00:09, 14.92it/s]



 41%|████▏     | 104/251 [00:05<00:09, 15.02it/s]



 42%|████▏     | 106/251 [00:05<00:09, 15.46it/s]



 43%|████▎     | 109/251 [00:05<00:08, 16.59it/s]



 44%|████▍     | 111/251 [00:05<00:08, 16.44it/s]



 45%|████▌     | 113/251 [00:05<00:09, 14.72it/s]



 46%|████▌     | 115/251 [00:05<00:09, 15.02it/s]



 47%|████▋     | 117/251 [00:06<00:09, 14.39it/s]



 47%|████▋     | 119/251 [00:06<00:08, 15.36it/s]



 48%|████▊     | 121/251 [00:06<00:09, 13.95it/s]



 49%|████▉     | 123/251 [00:06<00:08, 14.39it/s]



 50%|████▉     | 125/251 [00:06<00:08, 15.21it/s]



 51%|█████     | 127/251 [00:06<00:08, 13.86it/s]



 51%|█████▏    | 129/251 [00:06<00:08, 13.99it/s]



 52%|█████▏    | 131/251 [00:07<00:09, 13.31it/s]



 53%|█████▎    | 133/251 [00:07<00:08, 13.95it/s]



 54%|█████▍    | 135/251 [00:07<00:08, 14.28it/s]



 55%|█████▍    | 137/251 [00:07<00:08, 13.36it/s]



 55%|█████▌    | 139/251 [00:07<00:08, 12.90it/s]



 56%|█████▌    | 141/251 [00:07<00:07, 13.83it/s]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-101-4e3e2a0403ab> in <module>()
      2 clip2 = VideoFileClip('challenge.mp4')
      3 challenge_clip = clip2.fl_image(process_image_challenge)
----> 4 get_ipython().magic('time challenge_clip.write_videofile(challenge_output, audio=False)')

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
   2156         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2157         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2158         return self.run_line_magic(magic_name, magic_arg_s)
   2159 
   2160     #-------------------------------------------------------------------------

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
   2077                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2078             with self.builtin_trap:
-> 2079                 result = fn(*args,**kwargs)
   2080             return result
   2081 

<decorator-gen-59> in time(self, line, cell, local_ns)

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    186     # but it's overkill for just that one bit of state.
    187     def magic_deco(arg):
--> 188         call = lambda f, *a, **k: f(*a, **k)
    189 
    190         if callable(arg):

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/IPython/core/magics/execution.py in time(self, line, cell, local_ns)
   1174         if mode=='eval':
   1175             st = clock2()
-> 1176             out = eval(code, glob, local_ns)
   1177             end = clock2()
   1178         else:

<timed eval> in <module>()

<decorator-gen-172> in write_videofile(self, filename, fps, codec, bitrate, audio, audio_fps, preset, audio_nbytes, audio_codec, audio_bitrate, audio_bufsize, temp_audiofile, rewrite_audio, remove_temp, write_logfile, verbose, threads, ffmpeg_params)

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/decorators.py in requires_duration(f, clip, *a, **k)
     52         raise ValueError("Attribute 'duration' not set")
     53     else:
---> 54         return f(clip, *a, **k)
     55 
     56 

<decorator-gen-171> in write_videofile(self, filename, fps, codec, bitrate, audio, audio_fps, preset, audio_nbytes, audio_codec, audio_bitrate, audio_bufsize, temp_audiofile, rewrite_audio, remove_temp, write_logfile, verbose, threads, ffmpeg_params)

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/decorators.py in use_clip_fps_by_default(f, clip, *a, **k)
    135              for (k,v) in k.items()}
    136 
--> 137     return f(clip, *new_a, **new_kw)

<decorator-gen-170> in write_videofile(self, filename, fps, codec, bitrate, audio, audio_fps, preset, audio_nbytes, audio_codec, audio_bitrate, audio_bufsize, temp_audiofile, rewrite_audio, remove_temp, write_logfile, verbose, threads, ffmpeg_params)

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/decorators.py in convert_masks_to_RGB(f, clip, *a, **k)
     20     if clip.ismask:
     21         clip = clip.to_RGB()
---> 22     return f(clip, *a, **k)
     23 
     24 @decorator.decorator

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/video/VideoClip.py in write_videofile(self, filename, fps, codec, bitrate, audio, audio_fps, preset, audio_nbytes, audio_codec, audio_bitrate, audio_bufsize, temp_audiofile, rewrite_audio, remove_temp, write_logfile, verbose, threads, ffmpeg_params)
    337                            audiofile = audiofile,
    338                            verbose=verbose, threads=threads,
--> 339                            ffmpeg_params=ffmpeg_params)
    340 
    341         if remove_temp and make_audio:

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/video/io/ffmpeg_writer.py in ffmpeg_write_video(clip, filename, fps, codec, bitrate, preset, withmask, write_logfile, audiofile, verbose, threads, ffmpeg_params)
    202 
    203     for t,frame in clip.iter_frames(progress_bar=True, with_times=True,
--> 204                                     fps=fps, dtype="uint8"):
    205         if withmask:
    206             mask = (255*clip.mask.get_frame(t))

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/tqdm/_tqdm.py in __iter__(self)
    828 """, fp_write=getattr(self.fp, 'write', sys.stderr.write))
    829 
--> 830             for obj in iterable:
    831                 yield obj
    832                 # Update and print the progressbar.

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/Clip.py in generator()
    471             for t in np.arange(0, self.duration, 1.0/fps):
    472 
--> 473                 frame = self.get_frame(t)
    474 
    475                 if (dtype is not None) and (frame.dtype != dtype):

<decorator-gen-135> in get_frame(self, t)

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/decorators.py in wrapper(f, *a, **kw)
     87         new_kw = {k: fun(v) if k in varnames else v
     88                  for (k,v) in kw.items()}
---> 89         return f(*new_a, **new_kw)
     90     return decorator.decorator(wrapper)
     91 

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/Clip.py in get_frame(self, t)
     93                 return frame
     94         else:
---> 95             return self.make_frame(t)
     96 
     97     def fl(self, fun, apply_to=[] , keep_duration=True):

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/Clip.py in <lambda>(t)
    134 
    135         #mf = copy(self.make_frame)
--> 136         newclip = self.set_make_frame(lambda t: fun(self.get_frame, t))
    137 
    138         if not keep_duration:

/home/fgarriga/Development/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/moviepy/video/VideoClip.py in <lambda>(gf, t)
    512         `get_frame(t)` by another frame,  `image_func(get_frame(t))`
    513         """
--> 514         return self.fl(lambda gf, t: image_func(gf(t)), apply_to)
    515 
    516     # --------------------------------------------------------------

<ipython-input-89-f2f9bca89afe> in process_image_challenge(image)
      3 
      4 def process_image_challenge(image):
----> 5     return detect_lines_challenge(image)

<ipython-input-100-9ee7558e97c5> in detect_lines_challenge(image)
    210     color = [255,0,0]
    211     thickness = 5
--> 212     draw_hough_lines_average(line_image, hough_lines, color, thickness)
    213 
    214     # Draw the lines on the original image

<ipython-input-100-9ee7558e97c5> in draw_hough_lines_average(img, lines, color, thickness)
    113     right_lane_y = []
    114 
--> 115     for line in lines:
    116         for x1,y1,x2,y2 in line:
    117             to_right_lane = belongs_to_right_lane(x1, y1, x2, y2)

TypeError: 'NoneType' object is not iterable



 56%|█████▌    | 141/251 [00:17<00:13,  7.87it/s]

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