【目标检测】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)
相关推荐
minhuan1 天前
构建AI智能体:九十六、基于YOLO的智能生活助手:食材识别、植物健康与宠物行为分析
yolo·计算机视觉·视觉大模型·大模型应用
点PY2 天前
TR3D: Towards Real-Time Indoor 3D Object Detection论文精读
人工智能·目标检测·3d
xuehaikj2 天前
【深度学习】YOLOv10n-MAN-Faster实现包装盒flap状态识别与分类,提高生产效率
深度学习·yolo·分类
xuehaikj2 天前
【目标检测】YOLOv10n-ADown弹孔检测与识别系统
yolo·目标检测·目标跟踪
消失的旧时光-19432 天前
Kotlinx.serialization 使用指南
android·kotlin·json
消失的旧时光-19432 天前
Kotlinx.serialization 项目集成
android·kotlin·json
强盛小灵通专卖员2 天前
煤矿传送带异物检测:深度学习引领煤矿安全新革命!
人工智能·目标检测·sci·研究生·煤矿安全·延毕·传送带
B站_计算机毕业设计之家2 天前
python手写数字识别计分系统+CNN模型+YOLOv5模型 深度学习 计算机毕业设计(建议收藏)✅
python·深度学习·yolo·计算机视觉·数据分析·cnn
xuehaikj2 天前
基于YOLOv8的汽车目标检测系统实现与优化_含多种车型识别与自动驾驶应用场景
yolo·目标检测·汽车
xuehaikj2 天前
【水下目标检测】Yolov8-GDFPN实现水下气泡智能识别系统
yolo·目标检测·目标跟踪