下面是一个使用 OpenCV 实现灰度处理、赛道检测、方向线绘制和偏转角计算的 Python 代码示例:

import cv2
import numpy as np

def process_image(image):
    # 将图像转换为灰度图像
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # 对灰度图像进行阈值处理,将灰色区域二值化
    ret, binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
    
    # 执行 Canny 边缘检测
    edges = cv2.Canny(binary, 50, 150, apertureSize=3)
    
    # 执行霍夫直线检测
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=50, minLineLength=50, maxLineGap=10)
    
    # 计算赛道中心线的偏转角度
    deviation_angle = 0
    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line[0]
            cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
            deviation_angle += np.arctan2(y2-y1, x2-x1)
        deviation_angle /= len(lines)
        
    # 根据偏转角度判断赛道行驶方向并在图像上显示
    direction = ""
    if deviation_angle > 0.1:
        direction = "向右"
    elif deviation_angle < -0.1:
        direction = "向左"
    else:
        direction = "直走"
    cv2.putText(image, direction, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
    
    # 在图像上绘制赛道中心区域的一小段方向线
    height, width = image.shape[:2]
    center_x = width // 2
    center_y = height // 2
    line_length = 100
    x1 = int(center_x - line_length * np.cos(deviation_angle))
    y1 = int(center_y - line_length * np.sin(deviation_angle))
    x2 = int(center_x + line_length * np.cos(deviation_angle))
    y2 = int(center_y + line_length * np.sin(deviation_angle))
    cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
    
    # 分屏显示灰度处理下的图像和原始图像
    cv2.imshow("Gray", gray)
    cv2.imshow("Original", image)
    
    return image

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

while True:
    # 读取摄像头图像
    ret, frame = cap.read()
    
    # 处理图像并显示结果
    result = process_image(frame)
    
    # 按下"q"键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

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

在代码中,process_image 函数进行了以下操作:

  1. 将图像转换为灰度图像;
  2. 对灰度图像进行阈值处理,将灰色区域二值化;
  3. 执行 Canny 边缘检测,提取图像边缘;
  4. 执行霍夫直线检测,检测赛道中的直线;
  5. 计算赛道中心线的偏转角度,通过计算直线的斜率的平均值得到;
  6. 根据偏转角度判断赛道行驶方向:偏转角度大于 0.1 表示向右偏转,小于 -0.1 表示向左偏转,否则表示直走;
  7. 在图像上显示赛道行驶方向和赛道中心区域的一小段方向线;
  8. 分屏显示灰度处理下的图像和原始图像。

代码中使用了 cv2.VideoCapture 打开摄像头,并在循环中不断读取摄像头图像,并调用 process_image 函数进行处理和显示。按下键盘上的"q" 键可以退出循环。

OpenCV 实时赛道检测与方向判断:Python 代码实现

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

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