You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OpenCV检测无车道线的车道 解决全边缘识别误判问题

OpenCV车道检测仅保留车道区域边缘的解决方案
  • 新增感兴趣区域(ROI)掩码

    该方案是优化效果最明显的实现方式,车道仅会出现在摄像头视野下半部分的梯形区域,直接屏蔽其余区域的所有边缘即可过滤大部分无效识别结果,参考代码如下:
    import cv2
    import numpy as np
    
    def region_of_interest(img, vertices):
        mask = np.zeros_like(img)
        cv2.fillPoly(mask, vertices, 255)
        # 掩码和边缘检测结果做按位与,仅保留车道区域边缘
        return cv2.bitwise_and(img, mask)
    
    # 调用示例,顶点坐标可根据你的摄像头视角自行调整
    height, width = img.shape
    # 梯形顶点依次为:左下角、左上方拐点、右上方拐点、右下角
    roi_vertices = np.array([[
        (width*0.1, height),
        (width*0.45, height*0.6),
        (width*0.55, height*0.6),
        (width*0.9, height)
    ]], dtype=np.int32)
    edges = cv2.Canny(img, 50, 150)
    masked_edges = region_of_interest(edges, roi_vertices)
    
  • 提前过滤非车道线颜色像素

    车道线基本为白色或黄色,可在HSV颜色空间提前提取对应颜色区域,过滤其余颜色像素后再做边缘检测,参考代码如下:
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # 白色阈值范围
    lower_white = np.array([0, 0, 200])
    upper_white = np.array([255, 30, 255])
    # 黄色阈值范围
    lower_yellow = np.array([20, 100, 100])
    upper_yellow = np.array([30, 255, 255])
    white_mask = cv2.inRange(hsv, lower_white, upper_white)
    yellow_mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
    color_mask = cv2.bitwise_or(white_mask, yellow_mask)
    # 结合边缘检测结果,过滤非车道线区域的边缘
    filtered_edges = cv2.bitwise_and(edges, color_mask)
    
  • 霍夫变换增加车道线特征约束

    检测线条时增加参数限制,排除角度、长度不符合车道线特征的无效线条,比如车道线斜率绝对值一般在0.5~2之间,过于平缓或过于陡峭的线条直接过滤:
    # 调整霍夫线检测参数,过滤短线条、间隙过大的线条
    lines = cv2.HoughLinesP(masked_edges, 1, np.pi/180, threshold=50, minLineLength=100, maxLineGap=50)
    valid_lines = []
    for line in lines:
        x1, y1, x2, y2 = line[0]
        # 计算斜率,避免分母为0
        if x2 == x1:
            continue
        slope = (y2 - y1)/(x2 - x1)
        # 仅保留斜率符合车道线特征的线条
        if 0.5 < abs(slope) < 2:
            valid_lines.append(line)
    

原始全边缘检测结果
目标车道检测效果参考

内容的提问来源于stack exchange,提问作者Huy Bùi Quốc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:57:04