【目标检测】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)
相关推荐
2501_941837266 小时前
蛤蜊生存状态分类识别 _ 基于YOLOv10n的海洋生物检测与分类_1
yolo·数据挖掘
Loacnasfhia910 小时前
面部表情识别与分类_YOLOv10n与MobileNetV4融合方案详解
yolo·分类·数据挖掘
小高Baby@12 小时前
JSON、bind、form
数据结构·json
Loacnasfhia913 小时前
贝类海产品物种识别与分类_---_基于YOLOv10n与特征金字塔共享卷积的改进方法
yolo·分类·数据挖掘
睡醒了叭13 小时前
目标检测-深度学习-SSD模型项目
人工智能·深度学习·目标检测
Coding茶水间13 小时前
基于深度学习的狗品种检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
开发语言·人工智能·深度学习·yolo·目标检测·机器学习
qwerasda12385214 小时前
游戏场景中的敌方目标检测与定位实战使用mask-rcnn_regnetx模型实现
人工智能·目标检测·游戏
阿蒙Amon14 小时前
TypeScript学习-第11章:配置文件(tsconfig.json)
学习·typescript·json
Dev7z15 小时前
基于改进YOLOv5n与OpenVINO加速的课堂手机检测系统设计与实现
人工智能·yolo·openvino·手机检测·课堂手机检测
Loacnasfhia916 小时前
【深度学习】【目标检测】YOLO11-C3k2-Faster-EMA模型实现草莓与番茄成熟度及病害识别系统
人工智能·深度学习·目标检测