OpenCV 赛道识别:检测边界线并计算灰度赛道中点
要使用OpenCV识别赛道两边的线并找出标记灰度处理下黑色赛道中点,可以按照以下步骤进行:
- 读取图像:使用OpenCV的函数
cv2.imread()读取图像,并将其转换为灰度图像。
import cv2
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- 边缘检测:使用Canny边缘检测算法,通过调整阈值来检测图像中的边缘。
edges = cv2.Canny(gray, threshold1, threshold2)
- 霍夫直线检测:使用霍夫直线变换算法,检测图像中的直线段。
lines = cv2.HoughLinesP(edges, rho, theta, threshold, minLineLength, maxLineGap)
- 筛选直线:对于检测到的直线,根据斜率和位置进行筛选,以获取左右两条直线。
left_lines = []
right_lines = []
for line in lines:
x1, y1, x2, y2 = line[0]
slope = (y2 - y1) / (x2 - x1)
if slope < 0:
left_lines.append(line)
else:
right_lines.append(line)
- 拟合直线:对筛选出的直线进行拟合,得到一条左侧直线和一条右侧直线。
left_line = cv2.fitLine(np.array(left_lines), cv2.DIST_L2, 0, 0.01, 0.01)
right_line = cv2.fitLine(np.array(right_lines), cv2.DIST_L2, 0, 0.01, 0.01)
- 计算中点:根据左侧直线和右侧直线的斜率和截距,计算黑色赛道中点的位置。
left_slope = left_line[1][1] / left_line[1][0]
left_intercept = left_line[3][0] - left_slope * left_line[2][0]
right_slope = right_line[1][1] / right_line[1][0]
right_intercept = right_line[3][0] - right_slope * right_line[2][0]
midpoint_x = (right_intercept - left_intercept) / (left_slope - right_slope)
midpoint_y = left_slope * midpoint_x + left_intercept
midpoint = (int(midpoint_x), int(midpoint_y))
最后,可以在原始图像上绘制出检测到的直线和黑色赛道中点。
cv2.line(image, (left_line[2][0], left_line[3][0]), (left_line[2][0] + 100 * left_line[0][0], left_line[3][0] + 100 * left_line[0][1]), (0, 0, 255), 2)
cv2.line(image, (right_line[2][0], right_line[3][0]), (right_line[2][0] + 100 * right_line[0][0], right_line[3][0] + 100 * right_line[0][1]), (0, 0, 255), 2)
cv2.circle(image, midpoint, 5, (0, 255, 0), -1)
cv2.imshow('Result', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
以上代码假设图像名称为'image.jpg',并根据具体情况调整阈值、参数等。
原文地址: https://www.cveoy.top/t/topic/bUIh 著作权归作者所有。请勿转载和采集!