In [1]:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
In [45]:
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
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=5):
"""
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
"""
slope_pos = []
slope_neg = []
line_pos = []
line_neg = []
y_max = 320
y_min = 540
for line in lines:
for x1,y1,x2,y2 in line:
if line != None:
slope = (y2-y1)/(x2-x1)
if (slope>0.5) &(slope < 10):
slope_pos.append(slope)
line_pos.append([x1,y1,x2,y2])
# print (line_pos)
elif (slope<-0.5) & (slope > -10):
slope_neg.append(slope)
line_neg.append([x1,y1,x2,y2])
# print (line_neg)
if y1 < y_min:
y_min = y1
elif y2 < y_min:
y_min = y2
if y1 > y_max:
y_max = y1
elif y2 > y_max:
y_max = y2
if line_pos:
x1,y1,x2,y2=find_max_min(slope_pos,line_pos,y_max,y_min)
# print("pos_done")
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
if line_neg:
x1,y1,x2,y2=find_max_min(slope_neg,line_neg,y_max,y_min)
# print("neg_done")
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
# fin_line =[pos_line,neg_line]
# for x1,y1,x2,y2 in fin_line:
# cv2.line(img, (x1, y1), (x2, y2), color, thickness)
def find_max_min(slope,line,y_max,y_min):
slope_mean = np.mean(slope)
# print ("line: ", line)
line_array = np.array(line)
line_mean = np.mean(line_array,axis=0)
# print("line mean: ",line_mean)
y_intercept = line_mean[1] - line_mean[0]*slope_mean
x_max = int((y_max-y_intercept)/slope_mean)
x_min = int((y_min-y_intercept)/slope_mean)
return x_min,y_min,x_max,y_max
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)
# print (lines)
draw_lines(line_img, lines)
return line_img
# Python 3 has support for cool math symbols.
def weighted_img(img, initial_img, α=1., β=5., λ=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 [46]:
# #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) #call as plt.imshow(gray, cmap='gray') to show a grayscaled image
In [76]:
import os
file = os.listdir("test_images/")
for pic in file:
image = mpimg.imread("test_images/"+pic)
gray = grayscale(image)
# plt.imshow(gray, cmap='gray')
blur_gray = gaussian_blur(gray, 3)
# plt.imshow(blur_gray)
edges = canny(blur_gray,150,200)
# plt.imshow(edges)
# imshape = image.shape
vertices = np.array([[(0,540),(450,320),(490,320), (960,540)]], dtype=np.int32)
masked_edges = region_of_interest(edges,vertices)
# plt.imshow(masked_edges)
line_image = hough_lines(masked_edges,2,np.pi/180,80,100,150)
# plt.imshow(line_image)
lines_edges = weighted_img(line_image, image)
# plt.imshow(lines_edges)
#save the
pic = pic.replace(".jpg","" )
fin = "test_images_output/"+pic+"_finish"+".jpg"
plt.imsave(fin, lines_edges)
In [78]:
output_file = os.listdir("test_images_output/")
for i in output_file:
plt.figure()
path = "test_images_output/"+i
fin_image = mpimg.imread(path)
plt.imshow(fin_image)
In [ ]:
In [49]:
from moviepy.editor import VideoFileClip
from IPython.display import HTML
In [83]:
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 with lines are drawn on lanes)
# image = mpimg.imread(image)
gray = grayscale(image)
blur_gray = gaussian_blur(gray, 3)
edges = canny(blur_gray,150,200)
vertices = np.array([[(0,540),(460,320),(500,320), (960,540)]], dtype=np.int32)
masked_edges = region_of_interest(edges,vertices)
line_image = hough_lines(masked_edges,2,np.pi/180,80,100,150)
lines_edges = weighted_img(line_image, image)
return lines_edges
In [84]:
challenge_output = 'extra.mp4'
clip2 = VideoFileClip('challenge.mp4')
challenge_clip = clip2.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)
In [85]:
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output))
Out[85]:
In [86]:
white_output = 'white.mp4'
clip1 = VideoFileClip("solidWhiteRight.mp4")
# white_clip = clip1
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
%time white_clip.write_videofile(white_output, audio=False)
In [87]:
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output))
Out[87]:
In [88]:
yellow_output = 'yellow.mp4'
clip2 = VideoFileClip('solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)
In [89]:
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(yellow_output))
Out[89]: