【目标检测】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)
相关推荐
qq_252941316823 分钟前
多模态屋顶损伤与杂物检测数据集 | 屋顶检测 多模态 红外可见光 建筑巡检 目标检测9232期
人工智能·深度学习·yolo·目标检测·计算机视觉·屋顶
jay神1 小时前
基于 YOLOv11 的无人机航拍小目标检测系统
人工智能·深度学习·yolo·目标检测·计算机视觉·无人机·计算机毕业设计
jay神1 小时前
基于 YOLOv8 的手势识别系统
人工智能·深度学习·yolo·机器学习·计算机视觉·目标跟踪·课程设计
qq_25294131683 小时前
不同成熟度番茄果实多模态图像数据集 | 番茄成熟度 多模态检测 可见光深度红外 智慧农业 语义分割 目标检测9233期
人工智能·yolo·目标检测·目标跟踪·番茄多模态
江屿风4 小时前
【Plain Language Large Model】【大语言模型底层原理全解析:从Token生成到智能体演进】流食般投喂
人工智能·笔记·语言模型·llm·json·token·聊天模板
jay神4 小时前
基于 YOLOv8 的垃圾分类识别系统
人工智能·深度学习·yolo·机器学习·目标跟踪·分类·计算机毕业设计
qq_25294131685 小时前
航拍地面垃圾检测数据集 | 垃圾检测 航拍巡检 环境治理 目标检测 YOLO格式9224期
人工智能·yolo·目标检测·计算机视觉·垃圾检测·航拍地面
情 九15 小时前
Dify HTTP 请求节点实战:发送 JSON、解析响应与处理异常
网络协议·http·json·dify
fleaxin20 小时前
Atlas 300V:(3)模型精度数据对比
yolo·华为·atlas
jay神1 天前
基于 YOLOv8 与 Faster R-CNN 的盲道障碍检测系统
人工智能·深度学习·yolo·计算机视觉·cnn·课程设计·计算机毕业设计