OpenCV 实时赛道识别及转向控制 Python 代码
以下是基于 OpenCV 的 Python 代码,实现实时识别灰色赛道,并将赛道上的非灰色区域转化为白色,然后根据赛道的灰色区域判断车辆的行驶方向,显示出赛道中心区域的一小段方向线,并输出偏转角度。最后根据偏转角度判断向左、向右或直走,并将结果显示在屏幕上。
import cv2
import numpy as np
def process_image(image):
# 将图像转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 对灰度图像进行阈值处理,将非灰色的区域转化为白色
_, binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)
# 进行边缘检测
edges = cv2.Canny(binary, 50, 150)
# 利用霍夫变换检测直线
lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=50, minLineLength=50, maxLineGap=10)
# 将图像分割为上中下三个区域
height, width = image.shape[:2]
upper_region = image[0:int(height/3), :]
middle_region = image[int(height/3):int(2*height/3), :]
lower_region = image[int(2*height/3):height, :]
# 遍历直线,判断直线所在的区域,并计算直线的斜率
left_count = 0
left_slope_sum = 0
right_count = 0
right_slope_sum = 0
for line in lines:
x1, y1, x2, y2 = line[0]
slope = (y2 - y1) / (x2 - x1)
if y1 < int(height/3):
upper_region = cv2.line(upper_region, (x1, y1), (x2, y2), (0, 255, 0), 2)
if slope < 0: # 斜率小于0表示向左
left_count += 1
left_slope_sum += slope
else: # 斜率大于0表示向右
right_count += 1
right_slope_sum += slope
elif y1 < int(2*height/3):
middle_region = cv2.line(middle_region, (x1, y1-int(height/3)), (x2, y2-int(height/3)), (0, 255, 0), 2)
else:
lower_region = cv2.line(lower_region, (x1, y1-int(2*height/3)), (x2, y2-int(2*height/3)), (0, 255, 0), 2)
# 计算平均斜率
if left_count > 0:
left_slope_avg = left_slope_sum / left_count
else:
left_slope_avg = 0
if right_count > 0:
right_slope_avg = right_slope_sum / right_count
else:
right_slope_avg = 0
# 判断偏离角度
angle_threshold = 0.1 # 偏离角度的阈值
if left_slope_avg < -angle_threshold:
print('向左')
elif right_slope_avg > angle_threshold:
print('向右')
else:
print('直走')
# 将分割后的图像合并
result = np.vstack((upper_region, middle_region, lower_region))
return result
# 读取摄像头图像
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
# 对图像进行处理
processed_frame = process_image(frame)
# 在屏幕上显示图像
cv2.imshow('Processed Frame', processed_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
这段代码实现了图像的实时处理和显示。根据灰度处理后的图像找出灰色赛道,并将赛道上的非灰色区域转化为白色。然后根据赛道的灰色区域判断车辆的行驶方向,显示出赛道中心区域的一小段方向线,并输出偏转角度。最后根据偏转角度判断向左、向右或直走,并将结果显示在屏幕上。
原文地址: https://www.cveoy.top/t/topic/o8oO 著作权归作者所有。请勿转载和采集!