OpenCV 赛道识别:使用 Python 代码标记远近、倾斜和明暗
以下是一个使用 OpenCV 进行赛道识别并标记远近、倾斜和明暗的 Python 代码示例:
import cv2
import numpy as np
def preprocess_image(image):
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 应用高斯模糊以减少噪声
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
return blurred
def detect_edges(image):
# 使用 Canny 边缘检测算法检测边缘
edges = cv2.Canny(image, 50, 150)
return edges
def detect_lines(image):
# 使用霍夫直线变换检测直线
lines = cv2.HoughLinesP(image, 1, np.pi/180, 100, minLineLength=100, maxLineGap=10)
return lines
def process_lines(image, lines):
# 绘制检测到的直线
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
return image
def mark_distance(image, lines):
# 计算每条直线的长度,然后根据长度标记远近
for line in lines:
x1, y1, x2, y2 = line[0]
distance = np.sqrt((x2 - x1)**2 + (y2 - y1)**2)
if distance < 100:
cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, 'Far', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
else:
cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.putText(image, 'Near', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
return image
def mark_slope(image, lines):
# 根据斜率标记倾斜
for line in lines:
x1, y1, x2, y2 = line[0]
if x2 - x1 != 0:
slope = (y2 - y1) / (x2 - x1)
if abs(slope) < 0.5:
cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
cv2.putText(image, 'Flat', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
elif slope < 0:
cv2.line(image, (x1, y1), (x2, y2), (0, 255, 255), 2)
cv2.putText(image, 'Downhill', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 255), 2)
else:
cv2.line(image, (x1, y1), (x2, y2), (255, 255, 0), 2)
cv2.putText(image, 'Uphill', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 0), 2)
return image
def mark_brightness(image, edges):
# 计算灰度图像的平均亮度,然后根据亮度标记明暗
brightness = np.mean(image)
if brightness < 100:
cv2.putText(edges, 'Dark', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
else:
cv2.putText(edges, 'Bright', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
return edges
# 读取图像
image = cv2.imread('map.jpg')
# 图像预处理
processed_image = preprocess_image(image)
# 边缘检测
edges = detect_edges(processed_image)
# 直线检测
lines = detect_lines(edges)
# 标记直线
image_with_lines = process_lines(image.copy(), lines)
# 标记远近
image_with_distance = mark_distance(image_with_lines.copy(), lines)
# 标记倾斜
image_with_slope = mark_slope(image_with_distance.copy(), lines)
# 标记明暗
final_image = mark_brightness(image_with_slope.copy(), edges)
# 显示结果
cv2.imshow('Result', final_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
请确保将代码中的 'map.jpg' 替换为您要处理的地图图像的路径。此代码使用了一系列的图像处理技术,包括灰度转换、高斯模糊、Canny 边缘检测、霍夫直线变换和计算斜率和亮度等。最后,通过在图像上绘制直线和文本来自动标记远近、倾斜和明暗。
原文地址: http://www.cveoy.top/t/topic/T5B 著作权归作者所有。请勿转载和采集!