【目标检测】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)
相关推荐
Coovally AI模型快速验证10 分钟前
未来已来:从 CVPR & ICCV 观察 2025→2026 年计算机视觉的七大走向
人工智能·深度学习·目标检测·计算机视觉·stable diffusion
人工智能的苟富贵35 分钟前
用 Rust 写一个前端项目辅助工具:JSON 格式化器
前端·rust·json
B站_计算机毕业设计之家44 分钟前
计算机视觉:python车辆行人检测与跟踪系统 YOLO模型 SORT算法 PyQt5界面 目标检测+目标跟踪 深度学习 计算机✅
人工智能·python·深度学习·算法·yolo·目标检测·机器学习
fl1768313 小时前
基于yolov8+vue3实现目标检测后台管理系统
人工智能·yolo·目标检测
却道天凉_好个秋16 小时前
目标检测算法与原理(一):迁移学习
算法·目标检测·迁移学习
笑脸惹桃花17 小时前
目标检测数据集——路面裂缝检测数据集
人工智能·深度学习·yolo·目标检测·计算机视觉·数据集
清风与日月20 小时前
halcon分类器使用标准流程
深度学习·目标检测·计算机视觉
FL162386312920 小时前
[yolov11改进系列]基于yolov11使用fasternet_t0替换backbone用于轻量化网络的python源码+训练源码
python·yolo·php
AI浩1 天前
深入级联不稳定性:从 Lipschitz 连续性视角探讨图像恢复与目标检测的协同作用
人工智能·目标检测·php
星辰pid1 天前
基于ROS与YOLOv3的智能采购机器人设计(智能车创意组-讯飞智慧生活组)
人工智能·opencv·yolo·机器人