实现车道线检测的步骤

环境准备 确保安装OpenCV和NumPy库:

pip install opencv-python numpy

导入库

import cv2
import numpy as np

图像预处理

读取输入图像或视频

cap = cv2.VideoCapture('test_video.mp4')  # 或使用摄像头cv2.VideoCapture(0)

转换为灰度图像

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

应用高斯模糊降噪

blur = cv2.GaussianBlur(gray, (5, 5), 0)

Canny边缘检测

edges = cv2.Canny(blur, 50, 150)

感兴趣区域(ROI)提取

定义多边形掩膜

height, width = edges.shape
mask = np.zeros_like(edges)
polygon = np.array([[(0, height), (width//2, height//2), (width, height)]], np.int32)
cv2.fillPoly(mask, polygon, 255)

应用掩膜

masked_edges = cv2.bitwise_and(edges, mask)

霍夫变换检测直线

执行霍夫变换

lines = cv2.HoughLinesP(masked_edges, 1, np.pi/180, threshold=50, minLineLength=100, maxLineGap=50)

绘制检测到的车道线

line_image = np.zeros_like(frame)
for line in lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 10)

优化车道线显示

计算平均车道线

def average_slope_intercept(lines):
    left_lines = []
    right_lines = []
    for line in lines:
        x1, y1, x2, y2 = line[0]
        parameters = np.polyfit((x1, x2), (y1, y2), 1)
        slope = parameters[0]
        intercept = parameters[1]
        if slope < 0:
            left_lines.append((slope, intercept))
        else:
            right_lines.append((slope, intercept))
    
    left_avg = np.average(left_lines, axis=0)
    right_avg = np.average(right_lines, axis=0)
    
    return left_avg, right_avg

绘制优化后的车道线

def make_line_points(y1, y2, line):
    slope, intercept = line
    x1 = int((y1 - intercept)/slope)
    x2 = int((y2 - intercept)/slope)
    y1 = int(y1)
    y2 = int(y2)
    return (x1, y1), (x2, y2)

主循环处理视频帧

完整处理流程

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    
    # 预处理
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(blur, 50, 150)
    
    # ROI
    mask = np.zeros_like(edges)
    polygon = np.array([[(0, height), (width//2, height//2), (width, height)]], np.int32)
    cv2.fillPoly(mask, polygon, 255)
    masked_edges = cv2.bitwise_and(edges, mask)
    
    # 霍夫变换
    lines = cv2.HoughLinesP(masked_edges, 1, np.pi/180, 50, minLineLength=100, maxLineGap=50)
    
    # 优化和绘制车道线
    if lines is not None:
        left_avg, right_avg = average_slope_intercept(lines)
        left_line = make_line_points(height, height//2, left_avg)
        right_line = make_line_points(height, height//2, right_avg)
        cv2.line(frame, left_line[0], left_line[1], (0, 255, 0), 10)
        cv2.line(frame, right_line[0], right_line[1], (0, 255, 0), 10)
    
    cv2.imshow('Lane Detection', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

性能优化建议

使用颜色阈值过滤

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_yellow = np.array([20, 100, 100])
upper_yellow = np.array([30, 255, 255])
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
mask_white = cv2.inRange(gray, 200, 255)
mask_color = cv2.bitwise_or(mask_yellow, mask_white)

透视变换改善视角

src_points = np.float32([[width//2-76, height*0.625], [width//2+76, height*0.625], 
                         [width-50, height], [50, height]])
dst_points = np.float32([[50, 0], [width-50, 0], [width-50, height], [50, height]])
M = cv2.getPerspectiveTransform(src_points, dst_points)
warped = cv2.warpPerspective(frame, M, (width, height))

多项式拟合曲线车道

ploty = np.linspace(0, frame.shape[0]-1, frame.shape[0])
left_fit = np.polyfit(lefty, leftx, 2)
left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]

这些代码实现了一个基本的车道线检测系统,可以根据实际需求进行调整和优化,例如添加更复杂的车道跟踪算法或集成到更大的自动驾驶系统中。

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