以下是使用OpenCV实现实时基于灰度处理找出相对较深灰色赛道的Python代码:

import cv2
import numpy as np

# 定义灰度阈值
threshold_min = 100

# 定义方向线颜色和尺寸
line_color = (0, 255, 0)
line_thickness = 2

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

while True:
    # 读取摄像头图像
    ret, frame = cap.read()
    
    # 将图像转换为灰度图
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # 对灰度图进行阈值处理
    _, threshold = cv2.threshold(gray, threshold_min, 255, cv2.THRESH_BINARY)
    
    # 查找边缘
    canny = cv2.Canny(threshold, 50, 150)
    
    # 查找轮廓
    contours, _ = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    if len(contours) > 0:
        # 找到最大的轮廓
        max_contour = max(contours, key=cv2.contourArea)
        
        # 计算最大轮廓的中心点
        M = cv2.moments(max_contour)
        if M['m00'] != 0:
            center_x = int(M['m10'] / M['m00'])
            center_y = int(M['m01'] / M['m00'])
            
            # 在图像上绘制方向线
            cv2.line(frame, (center_x - 10, center_y), (center_x + 10, center_y), line_color, line_thickness)
            cv2.line(frame, (center_x, center_y - 10), (center_x, center_y + 10), line_color, line_thickness)
            
            # 计算摄像头偏移角度
            deviation_angle = (center_x - frame.shape[1] / 2) * 0.1
            
            # 判断偏移角度并显示在屏幕上
            if deviation_angle < -5:
                cv2.putText(frame, 'Turn Left', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, line_color, line_thickness)
            elif deviation_angle > 5:
                cv2.putText(frame, 'Turn Right', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, line_color, line_thickness)
            else:
                cv2.putText(frame, 'Go Straight', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, line_color, line_thickness)
    
    # 分屏显示灰度图像和处理后的图像
    cv2.imshow('Gray', gray)
    cv2.imshow('Frame', frame)
    
    # 按下q键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()

请注意,此代码假设您的摄像头已连接到计算机并正确配置。

OpenCV实时赛道识别及方向控制:灰度处理,中心线检测,偏转角计算,Python代码

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

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