Roboflow转Labelme

Labelme:json文件
Roboflow:YoloV5格式txt文件

def Txt2Json(txt_path, json_path, raw_w, raw_h, ID):
    shapes = []
    with open(txt_path, 'r') as f:
        for i in f.readlines():
            tmp_dict = {}
            
            pp = i.split(' ')
            
            tmp_dict['label'] = names[int(pp[0])]
            
            cx, cy, w, h = float(pp[1]), float(pp[2]), float(pp[3]), float(pp[4])
            
            #边界框反归一化
            x_t = cx * raw_w
            y_t = cy * raw_h
            w_t = w * raw_w
            h_t = h * raw_h
            
            #计算坐标
            x1 = x_t - w_t/2
            y1 = y_t - h_t/2
            x2 = x_t + w_t/2
            y2 = y_t + h_t/2
            
            tmp_dict['points'] = [[x1,y1], [x2,y2]]
            tmp_dict['group_id'] = None
            tmp_dict['shape_type'] = 'rectangle'
            tmp_dict['flags'] = {}
            
            shapes.append(tmp_dict)
            
    generate_labelme_json = {}
    generate_labelme_json['version'] = '5.0.1'
    generate_labelme_json['flags'] = {}
    generate_labelme_json['shapes'] = shapes
    generate_labelme_json['imagePath'] = ID + '.jpg'
    generate_labelme_json['imageData'] = None
    generate_labelme_json['imageHeight'] = raw_h
    generate_labelme_json['imageWidth'] = raw_w
    
    with open(json_path, 'w', encoding='utf-8') as f:
        json.dump(generate_labelme_json, f, indent=2)  # ensure_ascii=False



# names = ['1', '2', '3', '4', '5', '6', '7']
names = ['DN', 'IgAN']
# img_dir = glob('error-detection-v3-yolov5pytorch/train/images/*.jpg')
# img_dir = glob('tmp-img/*.jpg')
# img_dir = glob('C:/Users/29038/.keras/datasets/DN_database/labels/*.jpg')
img_dir = glob('C:/Users/29038/.keras/datasets/IgAN_database/labels/*.jpg')
img_size_dict = {}
for i in img_dir:
    w,h = Image.open(i).size
    img_id = i.split('\\')[-1].replace('.jpg', '')
    img_size_dict[img_id] = [w,h]






# roboflow_txt_dir = glob('error-detection-v3-yolov5pytorch/train/labels/*.txt')
# roboflow_txt_dir = glob('tmp-img/*.txt')
# roboflow_txt_dir = glob('C:/Users/29038/.keras/datasets/DN_database/labels/*.txt')
roboflow_txt_dir = glob('C:/Users/29038/.keras/datasets/IgAN_database/labels/*.txt')

for i in tqdm(roboflow_txt_dir):
    txt_path = i
    ID = i.split('\\')[-1].replace('.txt', '')
    raw_w, raw_h = img_size_dict[ID]
#     json_path = i.replace('labels', 'images').replace('.txt', '.json')
    json_path = i.replace('.txt', '.json')
    Txt2Json(txt_path, json_path, raw_w, raw_h, ID)



你可能感兴趣的:(人工智能)