Labelme生成的json文件转为txt格式

 使用Labelme标注软件会生成json格式的文件,而YOLOv5需要的标注文件是txt格式的。使用以下python代码可以使json格式转为txt格式,有几处代码需要修改:

1、json存放的文件夹路径与txt存放的文件夹路径

2、标注过程中用到的标签,以及确认是否使用矩形框进行的标注

3、如果有多个label需要创建if语句,并修改txt_file.write代码

import json
import os


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
    x1 = box[0]
    y1 = box[1]
    x2 = box[2]
    y2 = box[3]
    return x, y, w, h


def decode_json(json_folder_path, json_name):
    txt_name = '/home/xue/xlc/yolov5/' + json_name[0:-5] + '.txt'  # 生成的txt文件存放的路径
    txt_file = open(txt_name, 'w')
    json_path = os.path.join(json_folder_path, json_name)
    data = json.load(open(json_path, 'r', encoding='utf-8'))
    img_w = data['imageWidth']
    img_h = data['imageHeight']
    for i in data['shapes']:
        if i['shape_type'] == 'rectangle' and i['label'] == 'person':  # 分类的标签
            x1 = float((i['points'][0][0]))
            y1 = float((i['points'][0][1]))
            x2 = float((i['points'][1][0]))
            y2 = float((i['points'][1][1]))

            bb = (x1, y1, x2, y2)
            bbox = convert((img_w, img_h), bb)
            txt_file.write('0' + " " + " ".join([str(a) for a in bbox]) + '\n')


if __name__ == "__main__":
    json_folder_path = '/home/xue/xlc/yolov5/ImageData/'  # json文件存放的路径
    json_names = os.listdir(json_folder_path)
    for json_name in json_names:
        decode_json(json_folder_path, json_name)

  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值