Python中 json文件转化txt文件(矩形标注)

yolo目标检测

处理labelme矩形的标注  json转化txt

# 导入必要的库
import json
import os

# 定义一个标签到ID的映射
name2id = {'left_horn1': 0, 'left_horn2': 1, 'right_horn1': 2, 'right_horn2': 3}


# 定义转换函数,用于将坐标从原图到缩放图的转换
def convert(img_size, box):
    dw = 1. / img_size[0]
    dh = 1. / img_size[1]
    x = (box[0] + box[2]) / 2.0 - 1
    y = (box[1] + box[3]) / 2.0 - 1
    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)


# 解码JSON文件,并写入TXT文件
def decode_json(json_floder_path, json_name):
    txt_name = r'D:\python\yolov5\data_test\train\labels\\' + json_name[0:-5] + '.txt'
    txt_file = open(txt_name, 'w')
    json_path = os.path.join(json_floder_path, json_name)
    data = json.load(open(json_path, 'r', encoding='gb2312'))
    img_w = data['imageWidth']
    img_h = data['imageHeight']
    for i in data['shapes']:
        label_name = i['label']
        if i['shape_type'] == 'rectangle':  # 如果形状是矩形
            x1 = int(i['points'][0][0])
            y1 = int(i['points'][0][1])
            x2 = int(i['points'][1][0])
            y2 = int(i['points'][1][1])
            bb = (x1, y1, x2, y2)  # 获取边界框坐标
            bbox = convert((img_w, img_h), bb)  # 转换坐标
            txt_file.write(str(name2id[label_name]) + " " + " ".join([str(a) for a in bbox]) + '\n')  # 写入TXT文件


# 主函数,遍历指定目录下的所有JSON文件,并解码它们
if __name__ == '__main__':
    json_floder_path = r'D:\python\yolov5\data_test\train\json\\'  # JSON文件目录路径
    json_names = os.listdir(json_floder_path)  # 获取目录下的所有文件名
    for json_name in json_names:  # 遍历每一个JSON文件
        decode_json(json_floder_path, json_name)  # 解码JSON文件,并将结果写入TXT文件

  • 13
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值