YOLOv8交通目标检测实战:从BDD100K到TT100K的数据集处理与模型训练全流程

1次阅读
没有评论

共计 2628 个字符,预计需要花费 7 分钟才能阅读完成。

image.webp

背景痛点

在交通目标检测任务中,数据集格式的混乱是一个常见问题。BDD100K 使用 JSON 格式的标注,而 TT100K 则采用特定的格式,CCTSDB2017 又有自己的标注规范。这种不统一导致在模型训练前需要进行大量的数据预处理工作,增加了开发者的负担。

YOLOv8 交通目标检测实战:从 BDD100K 到 TT100K 的数据集处理与模型训练全流程

技术方案

BDD100K JSON 转 YOLO txt 格式的 Python 脚本

以下是一个将 BDD100K JSON 标注转换为 YOLO txt 格式的 Python 脚本,包含异常处理和多线程优化:

import json
import os
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

def convert_bdd_to_yolo(json_path, output_dir, img_width, img_height):
    try:
        with open(json_path, 'r') as f:
            data = json.load(f)

        for frame in data['frames']:
            txt_path = os.path.join(output_dir, f"{frame['name'].replace('.jpg','.txt')}")
            with open(txt_path, 'w') as f:
                for obj in frame['objects']:
                    # 转换坐标到 YOLO 格式
                    x_center = (obj['box2d']['x1'] + obj['box2d']['x2']) / 2 / img_width
                    y_center = (obj['box2d']['y1'] + obj['box2d']['y2']) / 2 / img_height
                    width = (obj['box2d']['x2'] - obj['box2d']['x1']) / img_width
                    height = (obj['box2d']['y2'] - obj['box2d']['y1']) / img_height

                    # 写入 YOLO 格式的标注
                    f.write(f"{obj['category']} {x_center} {y_center} {width} {height}\n")
    except Exception as e:
        print(f"Error processing {json_path}: {e}")

# 多线程处理
json_files = list(Path('bdd100k/labels').glob('*.json'))
with ThreadPoolExecutor(max_workers=4) as executor:
    for json_file in json_files:
        executor.submit(convert_bdd_to_yolo, json_file, 'bdd100k/labels_yolo', 1280, 720)

data.yaml 配置要点

在 YOLOv8 中,data.yaml文件是数据集配置的核心。以下是一个针对 CCTSDB2017 的配置模板:

# CCTSDB2017 data.yaml
train: ../CCTSDB2017/images/train
val: ../CCTSDB2017/images/val

# 类别数量
nc: 3

# 类别名称
names:
  0: prohibitory
  1: mandatory
  2: warning

YOLOv8 模型选型对比

YOLOv8 提供了多个版本的模型(n/s/m/l/x),在交通场景下需要权衡精度和速度:

模型 mAP50 FPS (RTX 3090) 参数量 (M)
YOLOv8n 0.72 450 3.2
YOLOv8s 0.78 350 11.4
YOLOv8m 0.82 250 25.9
YOLOv8l 0.84 180 43.7
YOLOv8x 0.85 120 68.2

核心实现

使用 Albumentations 进行数据增强

Albumentations 是一个高效的数据增强库,以下是一个配置示例:

import albumentations as A

transform = A.Compose([A.RandomBrightnessContrast(p=0.5),
    A.HueSaturationValue(p=0.5),
    A.RandomGamma(p=0.5),
    A.Blur(blur_limit=3, p=0.3),
    A.HorizontalFlip(p=0.5),
], bbox_params=A.BboxParams(format='yolo'))

基于 PyTorch Lightning 的训练循环优化

使用 PyTorch Lightning 可以简化训练循环的编写,以下是一个优化技巧示例:

import pytorch_lightning as pl

class YOLOv8Lightning(pl.LightningModule):
    def __init__(self, model):
        super().__init__()
        self.model = model

    def training_step(self, batch, batch_idx):
        images, targets = batch
        loss = self.model(images, targets)
        self.log('train_loss', loss)
        return loss

    def configure_optimizers(self):
        return torch.optim.Adam(self.model.parameters(), lr=0.001)

避坑指南

标注文件路径错误的常见排查方法

  1. 检查标注文件是否与图片文件一一对应
  2. 确保标注文件中的类别 ID 与 data.yaml 中的类别名称一致
  3. 验证标注文件的路径是否正确,特别是在使用相对路径时

类别不平衡问题的解决策略

类别不平衡是交通目标检测中的常见问题,可以通过调整 Focal Loss 的参数来缓解:

# 在 YOLOv8 中设置 Focal Loss 参数
model = YOLO('yolov8s.yaml')
model.loss = FocalLoss(alpha=0.25, gamma=2.0)

显存不足时的 batch size 自适应方案

当显存不足时,可以动态调整 batch size:

# 自动调整 batch size
trainer = pl.Trainer(
    auto_scale_batch_size='power',
    gpus=1
)

开放性问题

如何将训练好的 YOLOv8 模型量化部署到 Jetson 边缘设备?这是一个值得探讨的方向,涉及到模型量化、TensorRT 优化等技术。

正文完
 0
评论(没有评论)