coco数据集格式转yolo数据格式

一、coco数据集是什么?

COCO(Common Objects in Context)是一个广泛使用的目标检测和分割数据集,而YOLO(You Only Look Once)是一种流行的实时目标检测算法。

首先,导入了必要的库,包括jsonos。然后,定义了一个名为convert_coco_to_yolo的函数,用于将COCO数据转换为YOLO格式。该函数接受一个COCO数据的字典作为输入,并返回转换后的YOLO数据和类别字典。

在函数内部,提取了COCO数据中的图像列表、注释和类别信息。然后,创建了一个空的YOLO数据列表和一个用于存储类别名和序号映射关系的字典。

接下来,遍历图像列表,并获取图像的ID、文件名、宽度和高度。然后,根据图像ID筛选出与该图像相关的注释,并将它们存储在image_annotations列表中。

然后,遍历image_annotations列表,并提取注释的类别ID。通过在类别列表中查找与类别ID匹配的类别,可以获取类别的名称。如果找不到匹配的类别,则跳过该注释。

接下来,提取注释的边界框信息,并计算出边界框的中心坐标、归一化后的坐标和大小。将这些信息存储在yolo_annotations列表中。

如果存在YOLO注释,则按照类别序号对注释进行排序,并将图像的相关信息和注释存储在yolo_data列表中。

最后,返回转换后的YOLO数据和类别字典。

接下来,定义了几个变量,包括COCO数据文件的路径、文件名和保存目录的路径。然后,使用os.path.join函数构建了完整的文件路径。

通过检查文件是否存在,可以确保文件路径是有效的。如果文件存在,打开文件并加载其中的JSON数据。然后,调用convert_coco_to_yolo函数将COCO数据转换为YOLO数据。

使用os.makedirs函数创建保存目录,如果目录已经存在,则不进行任何操作。

接下来,生成了一个class.txt文件,用于存储类别的名称。遍历类别字典,并按照类别序号对字典进行排序。然后,将类别的名称写入文件中。

最后,遍历YOLO数据列表,并根据图像的文件名创建一个对应的.txt文件。然后,遍历注释列表,并将注释的类别和其他信息写入文件中。

最后,打印转换完成的消息,并显示保存目录的路径。如果文件不存在,则打印文件不存在的消息。

通过运行这个程序,可以将COCO数据集格式转换为YOLO格式,并将转换后的数据保存到指定的目录中。

这篇博客介绍了一个将COCO数据集格式转换为YOLO格式的Python程序。通过这个程序,可以轻松地处理COCO数据,并将其转换为适用于YOLO算法的格式。希望这个程序对你有所帮助!

二、完整代码

import json
import os

def convert_coco_to_yolo(coco_data):
    image_list = coco_data['images']
    annotations = coco_data['annotations']
    categories = coco_data['categories']

    yolo_data = []
    category_dict = {}  # 用于存储类别名和对应的序号
    for i, category in enumerate(categories):  # 构建类别名和序号的映射关系
        category_dict[category['name']] = i

    for image in image_list:
        image_id = image['id']
        file_name = image['file_name']
        width = image['width']
        height = image['height']

        image_annotations = [ann for ann in annotations if ann['image_id'] == image_id]
        yolo_annotations = []
        for ann in image_annotations:
            category_id = ann['category_id']
            category = next((cat for cat in categories if cat['id'] == category_id), None)
            if category is None:
                continue

            bbox = ann['bbox']
            x, y, w, h = bbox
            x_center = x + w / 2
            y_center = y + h / 2
            normalized_x_center = x_center / width
            normalized_y_center = y_center / height
            normalized_width = w / width
            normalized_height = h / height

            yolo_annotations.append({
                'category': category_dict[category['name']],  # 使用类别序号
                'x_center': normalized_x_center,
                'y_center': normalized_y_center,
                'width': normalized_width,
                'height': normalized_height
            })

        if yolo_annotations:
            yolo_annotations.sort(key=lambda x: x['category'])  # 按类别序号排序
            yolo_data.append({
                'file_name': file_name,
                'width': width,
                'height': height,
                'annotations': yolo_annotations
            })

    return yolo_data, category_dict

path = '/codeyard/yolov5_6.0/data_MS_1001labels'  # 修改为包含 via_export_coco.json 文件的目录路径
file_name = 'coco_filtered.json'  # 文件名
save_dir = '/codeyard/yolov5_6.0/data_MS_1001labels/labels'  # 保存目录
file_path = os.path.join(path, file_name)  # 完整文件路径

