【目标检测】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)
相关推荐
fl1768311 小时前
无人机视角低空拍摄的土豆马铃薯幼苗与杂草检测数据集VOC+YOLO格式5266张6类
yolo·无人机
qq_252941316816 小时前
列车车轮缺陷智能检测数据集:800张图像、4大类别,助力铁路安全运维
运维·人工智能·安全·yolo·目标检测·计算机视觉·视觉检测
雨晨源码(同名B站)18 小时前
基于深度学习YoloV11农业病害虫害检测系统 智慧农业信息化综合管理平台 (附源码+lw文档+ppt)
数据库·人工智能·深度学习·yolo·信息可视化
灵析表格1 天前
json_ObjectToKV 函数:Excel解析JSON对象的权威方案
json·excel
灵析表格1 天前
灵析表格文本处理函数技术白皮书:WPS Excel 官方函数扩展库 18 项文本规整与正则批处理企业落地标准
ai·json·excel·wps
西柚研究生1234561 天前
论文分析15:跨层特征交互的多尺度无人机小目标检测算法
人工智能·算法·目标检测
guo_xiao_xiao_2 天前
YOLO工业质检与产品展示灯泡目标检测数据集-509张
yolo·目标检测·目标跟踪
AI即插即用2 天前
即插即用系列 | IEEE TMI PLG-HN:原型学习引导的 CNN-Transformer 混合网络,攻克乳腺肿瘤分割难题
人工智能·深度学习·神经网络·学习·目标检测·cnn·transformer
桑榆4162 天前
JSON 格式
json
阿钱真强道2 天前
28 YOLOv8 ONNX输出的cls与box提取详解——从[1,84,8400]到检测框
目标检测·模型部署·yolov8·int8量化