使用 Python OpenCV 实时识别赛道中心线

本教程演示如何使用 Python OpenCV 库实时识别并显示黑色赛道中心线。该方法通过图像处理技术,包括灰度转换、高斯模糊、边缘检测和霍夫变换来实现。

1. 导入必要的库

import cv2
import numpy as np

2. 定义函数来识别并显示标出黑色赛道中心线

def detect_lane(image):
    # 转换为灰度图像
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 应用高斯模糊
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # 检测边缘
    edges = cv2.Canny(blurred, 50, 150)

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

    # 绘制检测到的直线
    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line[0]
            cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)

    # 显示图像
    cv2.imshow('Lane Detection', image)
    cv2.waitKey(1)

3. 打开摄像头并实时调用函数进行识别

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    detect_lane(frame)

cap.release()
cv2.destroyAllWindows()

这段代码会打开摄像头,并实时识别图像中的黑色赛道中心线,并在原图上标出检测到的直线。

Python OpenCV 实时识别赛道中心线 - 基于图像处理

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

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