以下是使用OpenCV实时识别赛道两边的线并找出黑色赛道中心线并在结果画面中分屏显示的示例代码:

import cv2
import numpy as np

# 设置视频输入
cap = cv2.VideoCapture(0)

# 设置ROI区域
roi_top = 200
roi_bottom = 350

while True:
    # 读取视频帧
    ret, frame = cap.read()
    
    # 裁剪ROI区域
    roi = frame[roi_top:roi_bottom, :]
    
    # 灰度处理
    gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
    
    # 高斯模糊
    blur = cv2.GaussianBlur(gray, (5, 5), 0)
    
    # 边缘检测
    edges = cv2.Canny(blur, 50, 150)
    
    # 霍夫直线变换
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, minLineLength=100, maxLineGap=50)
    
    # 分割画面
    result = np.zeros_like(frame)
    result[:roi_bottom-roi_top, :] = frame[roi_top:roi_bottom, :]
    
    # 绘制检测到的直线
    if lines is not None:
        left_lines = []
        right_lines = []
        
        for line in lines:
            x1, y1, x2, y2 = line[0]
            slope = (y2 - y1) / (x2 - x1)
            
            if slope < -0.5:
                left_lines.append(line)
            elif slope > 0.5:
                right_lines.append(line)
        
        # 拟合左侧直线
        if left_lines:
            left_lines = np.array(left_lines)
            left_line = np.mean(left_lines, axis=0, dtype=np.int32)
            x1, y1, x2, y2 = left_line[0]
            cv2.line(result, (x1, y1+roi_top), (x2, y2+roi_top), (0, 255, 0), 2)
        
        # 拟合右侧直线
        if right_lines:
            right_lines = np.array(right_lines)
            right_line = np.mean(right_lines, axis=0, dtype=np.int32)
            x1, y1, x2, y2 = right_line[0]
            cv2.line(result, (x1, y1+roi_top), (x2, y2+roi_top), (0, 255, 0), 2)
    
    # 显示结果
    cv2.imshow('Lane Detection', result)
    
    # 按下'q'键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放视频捕捉对象和窗口
cap.release()
cv2.destroyAllWindows()

在上述代码中,我们使用了以下步骤来实现赛道线的识别和中心线的拟合:

  1. 从视频输入中读取帧。
  2. 设置ROI区域(在垂直方向上裁剪图像)。
  3. 将ROI区域转换为灰度图像。
  4. 对灰度图像进行高斯模糊处理。
  5. 使用Canny边缘检测算法检测图像的边缘。
  6. 使用霍夫直线变换检测图像中的直线。
  7. 根据直线的斜率将其分类为左侧直线和右侧直线。
  8. 对左侧直线和右侧直线进行拟合,得到中心线。
  9. 在结果画面中绘制检测到的直线和中心线。
  10. 显示结果画面。
  11. 按下'q'键退出循环。

请注意,上述代码中的参数(如ROI区域、边缘检测的阈值、直线拟合的阈值等)可能需要根据具体情况进行调整以获得最佳结果。

OpenCV 实时赛道线识别与中心线拟合 - 分屏显示与灰度处理

原文地址: https://www.cveoy.top/t/topic/bUbz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录