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

本文详细介绍了如何使用Python编写一个函数,将COCO数据集转换为YOLO所需的格式,包括图像信息、注释和类别映射。通过这个脚本,用户可以方便地处理COCO数据并支持YOLO算法的训练。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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 数据集转换YOLO 格式 为了实现这一目标,可以遵循特定的过程来确保数据集能够被顺利转换并用于后续的目标检测任务。 #### 创建必要的目录结构 在 `convert2yolo` 文件夹中创建一个新的名为 YOLO 的文件夹[^1]。这一步骤有助于组织转换后的图像和标签文件,使得整个项目更加整洁有序。 #### 修改配置文件名 将原本命名为 coco.txt 的文件重命名为 coco.names。此操作是为了适应 YOLO 模型对于类别名称定义的要求,其中每一行代表一个类别的名字。 #### 编写转换脚本 编写 Python 脚本来处理 COCO JSON 注释文件到 YOLO 文本格式转换工作。该脚本会读取原始标注信息,并将其重新格式化为目标检测框架所需的输入形式: ```python import json from pathlib import Path def convert_coco_to_yolo(coco_annotation_file, output_dir): with open(coco_annotation_file) as f: data = json.load(f) categories = {category['id']: category['name'] for category in data['categories']} image_info = {} for img in data["images"]: image_info[img["id"]] = { 'file_name': img["file_name"], 'height': img["height"], 'width': img["width"] } annotations_by_image_id = {} for ann in data["annotations"]: if ann["image_id"] not in annotations_by_image_id: annotations_by_image_id[ann["image_id"]] = [] bbox = ann["bbox"] x_center = (bbox[0] + bbox[2] / 2) / image_info[ann["image_id"]]['width'] y_center = (bbox[1] + bbox[3] / 2) / image_info[ann["image_id"]]['height'] width_ratio = bbox[2] / image_info[ann["image_id"]]['width'] height_ratio = bbox[3] / image_info[ann["image_id"]]['height'] class_index = list(categories.keys()).index(ann["category_id"]) annotation_line = f"{class_index} {x_center:.6f} {y_center:.6f} {width_ratio:.6f} {height_ratio:.6f}" annotations_by_image_id[ann["image_id"]].append(annotation_line) for image_id, lines in annotations_by_image_id.items(): file_path = Path(output_dir) / Path(image_info[image_id]["file_name"]).with_suffix('.txt') with open(file_path, "w") as f: f.write("\n".join(lines)) if __name__ == "__main__": train_json = "/path/to/instances_train2017.json" val_json = "/path/to/instances_val2017.json" output_folder = "./YOLO" convert_coco_to_yolo(train_json, output_folder) convert_coco_to_yolo(val_json, output_folder) ``` 上述代码展示了如何解析 COCO JSON 文件中的对象边界框坐标以及对应的分类 ID ,然后按照 YOLO 所需的方式计算中心点位置及其相对于图片尺寸的比例值[^2]。 #### 运行转换工具 确保已经安装了所需依赖库之后,在命令行界面执行这段Python程序两次——一次针对训练集(`train`),另一次则是验证集(`val`)。由于算法效率较高,即使面对大规模的数据集合也能快速完成转换过程。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小张Tt

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

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

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

打赏作者

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

抵扣说明:

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

余额充值