【目标检测】YOLO格式数据集txt标注转换为COCO格式JSON

YOLO格式数据集:

python 复制代码
images
|--train
|--test
|--val


labels
|--train
|--test
|--val

代码:

python 复制代码
import os
import json
from PIL import Image

# 设置数据集路径
dataset_path = "path/to/your/dataset"
images_path = os.path.join(dataset_path, "images")
labels_path = os.path.join(dataset_path, "labels")

# 类别映射
categories = [
    {"id": 1, "name": "category1"},
    {"id": 2, "name": "category2"},
    # 添加更多类别
]

# YOLO格式转COCO格式的函数
def convert_yolo_to_coco(x_center, y_center, width, height, img_width, img_height):
    x_min = (x_center - width / 2) * img_width
    y_min = (y_center - height / 2) * img_height
    width = width * img_width
    height = height * img_height
    return [x_min, y_min, width, height]

# 初始化COCO数据结构
def init_coco_format():
    return {
        "images": [],
        "annotations": [],
        "categories": categories
    }

# 处理每个数据集分区
for split in ['train', 'test', 'val']:
    coco_format = init_coco_format()
    annotation_id = 1

    for img_name in os.listdir(os.path.join(images_path, split)):
        if img_name.lower().endswith(('.png', '.jpg', '.jpeg')):
            img_path = os.path.join(images_path, split, img_name)
            label_path = os.path.join(labels_path, split, img_name.replace("jpg", "txt"))

            img = Image.open(img_path)
            img_width, img_height = img.size
            image_info = {
                "file_name": img_name,
                "id": len(coco_format["images"]) + 1,
                "width": img_width,
                "height": img_height
            }
            coco_format["images"].append(image_info)

            if os.path.exists(label_path):
                with open(label_path, "r") as file:
                    for line in file:
                        category_id, x_center, y_center, width, height = map(float, line.split())
                        bbox = convert_yolo_to_coco(x_center, y_center, width, height, img_width, img_height)
                        annotation = {
                            "id": annotation_id,
                            "image_id": image_info["id"],
                            "category_id": int(category_id) + 1,
                            "bbox": bbox,
                            "area": bbox[2] * bbox[3],
                            "iscrowd": 0
                        }
                        coco_format["annotations"].append(annotation)
                        annotation_id += 1

    # 为每个分区保存JSON文件
    with open(f"path/to/output/{split}_coco_format.json", "w") as json_file:
        json.dump(coco_format, json_file, indent=4)
相关推荐
Wang's Blog16 小时前
Java框架快速入门: Spring Security+OAuth2之自定义认证过滤器实现JSON登录
java·spring·json
淼澄研学18 小时前
Win11 Dev Home与WinGet实操:基于JSON的声明式环境配置指南
json
YOLO数据集集合1 天前
福寿螺目标检测数据集 | 福寿螺检测 入侵物种 农业植保 目标检测9062期
人工智能·yolo·目标检测·计算机视觉·福寿螺·福寿螺检测·入侵物种
深度学习lover1 天前
<数据集>电力劳保穿戴识别<目标检测>
人工智能·yolo·目标检测·计算机视觉·数据集·电力劳保穿戴识别
YOLO数据集集合1 天前
反无人机禁飞识别无人机检测数据集 | 反无人机 禁飞识别 低空安防 目标检测 无人机检测10756期
人工智能·目标检测·无人机
可乐鸡翅yeah_1 天前
开发调试高频痛点解决,一站式在线加密解密与编码转换实战
json·加密解密·json在线转换
深度学习lover1 天前
<数据集>安全带穿戴识别<目标检测>
人工智能·yolo·目标检测·计算机视觉·安全带穿戴识别
小疯仔2 天前
轨迹在地图上“漂“了 500 米?一文吃透 WGS-84→GCJ-02 坐标转换引擎(GPX→JSON 实战源码剖析)
小程序·json·notepad++
Flynt2 天前
"只输出 JSON"根本不够:LLM 结构化输出的坑,我实测了 60 次调用
llm·json
这张生成的图像能检测吗2 天前
(论文速读)GMA-Net:面向嵌入式物联网设备的航空发动机损伤检测轻量级实时网络
物联网·目标检测·缺陷检测·轻量化·设备部署