OpenCV 实时灰度赛道识别与方向控制 Python 代码
以下是一个使用 OpenCV 实时处理灰度图像的示例代码,用于识别相对较深的灰色赛道,并根据其位置和偏转角判断车辆的行驶方向。
import cv2
import numpy as np
# 设置灰度阈值,用于找到相对较深的灰色赛道
gray_threshold = 100
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 通过灰度阈值处理,找到相对较深的灰色赛道
_, threshold = cv2.threshold(gray, gray_threshold, 255, cv2.THRESH_BINARY)
# 找到灰色赛道的轮廓
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:
# 找到最大的轮廓
max_contour = max(contours, key=cv2.contourArea)
# 找到灰色赛道的中心位置
M = cv2.moments(max_contour)
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
# 绘制赛道中心线
cv2.line(frame, (cx, 0), (cx, frame.shape[0]), (0, 0, 255), 2)
# 计算摄像头偏离中心线的偏转角
deviation_angle = np.arctan((cx - frame.shape[1] / 2) / (frame.shape[0] / 2)) * 180 / np.pi
# 根据偏转角判断向左、向右还是直走
if deviation_angle < -10:
direction = '向左转'
elif deviation_angle > 10:
direction = '向右转'
else:
direction = '直走'
# 在图像上显示方向线和偏转角
cv2.arrowedLine(frame, (cx, cy), (cx, cy + 50), (0, 255, 0), 2)
cv2.putText(frame, f'偏转角: {deviation_angle:.2f} 度', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.putText(frame, direction, (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
# 在屏幕上显示图像
cv2.imshow('Gray Image', gray)
cv2.imshow('Threshold Image', threshold)
cv2.imshow('Result', frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
这段代码会打开摄像头,实时处理灰度图像,并根据灰色赛道的位置和偏转角判断车辆的行驶方向。在图像上显示了灰色赛道的中心线和偏转角,并在屏幕上分屏显示了灰度图像、阈值图像和结果图像。按下键盘上的“q”键可以退出程序。
原文地址: https://www.cveoy.top/t/topic/o8p9 著作权归作者所有。请勿转载和采集!