1. 程式人生 > >檢測車道線——2.選擇興趣區域 Region Masking

檢測車道線——2.選擇興趣區域 Region Masking

出現 plot note nes gpo bsp AR nbsp upper

  通過簡單的顏色選擇,我們設法消除了圖像中除了車道線以外的幾乎所有內容。但是,在這一點上,自動提取確切的線條仍然非常棘手,因為我們仍然在周邊檢測到了一些不是線條線的其他物體。

  在這種情況下,我將假定拍攝圖像的前置攝像頭安裝在汽車的固定位置,這樣車道線總是會出現在圖像的同一區域。 所以在提取行車線的時候,只關註這個梯形區域內的圖像,可以避免其他區域的信息造成幹擾。這個梯形區域如果選取地太大,則會引入更多無關信息(比如護欄,樹木等),如果梯形區域選取太小,則可能看不見行車線,所以這裏需要權衡。接下來,我將通過添加一個標準來考慮這一點,僅在我們期望找到車道線的區域考慮用於顏色選擇的像素。

  看看下面的代碼。 變量left_bottom,right_bottom和apex代表了我想保留用於顏色選擇的三角形區域的頂點,同時掩蓋了其他所有內容。 在這裏,我使用三角形面具來說明最簡單的情況,但稍後您將使用四邊形,原則上可以使用任何多邊形。numpy.polyfit(x,y,n)是用於多項式求過已知點的表達式,其中x為源數據點對應的橫坐標,可為行向量、矩陣,y為源數據點對應的縱坐標,可為行向量、矩陣,n為你要擬合的階數,一階直線擬合,二階拋物線擬合,並非階次越高越好,看擬合情況而定。

 1 import matplotlib.pyplot as plt
 2 import matplotlib.image as mpimg
 3 import numpy as np
 4 
 5 # Read in the image and print some stats
 6 image = mpimg.imread(‘E:/spyder/a/a/test.jpg‘)
 7 print(‘This image is: ‘, type(image), 
 8          ‘with dimensions:‘, image.shape)
 9 
10 # Pull out the x and y sizes and make a copy of the image
11 ysize = image.shape[0]
12 xsize = image.shape[1]
13 region_select = np.copy(image)
14 
15 # Define a triangle region of interest 
16 # Keep in mind the origin (x=0, y=0) is in the upper left in image processing
17 # Note: if you run this code, you‘ll find these are not sensible values!!
18 # But you‘ll get a chance to play with them soon in a quiz 
19 left_bottom = [0, 539]
20 right_bottom = [900, 300]
21 apex = [400, 0]
22 
23 # Fit lines (y=Ax+B) to identify the  3 sided region of interest
24 # np.polyfit() returns the coefficients [A, B] of the fit
25 fit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)  
26 fit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1)
27 fit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1)
28 
29 # Find the region inside the lines
30 XX, YY = np.meshgrid(np.arange(0, xsize), np.arange(0, ysize))
31 region_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) & 32                     (YY > (XX*fit_right[0] + fit_right[1])) & 33                     (YY < (XX*fit_bottom[0] + fit_bottom[1]))
34 
35 # Color pixels red which are inside the region of interest
36 region_select[region_thresholds] = [255, 0, 0]
37 
38 # Display the image
39 plt.imshow(region_select)

技術分享圖片

若19~21的代碼改為如下:
19 left_bottom = [0, 540] 20 right_bottom = [900, 540] 21 apex = [400, 300]
則為:

技術分享圖片

檢測車道線——2.選擇興趣區域 Region Masking