Lane Line Detection

This project was a great project to learn Python, and used open-cv to detect and draw lane lines on a road. Here is a output video from it.

It works in 6 Steps

Step 1:

Greyscale the image with open-cv

cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Output Image:

Step 2:

Step two is to blur the image using the Gaussian Blur algorithm We do this to prevent unnecessary noise from showing up when we detect the lane lines.

cv2.blur(greyscaled-image, (5,5))

The (5,5) repersents the blurring kernel size, or the ammount to blur the image, with a higher value making the image more blurry.

Output Image:

Step 3:

Detect the edges in the image using the Canny Edge Detection algorithm.This works by looking at the differences in color between pixels to determine if there was a edge. If we didn't blur the image in the previous step, there would be too many edges, and it would add lots of noise to the output.

cv2.Canny(image,50,150)

Output Image:

Step 4:

Select the areas of interest (lane lines) out of the image using opencv. Step one is to make a blank image (or a mask) of the image. Next we create a polygon shape covering where the lane lines will be positioned looking from a dashcam. After that we put that polygon onto our mask, creating a filter to sort out our lane lines. Finally we can combine our mask and our original image to filter out only the lane lines.

#make the polygon to mask the lane lines rows, cols = image.shape[:2] bottom_left = [cols * 0.1, rows * 0.95] top_left = [cols * 0.4, rows * 0.6] bottom_right = [cols * 0.9, rows * 0.95] top_right = [cols * 0.6, rows * 0.6] #create a numpy array of the polygon vertices = np.array([[bottom_left, top_left, top_right, bottom_right]], dtype=np.int32) #create a mask/filter of the polygon's shape cv2.fillPoly(mask, vertices) #apply the mask to the image masked_image = cv2.bitwise_and(image, mask)

Output Image:

Now we're left with just the lane lines.

Step 5:

Detect the lines within our masked image. To do this, we use the hough transform fourmula. What this does is returns the lines it finds within a image. The downside to using this strategy is that it can only detect straight lines within a image, so I might switch to a different approach in the future.

cv2.HoughLinesP(image)

There isn't a output image for this because it generates a mathamatical repersentation of the lane lines rather than a image.

Step 6:

We're almost done! We need to draw the lines on the original image. To do this we iterate through the list of lines from the last step and use the cv2.line() function to draw the lines on the original image.

for line in lines:
  for x1, y1, x2, y2 in line:
      cv2.line(image, (x1, y1), (x2, y2), color,thickness)

Output Image:

There's a Playground for you to try it out below, and here's the github:

Technologies used: