【目标检测】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)
相关推荐
hans汉斯9 小时前
【计算机科学与应用】YOLO-Apple:一种用于苹果幼果检测的改进型目标检测方法
人工智能·yolo·目标检测·计算机视觉·目标跟踪·数据·病虫害检测
动物园猫10 小时前
外墙裂缝目标检测数据集分享(适用于YOLO系列深度学习分类检测任务)
深度学习·yolo·目标检测
TheRouter10 小时前
LLM 流式输出工程实践:SSE、背压、断流重连与JSON 流解析的 6 个生产陷阱
人工智能·json
stsdddd14 小时前
YOLO系列目标检测数据集大全【第七期】
yolo·目标检测·目标跟踪
YOLO数据集集合14 小时前
无人机低空安防巡检AI落地方案|航拍小目标人员入侵检测、多场景跨领域目标检测数据集与YOLO算法工程实战
人工智能·yolo·目标检测·无人机
Ricky055314 小时前
基于对比学习的卫星影像目标检测领域适应方法(2024年美国研究)
人工智能·学习·目标检测
chushiyunen15 小时前
json-rpc笔记
笔记·rpc·json
钓了猫的鱼儿15 小时前
基于深度学习+AI的茶叶病害目标检测与预警系统(Python源码+数据集+UI可视化界面+YOLOv11训练结果)
人工智能·深度学习·目标检测
YOLO数据集集合15 小时前
YOLOv11+DeepSeek多技术融合电网缺陷巡检平台|绝缘子破损瓷瓶故障AI识别、前后端一体化电力运维管理系统落地开发
运维·人工智能·yolo
Jumbuck_1015 小时前
从零实现《三角洲行动》手游自动跑刀脚本:ADB 直控 + OpenCV 视觉识别 + 固定点位搜刮)三角洲自动跑刀教程
嵌入式硬件·yolo·目标检测·自动化·自动驾驶·三角洲·自动跑刀