json代码转换成YOLO格式的txt标签

import json
import os

def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[2]) / 2.0
    y = (box[1] + box[3]) / 2.0
    w = box[2] - box[0]
    h = box[3] - box[1]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)

def decode_json(json_path, output_dir):
    with open(json_path, 'r') as f:
        data = json.load(f)

    base_name = os.path.splitext(os.path.basename(data['imagePath']))[0]
    txt_path = os.path.join(output_dir, base_name + '.txt')
    with open(txt_path, 'w') as txt_file:
        for shape in data['shapes']:
            if shape['shape_type'] == 'rectangle':
                label = shape['label']
                points = shape['points']
                x1, y1 = points[0]
                x2, y2 = points[1]  # Assuming the points are diagonal

                bb = convert((data['imageWidth'], data['imageHeight']), [x1, y1, x2, y2])
                txt_file.write(f"{label} {' '.join(map(str, bb))}\n")



# # ...之前的代码...
#
# def decode_json(json_path, output_dir):
#     with open(json_path, 'r') as f:
#         data = json.load(f)
#
#     base_name = os.path.splitext(os.path.basename(data['imagePath']))[0]
#     txt_path = os.path.join(output_dir, base_name + '.txt')
#     with open(txt_path, 'w') as txt_file:
#         for shape in data['shapes']:
#             if shape['shape_type'] == 'rectangle':
#                 label = shape['label']
#                 points = shape['points']
#
#                 # 只使用第一个和第三个点定义矩形(假设点是按顺序排列的)
#                 x1, y1 = points[0]
#                 x3, y3 = points[2]
#
#                 # 通过提取左上角和右下角的点来转换坐标并写入文件
#                 try:
#                     bb = convert((data['imageWidth'], data['imageHeight']), [x1, y1, x3, y3])
#                     txt_file.write(f"{label} {' '.join(map(str, bb))}\n")
#                 except ValueError as e:
#                     print(f"Error converting box with label {label}: {e}")
#                     continue
#
# # # ...之后的代码...


if __name__ == "__main__":
    json_folder_path = r'D:\Pycharm-Projects\ultralytics-main\json'  # JSON 文件所在的文件夹路径
    output_dir = r'D:\Pycharm-Projects\ultralytics-main\yolo_labels'  # 转换后的 YOLO 格式文本文件存放的文件夹路径,建议与JSON文件夹分开
    json_files = [file for file in os.listdir(json_folder_path) if file.endswith('.json')]

    for json_file in json_files:
        json_path = os.path.join(json_folder_path, json_file)
        decode_json(json_path, output_dir)



将 json_folder_path 替换为你存放 JSON 文件的实际文件夹路径,将 output_dir 替换为你想要保存转换后的 YOLO 格式文本文件的文件夹路径

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小远披荆斩棘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值