下面是一个示例代码,实现了基于灰度处理的实时赛道检测和偏转角度计算。

import cv2
import numpy as np

# 设置灰色阈值
gray_threshold = 150

# 设置ROI区域
roi_vertices = np.array([[(0, 480), (320, 350), (320, 350), (640, 480)]], dtype=np.int32)

# 设置摄像头偏移角度的阈值
angle_threshold = 5

# 打开摄像头
cap = cv2.VideoCapture(0)

while True:
    # 读取摄像头帧
    ret, frame = cap.read()
    
    # 将帧转为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # 应用灰度阈值,得到二值图像
    _, binary = cv2.threshold(gray, gray_threshold, 255, cv2.THRESH_BINARY)
    
    # 应用ROI
    masked = cv2.bitwise_and(binary, cv2.fillPoly(np.zeros_like(binary), roi_vertices, 255))
    
    # 检测线段
    lines = cv2.HoughLinesP(masked, 1, np.pi/180, 100, minLineLength=100, maxLineGap=50)
    
    # 初始化偏转角度
    angle = 0
    
    if lines is not None:
        # 计算所有线段的平均角度
        avg_angle = np.mean([np.arctan2((line[0][3] - line[0][1]), (line[0][2] - line[0][0])) for line in lines])
        
        # 将角度转为度数
        angle = np.rad2deg(avg_angle)
        
        # 绘制赛道中心线
        cv2.line(frame, (320, 480), (320 + int(1000 * np.tan(avg_angle)), 350), (0, 255, 0), 2)
        
        # 判断偏转方向
        if angle < -angle_threshold:
            direction = 'Right'
        elif angle > angle_threshold:
            direction = 'Left'
        else:
            direction = 'Straight'
        
        # 在图像上显示偏转角度和方向
        cv2.putText(frame, f'Angle: {angle:.2f} deg', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        cv2.putText(frame, f'Direction: {direction}', (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
    
    # 显示图像
    cv2.imshow('Lane Detection', frame)
    
    # 按下q键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头和销毁窗口
cap.release()
cv2.destroyAllWindows()

这段代码中,通过阈值来将灰度图像转为二值图像,并通过ROI区域提取出赛道的感兴趣区域。然后使用霍夫变换检测赛道中的线段,计算线段的角度,并根据角度判断赛道的偏转方向。最后,在图像上绘制赛道中心线和显示偏转角度和方向。

Python OpenCV实时赛道检测和偏转角度识别

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

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