Self-Driving Car Project1- Lane Finding實作

天道酬勤
5 min readMar 12, 2019

--

Lane Finding

Github: https://github.com/bob800530/Find_lane_line

簡介

本魯最近買了一台Mazda CX-5,這台車具備了車道偏移警示的功能,識別上還滿準確的。也因如此,在做這個Project時,特別地有感觸,也好奇做出來的東西,會不會跟車上那台車道攝影機一樣厲害。(以上絕非置入XD)

這是Self-Driving Car的第一個Project,剛開始還不熟悉時,常常把路邊的草跟白色的車當成車道線,想藉由調高Threshold的方式來偵測車道又常常偵測不到。

後來把先前上過的課程耐心地重新複習一遍,並加入多種影像處理後,才一步步完成,其中會運用灰階高斯模糊邊緣偵測霍夫轉換等演算法。並非想像中的直觀,在這過程中讓我了解到

"對於一個軟體工程師而言,耐心也是相當重要滴"

程式碼

Github: https://github.com/bob800530/Find_lane_line/blob/master/P1.ipynb

1.Converted the images to grayscale: OpenCV將圖片由RGB轉成灰階

def grayscale(img):
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

2.Use GaussianBlur to filter noise in image: 低通濾波器GaussianBlur濾除雜訊

def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)

3.Use Canny to detect the edges of image: Canny演算法是一個複合性的邊緣偵測演算法,結合了Gaussian Filter梯度偵測、非最大值抑制、判斷邊界四個演算法去實踐邊緣偵測

def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)

4.Use a four sided polygon to mask two lane lines: 僅偵測車道線可能會出現的那個矩形

def region_of_interest(img, vertices):
...

#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

5.Use Hough to find two lane lines: 運用Hough轉換,在球坐標系中找線

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

6. Extend two land lines: 延伸車道線增加視覺效果

運用高中所學的點斜式延伸所偵測到的直線,完成一張圖片的車道辨識。

影片則可視為多個圖片的組成,亦可藉由這個pipeline 求出車道線。

def draw_extend_line(extend_img,x1, y1, x2, y2):   
m = (y2-y1) / (x2 - x1)
bot_d = 540 - y1
top_d = y1 - 350
if abs(m)>.3 and abs(m)<3:
bot_x = int(x1 + bot_d/m);
top_x = int(x1 - top_d/m);
cv2.line(extend_img,(bot_x,540),(top_x,350),(255,0,255),10)

結論

才第一個Project就學到這麼多影像處理的技巧,一方面覺得這堂課真的太硬了,另一方面又覺得999美金花的好值得阿!!! 或許這就是用自己薪水付學費的好處吧。呵呵

--

--