OpenCV 实时灰度赛道识别:方向判断与偏转角计算
以下是一个使用 OpenCV 实时处理灰度图像的示例代码,包括找出灰色赛道、判断赛道方向并显示方向线和偏转角的功能。
import cv2
import numpy as np
# 摄像头参数
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
# 赛道颜色范围(根据实际情况调整)
lower_gray = np.array([0, 0, 0])
upper_gray = np.array([255, 50, 50])
while True:
# 捕获图像帧
ret, frame = cap.read()
# 将图像转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 对灰度图像进行阈值处理,找出灰色赛道
mask = cv2.inRange(gray, lower_gray, upper_gray)
# 在灰色赛道上寻找边界线
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 初始化方向线的位置和角度
direction_line_x = 0
direction_line_angle = 0
if len(contours) > 0:
# 找到最大的边界线
largest_contour = max(contours, key=cv2.contourArea)
# 找到最大边界线的最左和最右点
leftmost = tuple(largest_contour[largest_contour[:,:,0].argmin()][0])
rightmost = tuple(largest_contour[largest_contour[:,:,0].argmax()][0])
# 计算方向线的位置和角度
direction_line_x = int((leftmost[0] + rightmost[0]) / 2)
direction_line_angle = np.arctan2(rightmost[1] - leftmost[1], rightmost[0] - leftmost[0]) * 180 / np.pi
# 在图像上绘制方向线
cv2.line(frame, (direction_line_x, 0), (direction_line_x, frame.shape[0]), (0, 255, 0), 2)
# 计算摄像头偏离黑色赛道中心线的偏转角
deviation_angle = direction_line_angle - frame.shape[1] / 2
# 根据偏转角判断赛道方向
if np.abs(deviation_angle) < 10:
direction = '直走'
elif deviation_angle < 0:
direction = '向左'
else:
direction = '向右'
# 在图像上显示偏转角和赛道方向
cv2.putText(frame, '偏转角: {:.2f}'.format(deviation_angle), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.putText(frame, '赛道方向: ' + direction, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
# 显示处理后的图像帧
cv2.imshow('Frame', frame)
# 按下q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和销毁所有窗口
cap.release()
cv2.destroyAllWindows()
这段代码首先初始化摄像头,然后读取图像帧,将图像转换为灰度图像,并根据灰度图像找出灰色赛道。接下来,在灰色赛道上寻找边界线,并计算出边界线的位置和角度。然后,根据边界线的位置在图像上绘制出方向线。最后,计算摄像头偏离黑色赛道中心线的偏转角,并根据偏转角判断赛道方向。将偏转角和赛道方向显示在图像上,并实时显示图像帧。
请注意,此代码仅为示例,具体的颜色范围、阈值和角度判断条件可能需要根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/o8pa 著作权归作者所有。请勿转载和采集!