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

import cv2
import numpy as np

# 读取视频
cap = cv2.VideoCapture('video.mp4')

while True:
    # 读取视频帧
    ret, frame = cap.read()
    if not ret:
        break

    # 调整图像大小
    frame = cv2.resize(frame, (640, 480))

    # 灰度处理
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Canny边缘检测
    edges = cv2.Canny(gray, 50, 150)

    # ROI区域选择
    height, width = edges.shape
    roi_vertices = [(0, height), (width // 2 - 50, height // 2 + 50), (width // 2 + 50, height // 2 + 50), (width, height)]
    mask = np.zeros_like(edges)
    cv2.fillPoly(mask, np.array([roi_vertices], np.int32), 255)
    masked_edges = cv2.bitwise_and(edges, mask)

    # 霍夫直线检测
    lines = cv2.HoughLinesP(masked_edges, rho=1, theta=np.pi/180, threshold=50, minLineLength=100, maxLineGap=50)

    # 在结果画面中分屏画出灰度处理下黑色赛道中心线
    if lines is not None:
        center_x = int((roi_vertices[1][0] + roi_vertices[2][0]) / 2)
        for line in lines:
            x1, y1, x2, y2 = line[0]
            cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.line(frame, (center_x, 0), (center_x, height), (0, 0, 255), 2)

    # 显示结果画面
    cv2.imshow('Lane Detection', frame)

    # 按下'q'键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()

上述代码中,我们首先读取视频帧,并对图像进行灰度处理和 Canny 边缘检测,然后选择 ROI 区域,使用霍夫直线检测找出赛道的边界线。最后,我们计算出黑色赛道中心线的 x 坐标,并在结果画面中分屏画出黑色赛道中心线。

OpenCV 实时赛道线识别与中心线绘制

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

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