Finding Lanes on the Road

The objective of this project is to develop a software pipeline to identify lane lines on the road. The software pipeline is first tested on a series of images and then applied over a video stream.

Pipeline

Importing Required Packages/Dependencies


In [69]:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline

Helper Functions


In [70]:
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=[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
    """
    
    imshape = image.shape
    leftMinY = 0
    leftMaxY = imshape[0]
    leftMinX = 0
    leftMaxX = 0
    
    rightMinY = 0
    rightMaxY = imshape[0]
    rightMinX = 0
    rightMaxX = 0
    
    m1 = 1
    m2 = 1
      
        
    for line in lines:
        for x1,y1,x2,y2 in line:
            slope = (y2 - y1)/(x2- x1)
            if slope < 0:
                m1 = slope
                if(leftMinY < y1):
                    leftMinY = y1
                    leftMinX = x1
                if(leftMaxY > y2):
                    leftMaxY = y2
                    leftMaxX = x2
            elif slope > 0:
                m2 = slope
                if(rightMinY < y2):
                    rightMinY = y2
                    rightMinX = x2
                if(rightMaxY > y1):
                    rightMaxY = y1
                    rightMaxX = x1
    
    leftMinX = np.uint16(leftMinX - ((leftMinY - imshape[0])/m1)) #x2 - (y2 - y1) / m1
    rightMinX = np.uint16(rightMinX - ((rightMinY - imshape[0] )/m2))
    cv2.line(img, (leftMinX, imshape[0]), (leftMaxX, leftMaxY), color, thickness)
    cv2.line(img, (rightMinX, imshape[0]), (rightMaxX, rightMaxY), color, thickness)
    
    #for line in lines:
        #for x1,y1,x2,y2 in line:
            #cv2.line(img, (x1, y1), (x2, y2), [255,255,0], 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[0], img.shape[1], 3), dtype=np.uint8)
    draw_lines(line_img, lines,thickness=6)
    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, β, λ)


def laneDetection(inputImage, boundaries, preProcessingFlag=True, intelligentFlag = True, extrapolateFlag= True, showMask=False,kernel_size = 5, min_line_len = 20,max_line_gap = 6 , low_threshold = 95,high_threshold =  120,rho = 1,theta = np.pi/180,threshold = 10, color=[255,0,0],thickness=2,alpha=5,beta=10):
    #img = mpimg.imread(inputImage)
    #img = (mpimg.imread(test)*255).astype('uint8')
    img = inputImage
    if preProcessingFlag==True:
         img = preProcess(img, boundaries)
    gray = grayscale(img) # convert image from RGB to gray
    grayG = gaussian_blur(gray, kernel_size) #Gaussian filter is applied to remove the scharp edges
    cannyImg = canny(grayG, low_threshold, high_threshold) # apply canny edge detection algorithm

    # mask detection
    if not intelligentFlag:
        # add simple mask - handmade
        imshape = cannyImg.shape
        vertices = np.array([[(0,imshape[0]),(imshape[1]/2+3*imshape[0]/70, imshape[0]/3+imshape[0]/4), (imshape[1]/2+imshape[0]/70, imshape[0]/3+imshape[0]/4), (imshape[1],imshape[0])]], dtype=np.int32)
        masked = region_of_interest(cannyImg,vertices)
    else:
        # find the horizon line - adaptive masking
        # better way is finding slope and intersection between two lines
        masked = cannyImg

    houghImg, successfulFlag = hough_lines(masked, rho, theta, threshold, min_line_len, max_line_gap,color,thickness,intelligentFlag, extrapolateFlag,showMask,alpha,beta)
    if successfulFlag==True:
        houghRGB = np.dstack((houghImg*(color[0]//255), houghImg*(color[1]//255), houghImg*(color[2]//255))) # *(color[1]/255)
        result = weighted_img(inputImage, houghRGB,  α=1., β=0.8, λ=0.)
        return result
    else:
        return inputImage

Reading a sample Image


In [71]:
image = mpimg.imread('test_images/solidWhiteRight.jpg')
print('This image is:', type(image), 'with dimensions:', image.shape)
plt.imshow(image)


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

Testing on Images


In [72]:
import os

imgFolder = "test_images"
saveFolder = "testResults/images"
imgs = os.listdir(imgFolder)
for imageName in imgs:
    inputImagePath = os.path.join(imgFolder, imageName)
    image = cv2.imread(inputImagePath)
    gray = grayscale(image)
    
    kernel_size = 5
    blur_gray =  gaussian_blur(gray, kernel_size)
    high_threshold = 150
    low_threshold = high_threshold / 3
    edges = canny(blur_gray, low_threshold, high_threshold)
    imshape = image.shape
    vertices = np.array([[(0, imshape[0]),(imshape[1],imshape[0]),(imshape[1]/2, imshape[0]/2 + 50) ]], dtype=np.int32)
    masked_edges = region_of_interest(edges, vertices)
    rho = 2 
    theta = np.pi/180 
    threshold = 25    
    min_line_len = 40 
    max_line_gap = 70 
    
    line_image = hough_lines(masked_edges, rho, theta, threshold, min_line_len, max_line_gap)
    color_edges = np.dstack((edges, edges, edges)) 
    result = weighted_img(color_edges,  line_image)
    
    outputImagePath = os.path.join(saveFolder, imageName)
    cv2.imwrite(outputImagePath, result)
    plt.imshow(result)


Testing on Videos


In [73]:
from moviepy.editor import VideoFileClip
from IPython.display import HTML


def process_image(image):
    gray = grayscale(image)
    kernel_size = 5
    blur_gray =  gaussian_blur(gray, kernel_size)
    high_threshold = 150
    low_threshold = high_threshold / 3
    edges = canny(blur_gray, low_threshold, high_threshold)
    imshape = image.shape
    vertices = np.array([[(0, imshape[0]),(imshape[1],imshape[0]),(imshape[1]/2, imshape[1]/3 - 1) ]], dtype=np.int32)
    masked_edges = region_of_interest(edges, vertices)
    rho = 2 
    theta = np.pi/180 
    threshold = 25    
    min_line_len = 40 
    max_line_gap = 70 
    line_image = hough_lines(masked_edges, rho, theta, threshold, min_line_len, max_line_gap)
    #color_edges = np.dstack((masked_edges, masked_edges, masked_edges)) 
    result = weighted_img(image,  line_image)
    return result


whiteLaneVideo = VideoFileClip("test_videos/solidWhiteRight.mp4")
yellowLaneVideo = VideoFileClip("test_videos/solidYellowLeft.mp4")
whiteLaneResult = 'testResults/videos/solidWhiteRight.mp4'
yellowLaneResult = 'testResults/videos/solidYellowLeft.mp4'

whiteLaneProcessed = whiteLaneVideo.fl_image(process_image) 
yellowLaneProcessed = yellowLaneVideo.fl_image(process_image)

%time whiteLaneProcessed.write_videofile(whiteLaneResult, audio=False)
%time yellowLaneProcessed.write_videofile(yellowLaneResult, audio=False)


[MoviePy] >>>> Building video testResults/videos/solidWhiteRight.mp4
[MoviePy] Writing video testResults/videos/solidWhiteRight.mp4
100%|█████████▉| 221/222 [00:06<00:00, 32.86it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: testResults/videos/solidWhiteRight.mp4 

CPU times: user 2.53 s, sys: 220 ms, total: 2.75 s
Wall time: 7.66 s
[MoviePy] >>>> Building video testResults/videos/solidYellowLeft.mp4
[MoviePy] Writing video testResults/videos/solidYellowLeft.mp4
100%|█████████▉| 681/682 [00:21<00:00, 32.14it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: testResults/videos/solidYellowLeft.mp4 

CPU times: user 7.46 s, sys: 940 ms, total: 8.4 s
Wall time: 22.7 s

White Lane Result


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


Out[74]:

Yellow Lane Result


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


Out[75]:

Reflection

How the pipeline works

The pipeline first detects lanes in a set of images and uses the same techinque to detect lanes in a stream of video. The RGB images are converted to grayscale and gaussian blur is applied over them. Using canny edge detection, we then find the edges and extrapolate lines over the strongest edges. For a video stream, we essentially perform the same operations over every video frame which is inturn an image. The fl_image method comes in handy during lane detection on video streams.

Shortcomings

The above algorithm works best for smooth and straight lanes. When used on lanes with bumps and curves, this algorithm will fail to detect lanes. This algorithm will also fail in the event of bad weather.

Improvements

The current implemntation has some jitters. Pre-processing the images would result in a smoother extrapolation. We can use the intelligent flag on hough lines coupled with other parameters to detect curved lanes.