制作自己的YOLOv8图像检测数据集需要经过数据收集、标注、格式转换和训练配置等步骤。以下是详细流程:
1. 数据收集
- 图像来源:
- 自行拍摄(确保光照、角度、场景多样)。
- 公开数据集(如COCO、Open Images等)中提取相关类别。
- 网络爬虫(注意版权问题)。
- 要求:
- 图像分辨率建议在640x640以上。
- 覆盖不同场景、光照、遮挡情况。
- 每类至少200~1000张图片(数据少时可使用数据增强)。
2. 数据标注
标注工具推荐
- LabelImg(经典工具):
bash
pip install labelImg labelImg # 启动后选择YOLO格式输出
- CVAT(在线协作工具):https://cvat.org/
- Roboflow(在线平台,支持自动标注):https://roboflow.com/
标注步骤
- 用工具标注目标物体,绘制边界框(Bounding Box)。
- 为每个框指定类别标签(如
person
、dog
)。 - 保存为YOLO格式:
- 每张图片生成一个
.txt
文件,内容示例:
坐标需归一化到<class_id> <x_center> <y_center> <width> <height>
[0,1]
(相对于图片宽高)。
- 每张图片生成一个
3. 数据集目录结构
YOLOv8要求如下结构:
dataset/
├── images/
│ ├── train/ # 训练集图片
│ ├── val/ # 验证集图片
│ └── test/ # 测试集图片(可选)
├── labels/
│ ├── train/ # 训练集标签
│ ├── val/ # 验证集标签
│ └── test/ # 测试集标签(可选)
- 划分比例:通常按70%训练、20%验证、10%测试。
- 可用脚本自动划分(如Python的
sklearn.model_selection.train_test_split
)。
4. 创建数据集配置文件
在YOLOv8中需定义dataset.yaml
文件:
yaml
path: /path/to/dataset # 数据集根目录
train: images/train # 训练集路径
val: images/val # 验证集路径
test: images/test # 测试集路径(可选)
# 类别定义
names:
0: cat
1: dog
2: car
5. 验证数据集
使用YOLOv8命令检查数据是否正确:
bash
yolo detect train data=dataset.yaml imgsz=640
或手动检查标签与图像是否对齐:
python
from PIL import Image, ImageDraw
import os
image = Image.open("dataset/images/train/001.jpg")
draw = ImageDraw.Draw(image)
with open("dataset/labels/train/001.txt") as f:
for line in f:
cls, x, y, w, h = map(float, line.split())
# 反归一化坐标
x1 = (x - w/2) * image.width
y1 = (y - h/2) * image.height
x2 = (x + w/2) * image.width
y2 = (y + h/2) * image.height
draw.rectangle([x1, y1, x2, y2], outline="red", width=2)
image.show()
6. 训练模型
bash
yolo detect train data=dataset.yaml model=yolov8n.pt epochs=100 imgsz=640
注意事项
- 数据平衡:各类别样本数量尽量均衡。
- 数据增强:使用Albumentations或Roboflow生成旋转、缩放、模糊等变体。
- 标签错误检查:避免漏标、误标(可用FiftyOne可视化分析)。
扩展工具
- 自动标注:用预训练模型(如YOLOv8)生成初始标签,再人工修正。
- 公开数据集转换:将COCO/VOC格式转为YOLO格式(可用
json2yolo
等工具)。
通过以上步骤,你可以构建一个高质量的定制数据集,并训练出符合需求的YOLOv8模型。