要实现 OpenCV 实时识别赛道两边的线并找出中心位置,可以按照以下步骤进行:

  1. 首先,使用摄像头或者视频文件读取图像帧。
  2. 对每一帧图像进行预处理,包括灰度化处理、高斯模糊、Canny 边缘检测等操作,以便提取赛道线的边缘信息。
  3. 使用霍夫变换检测直线,在边缘图像上找到赛道线的直线段。
  4. 过滤掉不符合条件的直线段,比如长度过短或者斜率不在合理范围内的直线段。
  5. 将剩余的直线段根据斜率分为左右两侧。
  6. 对左右两侧的直线段进行拟合,得到两条直线的斜率和截距。
  7. 根据两条直线的斜率和截距,计算出赛道线的中心位置。
  8. 在结果画面中绘制出赛道线的中心位置,并进行分屏显示。

下面是一个示例代码,实现了以上的功能:

import cv2
import numpy as np

# 定义函数进行直线拟合
def fit_line(lines):
    x = []
    y = []
    for line in lines:
        for x1, y1, x2, y2 in line:
            x.append(x1)
            x.append(x2)
            y.append(y1)
            y.append(y2)
    fit = np.polyfit(y, x, 1)  # 使用一次多项式拟合
    return fit

# 定义函数计算中心位置
def calculate_center(left_fit, right_fit, height):
    left_x = left_fit[0] * height + left_fit[1]
    right_x = right_fit[0] * height + right_fit[1]
    center_x = (left_x + right_x) // 2
    return center_x

# 打开摄像头
cap = cv2.VideoCapture(0)

while True:
    # 读取图像帧
    ret, frame = cap.read()

    # 预处理:灰度化、高斯模糊、Canny 边缘检测等
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(blurred, 50, 150)

    # 霍夫变换检测直线
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 50, minLineLength=100, maxLineGap=50)

    # 过滤直线段
    filtered_lines = []
    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line[0]
            slope = (y2 - y1) / (x2 - x1 + 1e-5)  # 避免除零错误
            length = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
            if length > 100 and abs(slope) > 0.5 and abs(slope) < 2:
                filtered_lines.append(line)

    # 分类左右两侧的直线
    left_lines = []
    right_lines = []
    if filtered_lines:
        for line in filtered_lines:
            x1, y1, x2, y2 = line[0]
            slope = (y2 - y1) / (x2 - x1 + 1e-5)
            if slope < 0:
                left_lines.append(line)
            else:
                right_lines.append(line)

    # 直线拟合
    left_fit = fit_line(left_lines)
    right_fit = fit_line(right_lines)

    # 计算中心位置
    center_x = calculate_center(left_fit, right_fit, frame.shape[0])

    # 在结果画面中绘制出赛道线的中心位置
    cv2.line(frame, (center_x, 0), (center_x, frame.shape[0]), (0, 255, 0), 2)

    # 进行分屏显示
    result = np.hstack((cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR), frame))
    cv2.imshow('Result', result)

    # 按下 q 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()

请注意,以上代码仅供参考,具体的参数和条件可以根据实际情况进行调整和优化。

OpenCV 实时赛道线识别与中心定位:分屏显示和灰度拟合

原文地址: http://www.cveoy.top/t/topic/bT8m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录