if os.path.isfile(file_path):  # 检查文件是否存在
    with open(file_path, 'r', encoding='utf-8') as load_f:
        load_dict = json.load(load_f)
        yolo_data, category_dict = convert_coco_to_yolo(load_dict)

    os.makedirs(save_dir, exist_ok=True)  # 创建保存目录

    # 生成 class.txt 文件
    class_file_path = os.path.join(save_dir, 'classes.txt')
    with open(class_file_path, 'w', encoding='utf-8') as class_f:
        for category_name, category_index in sorted(category_dict.items(), key=lambda x: x[1]):
            class_f.write(f"{category_name}\n")

    for data in yolo_data:
        file_name = os.path.basename(data['file_name'])  # 提取文件名部分
        width = data['width']
        height = data['height']
        annotations = data['annotations']

        txt_file_path = os.path.join(save_dir, os.path.splitext(file_name)[0] + '.txt')
        with open(txt_file_path, 'w', encoding='utf-8') as save_f:
            for annotation in annotations:
                category = annotation['category']
                x_center = annotation['x_center']
                y_center = annotation['y_center']
                box_width = annotation['width']
                box_height = annotation['height']

                line = f"{category} {x_center:.6f} {y_center:.6f} {box_width:.6f} {box_height:.6f}\n"
                save_f.write(line)

    print("转换完成,保存到:", save_dir)
else:
    print("文件不存在:", file_path)
### COCO 数据集概述 COCO(Common Objects in Context)数据集是一种广泛应用于计算机视觉领域的重要资源,其主要特点在于提供了丰富的上下文信息和多样化的标注方式。以下是关于 COCO 数据集的下载、使用说明及其格式的具体介绍。 --- ### 下载链接 COCO 数据集官方提供多种版本供研究者选择,具体可以从以下地址访问并下载: - 官方网站: [http://cocodataset.org/#download](http://cocodataset.org/#download)[^1] - 提供不同年份的数据集(如 2014 和 2017),每一年都有对应的训练集(train)、验证集(val)以及测试集(test)。对于初学者而言,可以尝试下载 `coco128.zip`,这是一个简化版的小型数据集,仅包含 128 张图片,非常适合用于快速实验和调试模型[^3]。 --- ### 使用说明 #### 数据准备 1. **下载与解压**: 首先从官方网站或其他可信源下载所需版本的数据集,并将其解压缩至指定路径。 2. **文件结构**: 解压后通常会得到如下目录结构: ``` /annotations/ instances_train2017.json person_keypoints_val2017.json ... /images/train2017/ (或 val2017/) image_000001.jpg image_000002.jpg ... ``` #### 工具支持 为了便于处理 JSON 格式标注文件,推荐使用 Python 库 `pycocotools` 来加载和操作数据集中的内容。安装方法如下: ```bash pip install pycocotools ``` 通过以下代码片段可读取标注文件并提取感兴趣的信息: ```python from pycocotools.coco import COCO # 初始化 COCO API 对象 dataDir = './path/to/coco' dataType = 'train2017' # 或其他子集名称 annFile = f'{dataDir}/annotations/instances_{dataType}.json' coco = COCO(annFile) # 获取类别列表 cats = coco.loadCats(coco.getCatIds()) print(f"COCO 类别: {', '.join([cat['name'] for cat in cats])}") # 加载特定类别的图像 ID 列表 catIds = coco.getCatIds(catNms=['person']) imgIds = coco.getImgIds(catIds=catIds) images = coco.loadImgs(imgIds[:5]) for img in images: print(f"Image Path: {f'{dataDir}/{dataType}/{img["file_name"]}'") ``` --- ### 数据集格式 COCO 数据集采用 JSON 文件存储所有标注信息,主要包括以下几个部分: 1. **基本信息** - `"info"` 字段描述了数据集元信息,例如创建时间、贡献者等。 2. **许可协议** - `"licenses"` 记录了数据使用的授权条款。 3. **分类标签** - `"categories"` 定义了数据集中可用的目标类别及其属性。 4. **图像记录** - `"images"` 包含每张图片的基本信息,如宽度 (`width`)、高度 (`height`) 及文件名 (`file_name`)。 5. **对象标注** - `"annotations"` 描述了每个目标的位置和语义信息。位置通常由边界框 (`bbox`) 表示为 `[x, y, width, height]` 形式;而对于实例分割任务,则额外包含了多边形顶点坐标或 RLE 编码掩膜[^1]。 此外,针对人体姿态估计任务,还存在专门的关键点标注字段 `"keypoints"` 和 `"num_keypoints"`,遵循严格的定义规则以便于后续算法开发[^2]。 --- ### 小结 综上所述,COCO 数据集以其灵活的标注形式和支持多样化任务的能力成为现代计算机视觉研究不可或缺的一部分。无论是目标检测还是更复杂的实例分割乃至关键点定位,都可以基于此构建高效解决方案。 ---
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张Tt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值