车道线检测– Python中的计算机视觉项目
)
Python实现车道线检测代码及教程
车道线检测是自动驾驶汽车和计算机视觉的重要组成部分。 该概念用于描述自动驾驶汽车的路径,并避免进入另一条车道的风险。
在本文中,我们将构建一个机器学习项目,以实时检测车道线。 我们将使用OpenCV库中的计算机视觉概念来完成此操作。 要检测车道,我们必须检测车道两侧的白色标记。主要使用Python中的计算机视觉技术,因为自动驾驶汽车不应越过车道,也不应在对面的车道上行驶以避免发生事故。
霍夫变换
为了检测车道上的白色标记,首先,我们需要遮盖车架的其余部分。 我们使用帧遮罩进行此操作。 该帧不过是图像像素值的NumPy数组。 为了掩盖帧中不必要的像素,我们只需将NumPy数组中的像素值更新为0。
完成后,我们需要检测车道线。 这种用于检测数学形状的技术称为霍夫变换。 霍夫变换可以检测矩形,圆形,三角形和直线等形状
主要步骤如下
1. Imports:
导入我们需要的一些包
var foo = 'bar';
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
import matplotlib.image as mpimg
from moviepy.editor import VideoFileClip
import math
2. 应用帧遮罩并找到感兴趣的区域:
def interested_region(img, vertices):
if len(img.shape) > 2:
mask_color_ignore = (255,) * img.shape[2]
else:
mask_color_ignore = 255
cv2.fillPoly(np.zeros_like(img), vertices, mask_color_ignore)
return cv2.bitwise_and(img, np.zeros_like(img))
3.在霍夫变换空间中将像素转换为线
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
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)
lines_drawn(line_img,lines)
return line_img
4.霍夫变换后,在每帧中创建两行
def lines_drawn(img, lines, color=[255, 0, 0], thickness=6):
global cache
global first_frame
slope_l, slope_r = [],[]
lane_l,lane_r = [],[]
α =0.2
for line in lines:
for x1,y1,x2,y2 in line:
slope = (y2-y1)/(x2-x1)
if slope > 0.4:
slope_r.append(slope)
lane_r.append(line)
elif slope < -0.4:
slope_l.append(slope)
lane_l.append(line)
img.shape[0] = min(y1,y2,img.shape[0])
if((len(lane_l) == 0) or (len(lane_r