COCO 数据集
COCO(Common Objects in Context)是计算机视觉领域广泛使用的目标检测、实例分割和关键点检测数据集,由微软发布。其特点包括:
-
数据规模
包含超过 33 万张图像,标注对象超过 250 万个,涵盖 80 个常见物体类别(如人、车、动物等)。
-
标注类型
- 目标检测边界框: (x,y,width,height)
- 实例分割:多边形点集或 RLE 编码
- 关键点检测:人体 17 个关键点坐标
- 图像描述:每张图配有 5 句文字描述
-
数据结构
采用 JSON 格式组织,核心字段包括:
json{ "images": [{"id": 1, "file_name": "0001.jpg", "width": 640, "height": 480}], "annotations": [{ "id": 1, "image_id": 1, "category_id": 1, "bbox": [x,y,w,h], "segmentation": [[x1,y1,x2,y2,...]] }], "categories": [{"id": 1, "name": "person"}] }
转换为 YOLO 训练数据格式
YOLO 要求的数据格式为:
<类别索引> <中心点_x> <中心点_y> <宽度> <高度>
其中所有坐标值需归一化到 \[0,1\] 区间。
转换步骤:
-
数据归一化
对于每个边界框 (x,y,w,h) :
xcenter=x+w/2Wycenter=y+h/2Hwnorm=wWhnorm=hH \begin{aligned} x_{\text{center}} &= \frac{x + w/2}{W} \\ y_{\text{center}} &= \frac{y + h/2}{H} \\ w_{\text{norm}} &= \frac{w}{W} \\ h_{\text{norm}} &= \frac{h}{H} \end{aligned} xcenterycenterwnormhnorm=Wx+w/2=Hy+h/2=Ww=Hh其中 W 和 H 为图像宽高。
-
文件结构
-
每张图像对应一个
.txt标注文件 -
文件内容示例:
0 0.35 0.48 0.12 0.23 2 0.62 0.31 0.08 0.15
-
-
转换脚本示例
python
import json
# 加载 COCO 标注文件
with open('annotations.json') as f:
coco_data = json.load(f)
# 创建类别映射字典
cat_map = {cat['id']: idx for idx, cat in enumerate(coco_data['categories'])}
# 处理每张图像
for img in coco_data['images']:
img_id = img['id']
W, H = img['width'], img['height']
# 收集当前图像的所有标注
annotations = [a for a in coco_data['annotations'] if a['image_id'] == img_id]
# 生成 YOLO 格式文本
with open(f'labels/{img["file_name"].replace(".jpg", ".txt")}', 'w') as f:
for ann in annotations:
x, y, w, h = ann['bbox']
x_center = (x + w/2) / W
y_center = (y + h/2) / H
w_norm = w / W
h_norm = h / H
# 写入归一化坐标
f.write(f"{cat_map[ann['category_id']]} {x_center} {y_center} {w_norm} {h_norm}\n")
注意事项:
- 确保图像路径与标注文件路径匹配
- 类别索引需从 0 开始连续编号
- 对于分割任务需额外处理掩码数据
- 坐标值保留 6 位小数防止精度丢失
此转换适用于 YOLOv3/v4/v5/v6/v7/v8 等系列模型训练。