json格式数据集标注文件转换到yolov5所需的txt标注文件

import json
import os

def json_to_yolo_txt(json_path, output_folder):
    # 读取 JSON 文件
    with open(json_path, 'r') as f:
        data = json.load(f)

    # 创建输出文件夹
    os.makedirs(output_folder, exist_ok=True)

    # 处理 images 信息
    images = data.get('images', {})
    for image_info in images:
        image_id = image_info['id']
        image_filename = image_info['file_name']
        image_width = image_info['width']
        image_height = image_info['height']

        # 处理 annotations
        annotations = [ann for ann in data.get('annotations', []) if ann['image_id'] == image_id]
        for annotation in annotations:
            bbox = annotation['bbox']
            category_id = annotation['category_id']

            # 计算中心点坐标和宽高的相对值
            x_center = (bbox[0] + bbox[2] / 2) / image_width
            y_center = (bbox[1] + bbox[3] / 2) / image_height
            width = bbox[2] / image_width
            height = bbox[3] / image_height

            # 构造每个 annotation 对应的 TXT 文件内容
            txt_content = f"{category_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n"

            # 写入 TXT 文件
            txt_filename = f"{image_filename.replace('.jpg', '')}.txt"
            txt_path = os.path.join(output_folder, txt_filename)
            with open(txt_path, 'a') as txt_file:
                txt_file.write(txt_content)

    print("TXT 文件已生成!")

# 指定输入的 JSON 文件和输出的文件夹路径
json_file_path = "你的输入文件路径"
output_folder_path = "你的输出文件路径"

# 调用函数进行转换
json_to_yolo_txt(json_file_path, output_folder_path)

每个txt文件命名为对应的图片名(参考json里的标注)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值