yolo数据集格式(txt)转coco格式,方便mmyolo转标签格式

部署运行你感兴趣的模型镜像

近期使用mmyolo过程中发现工具自带的yolo2coco.py在转换完数据集格式后,可视化标签的时候会有标签错乱情况,具体原因也没找到,肯定是转换过程代码有问题,于是重新做一份代码直接从yolo数据集转化为coco的json格式。
代码如下:
只需要维护
category_map
data[“categories”]
这两个标签id和标签名即可。
我的txt标签格式如下
在这里插入图片描述
标签类别为:
{“id”: 0, “name”: “person”},
{“id”: 1, “name”: “robotic-arm”}

import os
import json
from PIL import Image

# 定义类别映射
category_map = {
    "0": 0,
    "1": 1
}

def txt_to_json(input_dir, output_json):
    # 初始化输出数据结构
    data = {
        "images": [],
        "annotations": [],
        "categories": [
            {"id": 0, "name": "person"},
            {"id": 1, "name": "robotic-arm"}
        ]
    }

    # 用于生成唯一的 image_id 和 annotation_id
    image_id = 1
    annotation_id = 1

    # 动态读取图像尺寸
    def get_image_size(image_path):
        with Image.open(image_path) as img:
            return img.width, img.height

    # 遍历输入目录中的所有文件
    for filename in os.listdir(input_dir):
        if filename.endswith('.txt'):
            # 提取图像文件名
            image_name = filename.replace('.txt', '.jpg')
            image_path = os.path.join(input_dir, image_name)

            # 动态读取图像尺寸
            if os.path.exists(image_path):
                image_width, image_height = get_image_size(image_path)
            else:
                print(f"警告: 图像文件 {image_name} 不存在,跳过文件 {filename}")
                continue

            image_info = {
                "id": image_id,
                "width": image_width,
                "height": image_height,
                "file_name": image_name
            }
            data['images'].append(image_info)

            # 读取文本文件
            with open(os.path.join(input_dir, filename), 'r') as file:
                lines = file.readlines()

            # 遍历文件中的每一行
            for line in lines:
                parts = line.strip().split()
                if len(parts) != 5:
                    print(f"警告: 文件 {filename} 中的行格式错误: {line.strip()}")
                    continue  # 跳过格式错误的行

                category_id = int(parts[0])
                x_center = float(parts[1]) * image_width
                y_center = float(parts[2]) * image_height
                bbox_width = float(parts[3]) * image_width
                bbox_height = float(parts[4]) * image_height

                x_min = int(x_center - bbox_width / 2)
                y_min = int(y_center - bbox_height / 2)
                bbox = [x_min, y_min, bbox_width, bbox_height]
                area = bbox_width * bbox_height

                annotation_info = {
                    "id": annotation_id,
                    "image_id": image_id,
                    "category_id": category_id,
                    "bbox": bbox,
                    "area": area,
                    "iscrowd": 0
                }
                data['annotations'].append(annotation_info)
                annotation_id += 1

            image_id += 1

    # 保存到 JSON 文件
    with open(output_json, 'w') as json_file:
        json.dump(data, json_file, indent=4)

    print(f"转换完成,输出文件保存为 {output_json}")


# 调用函数
input_dir = './personDataset/train'
output_json = './trainval.json'
txt_to_json(input_dir, output_json)

input_dir = './personDataset/test'
output_json = './test.json'
txt_to_json(input_dir, output_json)

结果:
在这里插入图片描述
![](https://i-blog.csdnimg.cn/direct/7e18c88f355340d5aaae4d466bda827e.png在这里插入图片描述

您可能感兴趣的与本文相关的镜像

Yolo-v5

Yolo-v5

Yolo

YOLO(You Only Look Once)是一种流行的物体检测和图像分割模型,由华盛顿大学的Joseph Redmon 和Ali Farhadi 开发。 YOLO 于2015 年推出,因其高速和高精度而广受欢迎

### 数据准备与格式要求 在使用 YOLO-World 模型进行自定义数据集训练时,数据集的构建应遵循 COCO 数据集格式要求。这意味着需要准备训练集和验证集,每个集合都应包含图像文件夹(images)以及对应的 JSON 标注文件,这些文件中包含了图片中的边界框和类别信息。此外,还可以根据需要检测的类别自定义文本 JSON 文件,例如 `xxx_class_tsxts.json`,以适应特定的应用场景[^4]。 ### 配置文件修改与模型下载 为了确保训练过程顺利进行,需要对配置文件进行适当的修改。具体来说,如果微调数据集包含掩码注释,则应该使用含有 mask-refine 的 YOLOv8 配置文件;反之,如果不包含掩码注释,则应选择不包含 mask-refine 的配置文件。模型下载路径如下: - YOLO-World 模型下载地址:[YOLO-World](https://github.com/AILab-CVC/YOLO-World) - CLIP-ViT-Base-Patch32 模型下载地址:[CLIP-ViT-Base-Patch32](https://hf-mirror.com/openai/clip-vit-base-patch32) 修改后的配置文件示例如下: ```python _base_ = ('../../third_party/mmyolo/configs/yolov8/yolov8_l_syncbn_fast_8xb16-500e_coco.py') ``` ### 训练模型 完成数据准备和配置文件修改后,可以通过执行以下命令启动训练过程: ```bash python tools/train.py configs/finetune_coco/yolo_world_v2_l_vlpan_bn_sgd_1e-3_40e_8gpus_finetune_coco.py --work-dir log --amp --resume ``` 此命令指定了训练脚本的路径、工作目录,并启用了自动混合精度训练(AMP)和从断点恢复训练的功能。通过这种方式,可以有效地提高训练效率并保证训练过程的稳定性[^3]。 ### 训练效果与优势 YOLO-World 模型在自定义数据集上的表现优于传统的 YOLOv8 模型,特别是在 mAP 指标上有着显著的提升。更重要的是,YOLO-World 支持自定义类别检测,这使得它能够更好地适应各种特定的应用场景,满足不同项目的需求[^1]。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值