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 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.
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 :#importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline
In :#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:<matplotlib.image.AxesImage at 0x7f9747c6d668>
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 :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 intensity_threshold(img, gray_threshold): threshold = img[:,:] < gray_threshold img[threshold] = 0 return img def mask_color_hsv(image_hsv, image, lower, upper): mask = cv2.inRange(image_hsv, lower, upper) image_masked = cv2.bitwise_and(image, image, mask = mask) return image_masked 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 # 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=4): """ 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 draw_lines_fit(img, lines, color=[255, 0, 0], thickness=12): xl =  yl =  xr =  yr =  img_width = img.shape img_mid = img.shape/2 for line in lines: for x1, y1, x2, y2 in line: if (x1 < img_mid): xl.extend([x1, x2]) yl.extend([y1, y2]) else: xr.extend([x1, x2]) yr.extend([y1, y2]) if (xl and yl): f_l = np.poly1d(np.polyfit(xl, yl, 1)) cv2.line(img, (0, int(f_l(0))), (int(img_mid-64), int(f_l(img_mid-64))), color, thickness) if (xr and yr): f_r = np.poly1d(np.polyfit(xr, yr, 1)) cv2.line(img, (int(img_mid+64), int(f_r(img_mid+64))), (int(img_width), int(f_r(img_width))), color, thickness) def filter_lines(lines): bad_lines =  filtered_lines =  for line in lines: for x1,y1,x2,y2 in line: slope = float((y1-y2)/(x2-x1)) if ((slope >= np.tan(np.pi/4)) or (slope <= np.tan(3*np.pi/4))): bad_lines.append(line) else: filtered_lines.append(line) return filtered_lines def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap): """ `img` should be the output of a Canny transform. Returns an array of hough lines. """ lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array(), minLineLength=min_line_len, maxLineGap=max_line_gap) return lines # Python 3 has support for cool math symbols. def weighted_img(img, initial_img, α=0.7, β=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 :import os image_names = os.listdir("test_images/")
Build the pipeline and run your solution on all test_images. Make copies into the test_images 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 :# TODO: Build your pipeline that will draw lane lines on the test_images # then save them to the test_images directory. def process_image (image, show_output = True, mask_lower_white = np.array([0,0,223]), mask_upper_white = np.array([255, 32, 255]), mask_lower_yellow = np.array([20, 100, 100]), mask_upper_yellow = np.array([30, 255, 255]), gaussian_kernel_size = 5, gaussian_iterations = 5, canny_low_threshold = 50, canny_high_threshold = 150, hough_rho = 4, hough_theta = np.pi/180, hough_threshold = 10, hough_min_line_length = 8, hough_max_line_gap = 16): if (show_output): plt.figure() plt.imshow(image) # Convert to HSV for white/yellow masking image_hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) # Mask white image_white = mask_color_hsv(image_hsv, image, mask_lower_white, mask_upper_white) if (show_output): plt.figure() plt.imshow(image_white) # Mask yellow image_yellow = mask_color_hsv(image_hsv, image, mask_lower_yellow, mask_upper_yellow) if (show_output): plt.figure() plt.imshow(image_yellow) # Combine both masks gray = grayscale(image_white + image_yellow) if (show_output): plt.figure() plt.imshow(gray, cmap='gray') # Histogram Equalization gray = cv2.equalizeHist(gray) if (show_output): plt.figure() plt.imshow(gray, cmap='gray') # Apply Gaussian smoothing blur_gray = gaussian_blur(gray, gaussian_kernel_size) if (show_output): plt.figure() plt.imshow(blur_gray, cmap='gray') # Apply Canny edge dectector edges = canny(blur_gray, canny_low_threshold, canny_high_threshold) if (show_output): plt.figure() plt.imshow(edges, cmap='gray') # Mask Canny edges using a polygonal ROI imshape = image.shape vertices = np.array([[(0,imshape),(imshape/2 - 64, imshape/2 + 64), (imshape/2 + 64, imshape/2 +64), (imshape,imshape)]], dtype=np.int32) masked_edges = region_of_interest(edges, vertices) if (show_output): masked_edges_roi = image cv2.line(masked_edges_roi, tuple(vertices), tuple(vertices), [0, 0, 255], 8) cv2.line(masked_edges_roi, tuple(vertices), tuple(vertices), [0, 0, 255], 8) cv2.line(masked_edges_roi, tuple(vertices), tuple(vertices), [0, 0, 255], 8) cv2.line(masked_edges_roi, tuple(vertices), tuple(vertices), [0, 0, 255], 8) plt.figure() plt.imshow(masked_edges_roi) plt.figure() plt.imshow(masked_edges, cmap='gray') # Apply Hough transform to detect lines lines = hough_lines(masked_edges, hough_rho, hough_theta, hough_threshold, hough_min_line_length, hough_max_line_gap) # Prune outliers filtered_lines = filter_lines(lines) line_img = np.zeros((image.shape, image.shape, 3), dtype=np.uint8) draw_lines(line_img, lines, [0, 255, 0]) draw_lines(line_img, filtered_lines) if (show_output): plt.figure() plt.imshow(line_img) # Fit lines fitted_lines_img = np.zeros((image.shape, image.shape, 3), dtype=np.uint8) draw_lines_fit(fitted_lines_img, filtered_lines) # Combine input with fitted lines for annotation result = weighted_img(image, fitted_lines_img) if (show_output): plt.figure() plt.imshow(fitted_lines_img) return result for image_name in image_names: print(image_name) image = mpimg.imread('test_images/' + image_name) res_img = process_image(image) plt.figure() plt.imshow(res_img)
solidWhiteCurve.jpg solidWhiteRight.jpg solidYellowCurve.jpg solidYellowCurve2.jpg solidYellowLeft.jpg whiteCarLaneSwitch.jpg