使用Python+OpenCV進行實時車道檢測
如上所示,對蒙版圖像應用閾值后,我們只得到輸出圖像中的車道標線。現在我們可以通過霍夫線變換很容易地檢測出這些標記。霍夫線變換霍夫線變換是一種檢測任何可以用數學方法表示形狀的方法。例如,它可以檢測矩形、圓、三角形或直線等形狀。我們感興趣的是檢測可以表示為直線的車道標線。這是相關文檔:https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html在執行圖像閾值化后對圖像應用霍夫線變換將提供以下輸出:

我們需要對所有幀執行此過程,然后將生成的幀縫合到新視頻中。用OpenCV在Python中實現車道檢測是時候用Python實現這個車道檢測項目了!我推薦使用Google Colab,因為構建車道檢測系統需要計算能力。首先導入所需的庫:import osimport reimport cv2import numpy as npfrom tqdm import tqdm_notebookimport matplotlib.pyplot as plt讀取視頻幀我已經從這個YouTube視頻中抽取了一些視頻片段。你可以從這個鏈接下載:https://drive.google.com/file/d/1e4cc4zFFna3Owyym6aq7ZXoquHA2l95O/view?usp=sharing。# 獲取幀的文件名col_frames = os.listdir('frames/')col_frames.sort(key=lambda f: int(re.sub('D', '', f)))
# 加載幀col_images=[]for i in tqdm_notebook(col_frames): img = cv2.imread('frames/'+i) col_images.append(img)讓我們繪制一個幀:# 指定一個索引idx = 457
# plot frameplt.figure(figsize=(10,10))plt.imshow(col_images[idx][:,:,0], cmap= "gray")plt.show()

幀掩碼創建我們感興趣的區域是一個多邊形。我們想掩蓋除了這個區域以外的一切。因此,我們首先必須指定多邊形的坐標,然后使用它來準備幀掩碼:# 創建0矩陣stencil = np.zeros_like(col_images[idx][:,:,0])
# 指定多邊形的坐標polygon = np.array([[50,270], [220,160], [360,160], [480,270]])
# 用1填充多邊形cv2.fillConvexPoly(stencil, polygon, 1)# 畫出多邊形plt.figure(figsize=(10,10))plt.imshow(stencil, cmap= "gray")plt.show()

# 應用該多邊形作為掩碼img = cv2.bitwise_and(col_images[idx][:,:,0], col_images[idx][:,:,0], mask=stencil)
# plot masked frameplt.figure(figsize=(10,10))plt.imshow(img, cmap= "gray")plt.show()

圖像預處理我們必須對視頻幀執行一些圖像預處理操作來檢測所需的車道。預處理操作包括:圖像閾值化霍夫線變換1.圖像閾值化# 應用圖像閾值化ret, thresh = cv2.threshold(img, 130, 145, cv2.THRESH_BINARY)
# 畫出圖像plt.figure(figsize=(10,10))plt.imshow(thresh, cmap= "gray")plt.show()

2.霍夫線變換lines = cv2.HoughLinesP(thresh, 1, np.pi/180, 30, maxLineGap=200)
# 創建原始幀的副本dmy = col_images[idx][:,:,0].copy()
# 霍夫線for line in lines: x1, y1, x2, y2 = line[0] cv2.line(dmy, (x1, y1), (x2, y2), (255, 0, 0), 3)
# 畫出幀plt.figure(figsize=(10,10))plt.imshow(dmy, cmap= "gray")plt.show()

現在我們將對每個幀應用所有這些操作。我們還將結果幀保存在新目錄中:cnt = 0
for img in tqdm_notebook(col_images):
# 應用幀掩碼 masked = cv2.bitwise_and(img[:,:,0], img[:,:,0], mask=stencil)
# 應用圖像閾值化 ret, thresh = cv2.threshold(masked, 130, 145, cv2.THRESH_BINARY)
# 應用霍夫線變換 lines = cv2.HoughLinesP(thresh, 1, np.pi/180, 30, maxLineGap=200) dmy = img.copy()
#畫出檢測到的線 try: for line in lines: x1, y1, x2, y2 = line[0] cv2.line(dmy, (x1, y1), (x2, y2), (255, 0, 0), 3)
cv2.imwrite('detected/'+str(cnt)+'.png',dmy)
except TypeError: cv2.imwrite('detected/'+str(cnt)+'.png',img)
cnt+= 1視頻準備# 輸入幀的路徑pathIn= 'detected/'
#輸出視頻路徑pathOut = 'roads_v2.mp4'
# 視頻每秒的幀數fps = 30.0from os.path import isfile, join
# 獲取幀的文件名files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]files.sort(key=lambda f: int(re.sub('D', '', f)))接下來,我們將把檢測到的車道上的所有幀放入一個列表中:frame_list = []
for i in tqdm_notebook(range(len(files))): filename=pathIn + files[i] #讀取每一個文件 img = cv2.imread(filename) height, width, layers = img.shape size = (width,height)
#將幀插入圖像數組 frame_list.append(img)最后,我們現在可以使用下面的代碼將幀合并為視頻:# 寫入視頻out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
for i in range(len(frame_array)): out.write(frame_array[i])
out.release()這就完成了Python中的車道檢測系統。
結尾在本教程中,我們介紹了一種簡單的車道檢測技術。我們沒有使用任何模型或復雜的圖像特征,相反,我們的解決方案完全基于某些圖像預處理操作。但是,在很多情況下,這個解決方案都無法工作。例如,當沒有車道標線,或者道路上的車輛太多時,該系統將失敗。在車道檢測中有更復雜的方法來克服這些問題。
請輸入評論內容...
請輸入評論/評論長度6~500個字
最新活動更多
- 1 AI狂歡遇上油價破百,全球股市還能漲多久? | 產聯看全球
- 2 OpenAI深夜王炸!ChatGPT Images 2.0實測:中文穩、細節炸,設計師慌了
- 3 6000億美元估值錨定:字節跳動的“去單一化”突圍與估值重構
- 4 Tesla AI5芯片最新進展總結
- 5 連夜測了一波DeepSeek-V4,我發現它可能只剩“審美”這個短板了
- 6 熱點丨AI“瑜亮之爭”:既生OpenClaw,何生Hermes?
- 7 AI界的殺豬盤:9秒刪庫跑路,全員被封號,還繼續扣錢!
- 8 2026,人形機器人只贏了面子
- 9 DeepSeek降價90%:價格屠夫不是身份,是戰略
- 10 AI Infra產業鏈卡在哪里了?


分享













