【目标检测】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)
相关推荐
前网易架构师-高司机13 小时前
带标注的SDD-SAR遥感船舶识别数据集,识别率92.9%,7000张图,支持yolo,coco json,voc xml,文末有模型训练代码
yolo·json·数据集·遥感·sar·船舶·sdd
QN1幻化引擎14 小时前
DalinX V8 — 整体能力地图与 AGI 阶段评估
人工智能·神经网络·目标检测·语言模型·数据挖掘·agi
AI浩14 小时前
面向野外无人机主动目标检测:大规模数据集、基准与方法
人工智能·目标检测·无人机
酉鬼女又兒18 小时前
零基础入门Vibe Coding实战:从RAG项目开发到测试部署全流程指南
开发语言·人工智能·机器学习·json
全堆鸿蒙19 小时前
鸿蒙应用开发实战【38】— 数据导出与备份:JSON 序列化
华为·json·harmonyos·鸿蒙系统
数聚天成DeepSData19 小时前
自动驾驶感知数据集选型指南:目标检测、分割、车道线、车牌识别
人工智能·目标检测·自动驾驶
汤米粥19 小时前
Python爬虫——json解析
爬虫·python·json
蓝冰凌19 小时前
vscode 用户级 settings.json
ide·vscode·json
动物园猫1 天前
校园异常行为目标检测数据集:5类别 | 目标检测
人工智能·目标检测·计算机视觉
一见已难忘1 天前
4类红外热成像目标检测数据集(轿车/行人/货车/摩托车)| 4300张YOLO红外夜视检测数据集 适用于自动驾驶、智能安防与红外目标检测研究
yolo·目标检测·自动驾驶