Road Lane Detection with OpenCV and Python

Posted by Jaime Arrocha on Wednesday, July 14, 2021

TOC

Introduction


This was my first attempt at working at this project based on the Udacity course. I found it an amazing experience to learn about this because once you get through all the math and see the results, you get a very good feeling of accomplishment, understanding, and humility on the problem to be solved.

Development


The code below is done twice, once for building single images and then the refactoring of the code to deal with videos.

Here’s an example image used to implement our algorithm pipeline.

png

Starting Code

Here’s the starting code, although it was modified a little to make it easier to build around it.

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.
    `vertices` should be a numpy array of integer points.
    """
    #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 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)
    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, β, γ)

Build a Lane Finding pipeline for single images

Here’s the part of the code that work with the test images. You can see the output below.

import numpy.polynomial.polynomial as poly

imageList = []
processImgList = []
test_images_loc = "test_images"
images = ["solidWhiteRight.jpg",
          "solidWhiteCurve.jpg",
          "solidYellowCurve.jpg",
          "solidYellowCurve2.jpg",
          "solidYellowLeft.jpg",
          "whiteCarLaneSwitch.jpg"]

class Image:
    def __init__(self, name, location):
        self.name = name
        self.location = location
        self.width = 0
        self.height = 0
        self.image = 0
        self.procImage = 0
        self.lines = 0

        # Keep track of left and right lane points
        self.leftLanePoints = []
        self.rightLanePoints = []
        
        # Used to draw final line
        self.left_x_top = 0
        self.left_x_bottom = 0
        self.left_y_top = 0
        self.left_y_bottom = 0
        self.right_x_bottom = 0
        self.right_x_top = 0
        self.right_y_bottom = 0
        self.right_y_top = 0

    def open(self):
        print("Opening image: " + self.name)
        img = mpimg.imread(self.location + '/' + self.name)
        imshape = img.shape
        self.height = imshape[0]
        self.width = imshape[1]
        self.image = img

def draw_lines(img, lines, color=[255, 0, 0], thickness=2):
    """
    Modification of the previous function to return the modified image with lines drawn.
    """
    for line in lines:
        for x1,y1,x2,y2 in line:
            cv2.line(img, (x1, y1), (x2, y2), color, thickness)
    
    return img

def show_imgs(imgList, proc=False):
    count = len(imgList)
    cols = 2
    rows = count//cols
    fig=plt.figure(figsize=(8, 8))
    for i in range(0, count):
        img_name = imgList[i].name
        fig.add_subplot(rows, cols, i+1)
        plt.title(img_name)
        if proc == True:
            plt.imshow(imgList[i].procImage)
        else:    
            plt.imshow(imgList[i].image)
    plt.tight_layout()
    plt.show()

def show_imgsVS(imgList, greyScale=False):
    count = len(imgList)
    cols = 2
    rows = 6
    fig=plt.figure(figsize=(12, 12), dpi=80)
    for i in range(0, count):
        img_name = imgList[i//2].name
        fig.add_subplot(rows, cols, (i*2)+1)
        plt.title(img_name)
        plt.imshow(imgList[i].image)
        
        fig.add_subplot(rows, cols, (i*2)+2)
        plt.title(img_name)
        if greyScale == True:
            plt.imshow(imgList[i].procImage, cmap='gray')
        else:
            plt.imshow(imgList[i].procImage)
    plt.tight_layout()
    plt.show()

def hough_transform(img, rho, theta, threshold, min_line_len, max_line_gap):
    """
    We need a function that returns the lines.
    """
    lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
    return lines

def draw_hough_lines(height, width, lines, color=[255, 0, 0], thickness=2):
    line_img = np.zeros((height, width, 3), dtype=np.uint8)
    return draw_lines(line_img, lines, color, thickness)

# Create image class for each loaded image
def InitImages():
    for x in images:
        img = Image(x, test_images_loc)
        img.open()
        imageList.append(img)

# Get grayscale for each image
def GetImgGreyscale():
    for x in imageList:
        x.procImage = grayscale(x.image)

# Apply Gaussian smoothing
def GetImgGaussianSmoothing():
    kernel_size = 3
    for x in imageList:
        x.procImage = gaussian_blur(x.procImage, kernel_size)

# Define our parameters for Canny and apply
def GetImgCanny():
    low_threshold = 100
    high_threshold = 150
    for x in imageList:
        x.procImage = canny(x.procImage, low_threshold, high_threshold)

# Define a four-sided polygon to mask
def GetImgRoI():
    for x in imageList:
        # Getting specifics for each image 
        height = x.height
        width = x.width
        bottom_offset = 0.9
        top_offset = 0.465

        x.left_x_bottom = width - (width*bottom_offset)
        x.left_x_top = width*top_offset
        x.right_x_bottom = width*bottom_offset
        x.right_x_top = (width*.5) + 50

        x.left_y_bottom = height
        x.left_y_top = height*.6
        x.right_y_bottom = height
        x.right_y_top = height*.6

        left_bottom = (x.left_x_bottom, x.left_y_bottom)
        left_top = (x.left_x_top, x.left_y_top)
        right_bottom = (x.right_x_bottom, x.right_y_bottom)
        right_top = (x.right_x_top, x.right_y_top)

        vertices = np.array([[left_bottom, left_top, right_top, right_bottom]], dtype=np.int32)
        x.procImage = region_of_interest(x.procImage, vertices)

# Define the Hough transform parameters
def GetImgRoughTransform():
    # Make a blank the same size as our image to draw on
    rho = 2                         # distance resolution in pixels of the Hough grid
    theta = 1 * np.pi/180           # angular resolution in radians of the Hough grid
    threshold = 15                  # minimum number of votes (intersections in Hough grid cell)
    min_line_length = 50             # minimum number of pixels making up a line
    max_line_gap = 150               # maximum gap in pixels between connectable line segments
    for x in imageList:
        x.lines = hough_transform(x.procImage, rho, theta, threshold, min_line_length, max_line_gap)
        x.procImage = draw_hough_lines(x.height, x.width, x.lines)
        x.procImage = weighted_img(x.procImage, x.image, 0.8, 1, 0)

# Separate the lane points
def GetImgLanePoints():
    for x in imageList:
        imgMiddle = x.width/2

        for line in x.lines:
            for x1,y1,x2,y2 in line:
                dx = x2-x1
                dy = y2-y1

                # Line not increasing
                if dx == 0 or dy == 0:
                    continue

                m = dy/dx

                # Discard lines with small slopes
                slope_threshold = 0.2
                if abs(m) < slope_threshold:
                    continue

                # Indentify left and right lanes
                if x1 < imgMiddle and x2 < imgMiddle:
                    x.leftLanePoints.append([[x1,y1,x2,y2]])
                elif x1 >= imgMiddle and x2 >=imgMiddle:
                    x.rightLanePoints.append([[x1,y1,x2,y2]])

        # With the points separated, now this points will be drawn into the
        # image with different colors
        
        # Mark left lane points
        x.procImage = draw_hough_lines(x.height, x.width, x.leftLanePoints, [0,0,255], 10)
        # Mark right lane points
        x.procImage = draw_lines(x.procImage, x.rightLanePoints, [255,0,0], 10)

# Calculate line fit for each lane
def GetImgLineFit():
    for x in imageList:
        xs = []
        ys = []
        for line in x.leftLanePoints:
                for x1, y1, x2, y2 in line:
                    xs.append(x1)
                    xs.append(x2)
                    ys.append(y1)
                    ys.append(y2)

        z = poly.polyfit(xs, ys, 1)
        # Extrapolate to the top and bottom of the special regions
        y_bottom = poly.polyval(x.left_x_bottom, z)
        y_top = poly.polyval(x.left_x_top, z)
        # print("Debug: Top Left: Y: " + str(y_top) + " X: " + str(x.left_x_top))
        # print("Debug: Bottom Left: Y: " + str(y_bottom) + " X: " + str(x.left_x_bottom))

        new_lines = [[[int(x.left_x_bottom), int(y_bottom), int(x.left_x_top), int(y_top)]]]
        line_img = np.zeros((x.height, x.width, 3), dtype=np.uint8)
        x.procImage = draw_lines(line_img, new_lines, [0,255,0], 10)

        xs.clear()
        ys.clear()
        for line in x.rightLanePoints:
                for x1, y1, x2, y2 in line:
                    xs.append(x1)
                    xs.append(x2)
                    ys.append(y1)
                    ys.append(y2)

        z = poly.polyfit(xs, ys, 1)
        # Extrapolate to the top and bottom of the special regions
        y_bottom = poly.polyval(x.right_x_bottom, z)
        y_top = poly.polyval(x.right_x_top, z)
        # print("Debug: Top Right: Y: " + str(y_top) + " X: " + str(x.right_x_top))
        # print("Debug: Bottom Right: Y: " + str(y_bottom) + " X: " + str(x.right_x_bottom))

        new_lines = [[[int(x.right_x_bottom), int(y_bottom), int(x.right_x_top), int(y_top)]]]
        x.procImage = draw_lines(x.procImage, new_lines, [0,255,0], 10)
        x.procImage = weighted_img(x.procImage, x.image, 0.8, 1, 0)
        
        
#Pipeline to work with the images
InitImages()
# show_imgs(imageList)

GetImgGreyscale()
# show_imgsVS(imageList, True)

GetImgGaussianSmoothing()
# show_imgsVS(imageList, True)

GetImgCanny()
# show_imgs(imageList, True)

GetImgRoI()
# show_imgs(imageList, True)

GetImgRoughTransform()
# show_imgs(imageList, True)

GetImgLanePoints()
# show_imgs(imageList, True)

GetImgLineFit()
show_imgs(imageList, True)
Opening image: solidWhiteRight.jpg
Opening image: solidWhiteCurve.jpg
Opening image: solidYellowCurve.jpg
Opening image: solidYellowCurve2.jpg
Opening image: solidYellowLeft.jpg
Opening image: whiteCarLaneSwitch.jpg

png

Build a Lane Finding pipeline for videos

The code is very similar but transformed to deal with videos. This gives you an idea of how things are processed in the field. Output videos are shown below.

# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
class Image:
    def __init__(self, name="", location=""):
        self.name = name
        self.location = location
        self.width = 0
        self.height = 0
        self.image = 0
        self.procImage = 0
        self.lines = 0

        # Keep track of left and right lane points
        self.leftLanePoints = []
        self.rightLanePoints = []
        
        # Used to draw final line
        self.left_x_top = 0.0
        self.left_x_bottom = 0.0
        self.left_y_top = 0.0
        self.left_y_bottom = 0.0
        self.right_x_bottom = 0.0
        self.right_x_top = 0.0
        self.right_y_bottom = 0.0
        self.right_y_top = 0.0

    def open(self):
        print("Opening image: " + self.name)
        img = mpimg.imread(self.location + '/' + self.name)
        imshape = img.shape
        self.height = imshape[0]
        self.width = imshape[1]
        self.image = img
    
    def initVideoImg(self):
        self.height = 540
        self.width = 960
    
    def SetVideoDim(self, w, h):
        self.height = h
        self.width = w

def show_imgs(imgList, proc=False):
    count = len(imgList)
    cols = 2
    rows = count//cols
    fig=plt.figure(figsize=(8, 8))
    for i in range(0, count):
        img_name = imgList[i].name
        fig.add_subplot(rows, cols, i+1)
        plt.title(img_name)
        if proc == True:
            plt.imshow(imgList[i].procImage)
        else:    
            plt.imshow(imgList[i].image)
    plt.tight_layout()
    plt.show()

def show_imgsVS(imgList, greyScale=False):
    count = len(imgList)
    cols = 2
    rows = 6
    fig=plt.figure(figsize=(12, 12), dpi=80)
    for i in range(0, count):
        img_name = imgList[i//2].name
        fig.add_subplot(rows, cols, (i*2)+1)
        plt.title(img_name)
        plt.imshow(imgList[i].image)
        
        fig.add_subplot(rows, cols, (i*2)+2)
        plt.title(img_name)
        if greyScale == True:
            plt.imshow(imgList[i].procImage, cmap='gray')
        else:
            plt.imshow(imgList[i].procImage)
    plt.tight_layout()
    plt.show()

def hough_transform(img, rho, theta, threshold, min_line_len, max_line_gap):
    """
    We need a function that returns the lines.
    """
    lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
    return lines

def draw_hough_lines(height, width, lines, color=[255, 0, 0], thickness=2):
    line_img = np.zeros((height, width, 3), dtype=np.uint8)
    return draw_lines(line_img, lines, color, thickness)

# Create image class for each loaded image
def InitImages(imgLocation, imgName):
    img = Image(imgName, imgLocation)
    img.open()
    return img

# Get grayscale for each image
def GetImgGreyscale(img):
    img.procImage = grayscale(img.image)

# Apply Gaussian smoothing
def GetImgGaussianSmoothing(img):
    kernel_size = 3
    img.procImage = gaussian_blur(img.procImage, kernel_size)

# Define our parameters for Canny and apply
def GetImgCanny(img):
    low_threshold = 100
    high_threshold = 150
    img.procImage = canny(img.procImage, low_threshold, high_threshold)

# Define a four-sided polygon to mask
def GetImgRoI(img):
    # Getting specifics for each image 
    height = img.height
    width = img.width
    bottom_offset = 0.9
    top_offset = 0.455

    img.left_x_bottom = width - (width*bottom_offset)
    img.left_x_top = width*top_offset
    img.right_x_bottom = width*bottom_offset
    img.right_x_top = (width*0.5) + 50.0

    img.left_y_bottom = height
    img.left_y_top = height*.6
    img.right_y_bottom = height
    img.right_y_top = height*.6

    left_bottom = (img.left_x_bottom, img.left_y_bottom)
    left_top = (img.left_x_top, img.left_y_top)
    right_bottom = (img.right_x_bottom, img.right_y_bottom)
    right_top = (img.right_x_top, img.right_y_top)

    vertices = np.array([[left_bottom, left_top, right_top, right_bottom]], dtype=np.int32)
    img.procImage = region_of_interest(img.procImage, vertices)

# Define the Hough transform parameters
def GetImgRoughTransform(img):
    # Make a blank the same size as our image to draw on
    rho = 2                         # distance resolution in pixels of the Hough grid
    theta = 1 * np.pi/180           # angular resolution in radians of the Hough grid
    threshold = 15                  # minimum number of votes (intersections in Hough grid cell)
    min_line_length = 50             # minimum number of pixels making up a line
    max_line_gap = 150               # maximum gap in pixels between connectable line segments
    
    img.lines = hough_transform(img.procImage, rho, theta, threshold, min_line_length, max_line_gap)
    img.procImage = draw_hough_lines(img.height, img.width, img.lines)
    img.procImage = weighted_img(img.procImage, img.image, 0.8, 1, 0)

# Separate the lane points
def GetImgLanePoints(img):
   
    imgMiddle = img.width/2

    for line in img.lines:
        for x1,y1,x2,y2 in line:
            dx = x2-x1
            dy = y2-y1

            # Line not increasing
            if dx == 0 or dy == 0:
                continue

            m = dy/dx

            # Discard lines with small slopes
            slope_threshold = 0.2
            if abs(m) < slope_threshold:
                continue

            # Indentify left and right lanes
            if x1 < imgMiddle and x2 < imgMiddle:
                img.leftLanePoints.append([[x1,y1,x2,y2]])
            elif x1 >= imgMiddle and x2 >=imgMiddle:
                img.rightLanePoints.append([[x1,y1,x2,y2]])

    # With the points separated, now this points will be drawn into the
    # image with different colors
    
    # Mark left lane points
    img.procImage = draw_hough_lines(img.height, img.width, img.leftLanePoints, [0,0,255], 10)
    # Mark right lane points
    img.procImage = draw_lines(img.procImage, img.rightLanePoints, [255,0,0], 10)

# Calculate line fit for each lane
def GetImgLineFit(img):
    xs = []
    ys = []
    for line in img.leftLanePoints:
            for x1, y1, x2, y2 in line:
                xs.append(x1)
                xs.append(x2)
                ys.append(y1)
                ys.append(y2)

    z = poly.polyfit(xs, ys, 1)
    # Extrapolate to the top and bottom of the special regions
    y_bottom = poly.polyval(img.left_x_bottom, z)
    y_top = poly.polyval(img.left_x_top, z)
    # print("Debug: Top Left: Y: " + str(y_top) + " X: " + str(x.left_x_top))
    # print("Debug: Bottom Left: Y: " + str(y_bottom) + " X: " + str(x.left_x_bottom))

    new_lines = [[[int(img.left_x_bottom), int(y_bottom), int(img.left_x_top), int(y_top)]]]
    line_img = np.zeros((img.height, img.width, 3), dtype=np.uint8)
    img.procImage = draw_lines(line_img, new_lines, [0,255,0], 10)

    xs.clear()
    ys.clear()
    for line in img.rightLanePoints:
            for x1, y1, x2, y2 in line:
                xs.append(x1)
                xs.append(x2)
                ys.append(y1)
                ys.append(y2)

    z = poly.polyfit(xs, ys, 1)
    # Extrapolate to the top and bottom of the special regions
    y_bottom = poly.polyval(img.right_x_bottom, z)
    y_top = poly.polyval(img.right_x_top, z)
    # print("Debug: Top Right: Y: " + str(y_top) + " X: " + str(x.right_x_top))
    # print("Debug: Bottom Right: Y: " + str(y_bottom) + " X: " + str(x.right_x_bottom))

    new_lines = [[[int(img.right_x_bottom), int(y_bottom), int(img.right_x_top), int(y_top)]]]
    img.procImage = draw_lines(img.procImage, new_lines, [0,255,0], 10)
    img.procImage = weighted_img(img.procImage, img.image, 0.8, 1, 0)

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 where lines are drawn on lanes)
    
    img = Image()
    img.image = image
    img.SetVideoDim(960, 540)
    
    GetImgGreyscale(img)
    GetImgGaussianSmoothing(img)
    GetImgCanny(img)
    GetImgRoI(img)
    GetImgRoughTransform(img)
    GetImgLanePoints(img)
    GetImgLineFit(img)

    return img.procImage

png

png

Conclusion

For the first problem, a process to smooth out the current result with the past frame result will make it less jumpy. But I’m not sure this is the correct result given my current knowledge because this smoothing process could not work with the car going at high speeds. I think a better approach could be better lane identification.

The other problem is the curved lanes and I think this can be easily addressed with a regression result with higher degree order coefficients. The current problem I face is how to calculate the extrapolated lane. How far in the lane is safe enough to calculate an extrapolation? I will come back to this problem and improve this project once I get more knowledge on lane identification.

Overall, an very interesting project to understand the kind of problems this field has in regards to environment perception.