使用 OpenCV 实时识别赛道两边的线,并在结果画面中分屏显示。对灰度处理后的图像进行霍夫线变换,拟合出黑色赛道的中心位置并显示。可以使用以下步骤:

  1. 导入所需的库和模块:
import cv2
import numpy as np
  1. 读取摄像头的视频流:
cap = cv2.VideoCapture(0)
  1. 定义函数来处理视频流帧:
def process_frame(frame):
    # 将帧转换为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # 对图像进行高斯模糊
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    
    # 进行边缘检测
    edges = cv2.Canny(blurred, 50, 150)
    
    # 对边缘图像进行霍夫线变换
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, minLineLength=100, maxLineGap=50)
    
    # 创建空白图像
    mask = np.zeros_like(edges)
    
    # 绘制检测到的线段
    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line[0]
            cv2.line(mask, (x1, y1), (x2, y2), 255, 5)
    
    # 对图像进行分割
    height, width = frame.shape[:2]
    mask = mask[0:height//2, :]
    
    # 将分割后的图像转换为彩色图像
    mask_colored = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
    
    # 在彩色图像上绘制中心线
    cv2.line(mask_colored, (0, height//4), (width, height//4), (0, 0, 255), 2)
    
    # 将原始帧和处理后的帧水平拼接
    result = np.hstack((frame, mask_colored))
    
    # 显示结果帧
    cv2.imshow('Result', result)
  1. 不断循环读取视频流帧并调用处理函数:
while True:
    # 读取一帧
    ret, frame = cap.read()
    
    # 处理当前帧
    process_frame(frame)
    
    # 按下q键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
  1. 释放摄像头并关闭窗口:
cap.release()
cv2.destroyAllWindows()

注意:以上代码仅提供了一个基本的实现思路,具体的参数和调整方式可能需要根据实际情况进行调整。

OpenCV 实时赛道线识别及中心线拟合显示

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

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