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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
将实例分割的json文件换为yolotxt文件的主要步骤如下: 1. 读取json文件中的数据,包括图片大小、目标数量、目标类别、目标位置等信息。 2. 将目标位置信息按照yolo格式进行换。yolo格式中的坐标是归一化的,即左上角坐标为(0,0),右下角坐标为(1,1)。 3. 将目标类别信息换为对应的数字标签。 4. 将换后的目标信息按照yolo格式写入到txt文件中。 下面是一个基于Python语言的代码示例,用于将json文件换为yolotxt文件: ```python import json # 定义目标类别和对应数字标签的映射关系 class_map = {'car': 0, 'person': 1, 'dog': 2} def convert_json_to_txt(json_file, txt_file): with open(json_file, 'r') as f: data = json.load(f) img_width = data['imageWidth'] img_height = data['imageHeight'] objects = data['objects'] num_obj = len(objects) with open(txt_file, 'w') as f: for obj in objects: class_name = obj['classTitle'] if class_name not in class_map: continue class_id = class_map[class_name] x, y, w, h = obj['points']['exterior'][0] x_min = x / img_width y_min = y / img_height x_max = (x + w) / img_width y_max = (y + h) / img_height f.write(f"{class_id} {x_min:.6f} {y_min:.6f} {x_max:.6f} {y_max:.6f}\n") ``` 在上述代码中,`json_file`是要换的json文件路径,`txt_file`是输出的txt文件路径。`class_map`定义了目标类别和对应数字标签的映射关系,可以根据实际情况进行修改。`convert_json_to_txt`函数读取json文件中的数据,将目标位置信息按照yolo格式进行换,并将换后的目标信息写入到txt文件中。最后,调用该函数即可完成json文件到yolotxt文件的换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小远披荆斩棘

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

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

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

打赏作者

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

抵扣说明:

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

余额充值