labelme标注的json文件转成coco128的格式

用Labelme标注的实例分割的label,用于训练实例分割模型,但是后来想用Yolov5训练检测模型,不想重新标注数据,就用实例分割取出外接矩形框,转成coco128的那种格式,用于yolov5的训练。

转换代码如下,其中主要是涉及到一些json格式的处理,自己主要是用的是jupyter notebook单步调试的,所以代码格式看起来稍微有点乱。

# +
#encoding: utf-8
# -

import json
import cv2
import base64
import os


def readJson(jsonfile):
    with open(jsonfile,'r') as f:
        jsonData = json.load(f)
    return jsonData


def writeToJson(filePath,data):
    fb = open(filePath,'w')
    # json.dumps(data).decode('unicode-escape')
    fb.write(json.dumps(data,indent=2,ensure_ascii=False)) # ,encoding='utf-8'
    fb.close()


# +
#json_path = r'C:\Users\Administrator\Desktop\carton_data\carton_1_instance\1337_75.json'

# +
#contentJson = readJson(json_path)

# +
#print(contentJson['shapes'][0])

# +
#print(len(contentJson['shapes']))
# -

dicts = {"version":"4.2.7", "flags":{}, "shapes":[], "imagePath":"","imageData":"","imageHeight": 960, "imageWidth":1280}


def getMinRect(points_coord):
    len_pts = len(points_coord)
    x_min = 10000
    y_min = 10000 
    x_max = 0
    y_max = 0
    for i in range(len_pts):
        if points_coord[i][0] < x_min:
            x_min = points_coord[i][0]
        if points_coord[i][1] < y_min:
            y_min = points_coord[i][1]
        if points_coord[i][0] > x_max:
            x_max = points_coord[i][0]
        if points_coord[i][1] > y_max:
            y_max = points_coord[i][1]
    return x_min, y_min, x_max, y_max


size = len(json_path.split('\\'))
json_name = json_path.split('\\')[size - 1][:-4] + 'jpg'
image_name = json_name
for i in range(len(contentJson['shapes'])):
    x_min, y_min, x_max, y_max = getMinRect(contentJson['shapes'][i]["points"])
    tmp_rect_dict = {"label":"rect","points":[],"group_id":"","shape_type":"rectangle","flags":{}}
    pt1 = [x_min, y_min]
    pt2 = [x_max, y_max]
    tmp_rect_dict['points'].append(pt1)
    tmp_rect_dict['points'].append(pt2)
    dicts['shapes'].append(tmp_rect_dict)
    dicts['imagePath'] = image_name

new_json = r'C:\Users\Administrator\Desktop\carton_data\test\yrdy.json'
with open(new_json, "w") as dump_f:
    json.dump(dicts, dump_f)


def file_name(file_dir):
    L = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == '.json':
                L.append(os.path.join(root, file))
    return L


json_list = file_name(r'C:\Users\Administrator\Desktop\carton_data\carton_yolov5')
print(json_list[0])

for tmp_json in json_list:
    with open(tmp_json, "w+") as fp:
        size = len(tmp_json.split('\\'))
        json_name = tmp_json.split('\\')[size - 1][:-4] + 'jpg'
        image_name = json_name
        dicts = {"version":"4.2.7", "flags":{}, "shapes":[], "imagePath":"","imageData":"","imageHeight": 960, "imageWidth":1280}
        for i in range(len(contentJson['shapes'])):
            x_min, y_min, x_max, y_max = getMinRect(contentJson['shapes'][i]["points"])
            tmp_rect_dict = {"label":"rect","points":[],"group_id":"","shape_type":"rectangle","flags":{}}
            pt1 = [x_min, y_min]
            pt2 = [x_max, y_max]
            tmp_rect_dict['points'].append(pt1)
            tmp_rect_dict['points'].append(pt2)
            dicts['shapes'].append(tmp_rect_dict)
            dicts['imagePath'] = image_name
    os.remove(tmp_json)
    with open(tmp_json, "w+") as dump_f:
        json.dump(dicts, dump_f)

test_json = r"C:\Users\Administrator\Desktop\carton_data\test\1337_0.json"
contentJson = readJson(test_json)
print(contentJson["shapes"][0])

for tmp_json in json_list:
    contentJson = readJson(tmp_json)
    txt_name = tmp_json[:-4] + 'txt'
    with open(txt_name, 'w') as fp:
        for tmp_rect in contentJson["shapes"]:
            xmin = tmp_rect['points'][0][0]
            ymin = tmp_rect['points'][0][1]
            xmax = tmp_rect['points'][1][0]
            ymax = tmp_rect['points'][1][1]
            # image name
            image_name = tmp_json[:-4] + 'jpg'
            print(image_name)
            frame = cv2.imread(image_name)
            width = frame.shape[0]
            height = frame.shape[1]
            # normalize
            x0 = (xmin+xmax)*0.5/width
            y0 = (ymin+ymax)*0.5/height
            w0 = (xmax-xmin)*1.0/width
            h0 = (ymax-ymin)*1.0/height
            # save txt
            fp.write("0")
            fp.write(" ")
            fp.write(str(x0))
            fp.write(" ")
            fp.write(str(y0))
            fp.write(" ")
            fp.write(str(w0))
            fp.write(" ")
            fp.write(str(h0))
            fp.write("\n")
            


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值