labelme标注的json文件转为yolov5 所需的txt

import json
import os


def convert(img_size, box):
    x1 = box[0]
    y1 = box[1]
    x2 = box[2]
    y2 = box[3]

    center_x = (x1 + x2) * 0.5 / img_size[0]
    center_y = (y1 + y2) * 0.5 / img_size[1]
    w = abs((x2 - x1)) * 1.0 / img_size[0]
    h = abs((y2 - y1)) * 1.0 / img_size[1]

    return (center_x, center_y, w, h)


def convert1(img_size, box):
    x1 = box[0]
    y1 = box[1]

    center_x = x1 / img_size[0]
    center_y = y1 / img_size[1]

    return (center_x, center_y)


def decode_json(jsonfloder_path, json_name):
    txt_name = '/home/wyr/jc_photo_test/labels/' + json_name[0:-5] + '.txt'
    # txt保存位置

    txt_file = open(txt_name, 'w')  # te files

    json_path = os.path.join(json_folder_path, json_name)
    data = json.load(open(json_path, 'r'))

    img_w = data['imageWidth']
    img_h = data['imageHeight']
    for i in data['shapes']:
        if (i['shape_type'] == 'rectangle'):  # 仅适用矩形框标注
            x1 = float(i['points'][0][0])
            y1 = float(i['points'][0][1])
            x2 = float(i['points'][1][0])
            y2 = float(i['points'][1][1])
            if x1 < 0 or x2 < 0 or y1 < 0 or y2 < 0:
                continue
            else:
                bb = (x1, y1, x2, y2)
                bbox = convert((img_w, img_h), bb)
            if i['label'] == "jc_re":
                txt_file.write("0 " + " ".join([str(a) for a in bbox])+" ")
            # elif i['label'] == "jc_point":
            # txt_file.write("1 " + " ".join([str(a) for a in bbox]) + '\n')
            # elif i['label'] == "Computer":
            # txt_file.write("2 " + " ".join([str(a) for a in bbox]) + '\n')
            # else:
            # txt_file.write("3 " + " ".join([str(a) for a in bbox]) + '\n')
        elif (i['shape_type'] == 'point'):  # 适用点标注

            x1 = float(i['points'][0][0])
            y1 = float(i['points'][0][1])
            if x1 < 0 or y1 < 0:
                continue
            else:
                bb = (x1, y1)
                bbox = convert1((img_w, img_h), bb)
            if i['label'] == "jc_point":
                # txt_file.write(" ".join([str(a) for a in bbox]) + "\n")
                txt_file.write(" ".join([str(a) for a in bbox])+" ")


if __name__ == "__main__":

    json_folder_path = '/home/wyr/jc_photo_test/'  # json文件夹路径
    json_names = os.listdir(json_folder_path)  # file name
    for json_name in json_names:  # output all files
        if json_name[-5:] == '.json':  # just work for json files
            decode_json(json_folder_path, json_name)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值