【目标检测】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)
相关推荐
一晌小贪欢6 小时前
Python办公笔记——将csv文件转Json
笔记·python·json·python办公·python读取csv
Ayakanoinu7 小时前
【论文阅读】Adversarial Detection: Attacking Object Detection in Real Time
论文阅读·人工智能·目标检测
另寻沧海1 天前
如何打开vscode系统用户全局配置的settings.json
ide·vscode·json
leo_hush1 天前
java解析复杂json
java·前端·json
HyperAI超神经1 天前
在线教程丨YOLO系列10年更新11个版本,最新模型在目标检测多项任务中达SOTA
人工智能·深度学习·yolo·目标检测·机器学习·物体检测·姿态估计
HaiLang_IT2 天前
毕业设计:基于深度学习的高压线周边障碍物自动识别与监测系统
人工智能·目标检测·毕业设计
winrisef2 天前
YOLOv11实时目标检测 | 摄像头视频图片文件检测
人工智能·python·深度学习·yolo·目标检测·音视频
脚大江山稳2 天前
JSON常用的工具方法
java·json·糊涂工具
大美B端工场-B端系统美颜师3 天前
站在JavaScript的视角去看,HTML的DOM和GLTF的Json数据。
javascript·html·json·gltf
AI浩4 天前
【Block总结】HWD,小波下采样,适用分类、分割、目标检测等任务|即插即用
人工智能·目标检测·分类