【目标检测】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)
相关推荐
code_pgf9 分钟前
yolox详细讲解,包括网络结构图、关键创新点、部署
网络·人工智能·目标检测·ai
wal13145203 小时前
OpenClaw 2026.4.2 版本更新:默认 YOLO 模式,告别批准提示
人工智能·yolo·openclaw
code_pgf3 小时前
yolov5详细讲解,包括网络结构图、关键创新点和部署
网络·yolo
电商API&Tina8 小时前
【京东item_getAPI 】高稳定:API 、非爬虫、不封号、不掉线、大促稳跑
大数据·网络·人工智能·爬虫·python·sql·json
LittroInno8 小时前
T-JSON跨平台网络通信协议——边缘认知设备的二次开发实战指南
人工智能·计算机视觉·目标跟踪·json
chao1898448 小时前
基于粒子滤波的雷达弱小点目标检测MATLAB实现
人工智能·目标检测·matlab
童话名剑8 小时前
YOLO v8(学习笔记)
笔记·学习·yolo
Coovally AI模型快速验证9 小时前
低空安全刚需!西工大UAV-DETR反无人机小目标检测,参数减少40%,mAP50:95提升6.6个百分点
人工智能·目标检测·计算机视觉·无人机
code_pgf9 小时前
yolov10详细讲解,包括网络结构图、关键创新点、部署
yolo·目标检测
椰汁菠萝1 天前
Mybatis-plus + PostgreSQL json格式类型转换异常
postgresql·json·mybatis