YOLO-COCO数据集
时间: 2025-04-29 11:50:05 浏览: 23
### YOLO 和 COCO 数据集概述
YOLO (You Only Look Once) 是一种流行的实时目标检测算法,其数据集格式相对简洁。而 COCO (Common Objects in Context) 数据集则是一个大型图像识别、分割和字幕生成数据库,广泛用于计算机视觉研究。
#### YOLO 格式特点
YOLO 的标注文件通常为 `.txt` 文件,每行代表一个对象的类别及其边界框位置,采用归一化坐标表示法[^1]:
```
<class_id> <center_x> <center_y> <width> <height>
```
其中 `<class_id>` 表示类别的索引号;其他四个参数均为相对于图片尺寸的比例值。
#### COCO 格式特点
COCO 数据集中每个样本由一张或多张带有详细注解信息的 JSON 文件描述,包含但不限于:
- 图像基本信息(ID, 宽高)
- 对象实例列表(bbox, segmentation mask, area 等)
JSON 结构较为复杂,适合处理多样的场景需求[^2]。
#### 转换过程简介
为了实现从 YOLO 至 COCO 的转换,主要涉及以下几个方面的工作:
- **目录结构调整**:按照特定规则重新组织原始数据的位置;
- **标签映射创建**:建立两套编号体系之间的对应关系表;
- **脚本编写执行**:利用 Python 编写自动化工具完成实际迁移操作[^3]。
```python
import json
from pathlib import Path
def yolo_to_coco(yolo_dir: str, coco_output_path: str):
"""Converts YOLO format dataset to COCO format."""
images = []
annotations = []
annotation_id = 0
# Iterate over all image files and their corresponding label txt files.
for img_file in Path(yolo_dir).glob('*.jpg'):
with open(str(img_file.with_suffix('.txt'))) as f:
lines = f.readlines()
width, height = get_image_size(img_file)
image_info = {
'id': len(images),
'file_name': img_file.name,
'width': width,
'height': height
}
images.append(image_info)
for line in lines:
class_id, center_x, center_y, bbox_width, bbox_height = map(float, line.strip().split())
x_min = int((center_x - bbox_width / 2.) * width)
y_min = int((center_y - bbox_height / 2.) * height)
w = int(bbox_width * width)
h = int(bbox_height * height)
anno = {
'id': annotation_id,
'image_id': image_info['id'],
'category_id': int(class_id)+1, # Assuming category IDs start from 1 in COCO
'segmentation': [],
'area': float(w*h),
'bbox': [x_min, y_min, w, h],
'iscrowd': 0
}
annotations.append(anno)
annotation_id += 1
output_dict = {'images': images, 'annotations': annotations}
with open(coco_output_path, 'w') as outfile:
json.dump(output_dict, outfile)
def get_image_size(file_path):
"""Helper function to read an image file's dimensions"""
pass # Implementation depends on the library used
if __name__ == '__main__':
yolo_to_coco('./data/yolo', './output/coco.json')
```
阅读全文
相关推荐


















