以下是一个使用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)
    
    # 使用Canny边缘检测算法检测图像边缘
    edges = cv2.Canny(blurred, 50, 150)
    
    return edges

def get_lane_lines(image, edges):
    # 设置感兴趣区域
    height, width = image.shape[:2]
    mask = np.zeros_like(edges)
    region_of_interest_vertices = np.array([[0, height], [width / 2, height / 2], [width, height]], np.int32)
    cv2.fillPoly(mask, [region_of_interest_vertices], 255)
    masked_edges = cv2.bitwise_and(edges, mask)
    
    # 使用Hough变换检测直线
    lines = cv2.HoughLinesP(masked_edges, rho=6, theta=np.pi/60, threshold=160, minLineLength=40, maxLineGap=25)
    
    return lines

def draw_lane_lines(image, lines):
    # 绘制检测到的直线
    line_image = np.zeros_like(image)
    if lines is not None:
        for line in lines:
            for x1, y1, x2, y2 in line:
                cv2.line(line_image, (x1, y1), (x2, y2), (0, 0, 255), 3)
    
    return cv2.addWeighted(image, 0.8, line_image, 1, 0)

def display_distance(image, lines):
    if lines is not None:
        for line in lines:
            for x1, y1, x2, y2 in line:
                # 计算直线长度
                distance = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
                # 将长度信息显示在图像上
                cv2.putText(image, f'{distance:.2f}', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
    
    return image

# 读取视频
cap = cv2.VideoCapture('path_to_your_video.mp4')

while True:
    ret, frame = cap.read()
    if not ret:
        break
    
    # 图像预处理
    edges = preprocess_image(frame)
    
    # 检测赛道线
    lane_lines = get_lane_lines(frame, edges)
    
    # 绘制赛道线
    lane_image = draw_lane_lines(frame, lane_lines)
    
    # 显示距离信息
    lane_image_with_distance = display_distance(lane_image, lane_lines)
    
    # 显示结果图像
    cv2.imshow('Lane Detection', lane_image_with_distance)
    
    # 按下q键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

使用此代码,您需要将path_to_your_video.mp4替换为您要处理的视频文件的路径。

OpenCV赛道识别及距离、倾斜、明暗信息显示 Python 代码

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

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