Python基于YOLOv8和OpenCV实现车道线和车辆检测

使用YOLOv8(You Only Look Once)和OpenCV实现车道线和车辆检测,目标是创建一个可以检测道路上的车道并识别车辆的系统,并估计它们与摄像头的距离。该项目结合了计算机视觉技术和深度学习物体检测。

1、系统主要功能

  • 车道检测:使用边缘检测和霍夫线变换检测道路车道。
  • 汽车检测:使用 YOLOv8 模型识别汽车并在汽车周围绘制边界框。
  • 距离估计:使用边界框大小计算检测到的汽车与摄像头的距离。

2、环境要求

  • OpenCV:用于图像处理和车道检测。
  • Ultralytics YOLOv8:用于车辆检测。
  • NumPy:用于数组操作。
pip install opencv-python-headless numpy ultralytics

opencv-pythonopencv-python-headless 区别是 OpenCV 的 Python 包,主要区别在于是否包含 GUI 相关的功能。

opencv-python
  • 包含 GUI 功能:支持窗口显示、鼠标事件等图形界面操作。
  • 依赖:需要 GUI 库(如 GTK、Qt)支持。
  • 适用场景:适用于需要显示图像或与用户交互的环境,如桌面应用。
opencv-python-headless
  • 不包含 GUI 功能:去除了窗口显示和用户交互功能。
  • 依赖:无需 GUI 库,适合无图形界面的环境。
  • 适用场景:适用于服务器或无图形界面的环境,如远程服务器、Docker 容器。
选择建议
  • 如果需要显示图像或与用户交互,选择 opencv-python
  • 如果仅需图像处理且无图形界面需求,选择 opencv-python-headless

3、代码

import cv2
import numpy as np
import math
import time
from ultralytics import YOLO  # YOLOv8 module

# Function to mask out the region of interest
def region_of_interest(img, vertices):
    mask = np.zeros_like(img)
    match_mask_color = 255
    cv2.fillPoly(mask, vertices, match_mask_color)
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image

# Function to draw the filled polygon between the lane lines
def draw_lane_lines(img, left_line, right_line, color=[0, 255, 0], thickness=10):
    line_img = np.zeros_like(img)
    poly_pts = np.array([[
        (left_line[0], left_line[1]),
        (left_line[2], left_line[3]),
        (right_line[2], right_line[3]),
        (right_line[0], right_line[1])
    ]], dtype=np.int32)
    
    # Fill the polygon between the lines
    cv2.fillPoly(line_img, poly_pts, color)
    
    # Overlay the polygon onto the original image
    img = cv2.addWeighted(img, 0.8, line_img, 0.5, 0.0)
    return img

# The lane detection pipeline
def pipeline(image):
    height = image.shape[0]
    width = image.shape[1]
    region_of_interest_vertices = [
        (0, height),
        (width / 2, height / 2),
        (width, height),
    ]

    # Convert to grayscale and apply Canny edge detection
    gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    cannyed_image = cv2.Canny(gray_im
### 基于YOLOv8车道线检测系统实现方法 #### 数据集准备 为了使用 YOLOv8 进行车道线检测,首先需要准备好标注好的数据集。这些数据应包含图像及其对应的标签文件,其中标签需遵循 YOLO 的格式要求(即相对坐标表示法)。通常情况下,车道线可以被标记为不同类别的对象,例如“Lane_Marking”,以便区分不同的车道特征[^3]。 ```python import os from PIL import Image def prepare_dataset(input_dir, output_dir): """ 准备数据集函数:将原始图片转换成适合YOLOv8使用的格式。 :param input_dir: 输入目录路径 :param output_dir: 输出目录路径 """ if not os.path.exists(output_dir): os.makedirs(os.path.join(output_dir, 'images')) os.makedirs(os.path.join(output_dir, 'labels')) for filename in os.listdir(input_dir): img_path = os.path.join(input_dir, filename) label_filename = f"{os.path.splitext(filename)[0]}.txt" # 复制并调整大小 image = Image.open(img_path).resize((640, 640)) new_img_path = os.path.join(output_dir, 'images', filename) image.save(new_img_path) # 创建空标签文件作为占位符 with open(os.path.join(output_dir, 'labels', label_filename), 'w'): pass ``` #### 模型加载与初始化 接下来,利用 `ultralytics` 库加载预训练的 YOLOv8 模型,并对其进行微调以适应特定任务需求。如果已有针对车道线的数据集,则可以直接在此基础上继续训练模型。 ```python from ultralytics import YOLO model = YOLO('yolov8n.pt') # 使用官方提供的基础模型 ``` #### 训练过程 定义好配置参数之后即可启动训练流程。这一步骤涉及设置超参、指定GPU设备等操作。以下是简单的训练脚本示例: ```python results = model.train( data='lane_detection.yaml', epochs=50, batch=-1, name="custom_lane_model", patience=20 ) ``` 此处需要注意的是,`data` 参数应当指向描述数据分布情况的 YAML 文件;而其他选项可以根据实际硬件条件灵活调整[^5]。 #### 推理阶段 完成训练后就可以进入推理部分了。给定一张测试图片,通过预测接口获取可能存在的车道线条目及相关置信度得分。 ```python def predict_lanes(image_path, conf_threshold=0.5): results = model.predict(source=image_path, save=True, conf=conf_threshold) lanes_detected = [] for result in results: boxes = result.boxes.xyxy.cpu().numpy() scores = result.boxes.conf.cpu().numpy() classes = result.boxes.cls.cpu().numpy() for box, score, cls_ in zip(boxes, scores, classes): if int(cls_) == 0 and score >= conf_threshold: # Assuming class id 0 is lane marking. lanes_detected.append(box.tolist()) return lanes_detected ``` 以上代码片段展示了如何读取单张输入图像并返回所有满足阈值设定的标准候选框列表[^4]。 #### UI界面设计 最后考虑加入图形化用户交互组件使得整个解决方案更加直观易懂。借助 OpenCV 或 PyQt 等工具库能够快速搭建起具备基本功能的应用程序框架[^2]。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值