【目标检测】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)
相关推荐
shayudiandian3 小时前
YOLOv8目标检测项目实战(从训练到部署)
人工智能·yolo·目标检测
Hcoco_me18 小时前
YOLO目标检测学习路线图
学习·yolo·目标检测
dotphoenix20 小时前
在wsl ubuntu下安装,训练,验证,导出,部署YOLO的完整例子
yolo
会篮球的程序猿1 天前
html+canvas+thikphp 可视化工具拖拽、编辑生成JSON,渲染成海报图片 完全自定义,支持选择,文字背景色
前端·html·json
倚肆1 天前
Hutool-json 库完整指南
java·json
q***23922 天前
MySQL JSON数据类型全解析(JSON datatype and functions)
android·mysql·json
paopao_wu2 天前
目标检测YOLO[03]:推理入门
人工智能·yolo·目标检测
WWZZ20252 天前
快速上手大模型:深度学习11(数据增强、微调、目标检测)
人工智能·深度学习·算法·目标检测·计算机视觉·大模型·具身智能
深度学习lover3 天前
<项目代码>yolo遥感航拍船舶识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·遥感船舶识别
FL16238631293 天前
无人机方面数据集目标检测分割分类数据集汇总介绍
目标检测·分类·无人机