美文网首页darknet
labelme标注的json标签转txt格式

labelme标注的json标签转txt格式

作者: 1037号森林里一段干木头 | 来源:发表于2020-11-26 17:05 被阅读0次

    简介:

    在机器学习训练中常常会有不同格式的标签之间的转换,在此造个轮子方便使用。

    1.labelme标注:

    labelme.PNG

    2.json文件

    {
      "version": "4.5.6",
      "flags": {},
      "shapes": [
        {
          "label": "1",
          "points": [
            [
              1609.6923076923076,
              884.6153846153846
            ],
            [
              1988.1538461538462,
              1172.3076923076924
            ]
          ],
          "group_id": null,
          "shape_type": "rectangle",
          "flags": {}
        },
        {
          "label": "0",
          "points": [
            [
              1352.7692307692307,
              3.0769230769230766
            ],
            [
              1925.076923076923,
              578.4615384615385
            ]
          ],
          "group_id": null,
          "shape_type": "rectangle",
          "flags": {}
        }
      ],
      "imagePath": "..\\imgs\\0001.jpg",
      "imageData": null,
      "imageHeight": 1492,
      "imageWidth": 2040
    }
    

    3.json解析:

    • annotation里面存放labelme生成的标注文件
    • imgs里面存图片
    • txtlabel文件夹存放我们转换后的txt标签文件

    3.1 从json查看标注结果

    import json
    import os
    import cv2
    img_folder_path=r'F:\imagedata\FOV\FOV_SRC_2\imgs'#原图片存放地址
    folder_path=r"F:\imagedata\FOV\FOV_SRC_2\annotation"#标注数据的文件地址
    
    
    # cv2.putText(img, str, (123,456)), font, 2, (0,255,0), 3)
    # 各参数依次是:图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细
    def show_label_from_json(img_path,json_d):
        window_name = ('src') 
        cv2.namedWindow(window_name,cv2.WINDOW_FREERATIO)
        src_img=cv2.imread(img_path)   
        font = cv2.FONT_HERSHEY_SIMPLEX
        for item in json_d["shapes"]:
            #print(item['points'])
            point=item['points']
            p1=(int(point[0][0]),int(point[0][1]))
            p2=(int(point[1][0]),int(point[1][1]))
            cv2.rectangle(src_img, p1, p2, (0, 255, 0), 2)
            cv2.putText(src_img,item['label'],p1,font,2,(0,255,255),3)
            cv2.imshow(window_name,src_img)
            cv2.waitKey(0)
        cv2.destroyAllWindows()
        return 
    
    i=0
    for jsonfile in os.listdir(folder_path):
        temp_path=os.path.join(folder_path,jsonfile)
        
        i+=1
        if i>5:
            break
        #如果是一个子目录就继续
        if os.path.isdir(temp_path):
            continue
        print("json_path:\t",temp_path)
        temp_path
        with open(temp_path, "r", encoding='utf-8') as f:
            json_d = json.load(f)
            img_name=json_d['imagePath'].split("\\")[-1].split(".")[0]+".jpg"
            img_path=os.path.join(img_folder_path,img_name)    
            print("img_path:\t",img_path)
            show_label_from_json(img_path,json_d)
    
    image.png

    3.2 json转txt
    有些用图片的绝对坐标,有的用相对坐标,下面两种方式都写了

    • 相对坐标形式 :label x_center y_center w h
    • 绝对坐标形式 :label x1 y1 x2 y2(x1,y1是标记的左上角的坐标,x2 y2右下角坐标)
    import json
    import os
    import cv2
    img_folder_path=r'F:\imagedata\FOV\FOV_SRC_2\imgs'#图片存放文件夹
    folder_path=r"F:\imagedata\FOV\FOV_SRC_2\annotation"#标注数据的文件地址
    txt_folder_path = r"F:\imagedata\FOV\FOV_SRC_2\txtlabel"#转换后的txt标签文件存放的文件夹
    
    #保存为相对坐标形式 :label x_center y_center w h
    def relative_coordinate_txt(img_name,json_d,img_path):
        src_img=cv2.imread(img_path)
        h,w = src_img.shape[:2]
        txt_name = img_name.split(".")[0]+".txt"
        txt_path = os.path.join(txt_folder_path,txt_name)
        print(txt_path)
        with open(txt_path,'w') as f:
            for item in json_d["shapes"]:
                #print(item['points'])
                #print(item['label'])
                point=item['points']
                x_center = (point[0][0]+point[1][0])/2
                y_center = (point[0][1]+point[1][1])/2
                width = point[1][0]-point[0][0]
                hight = point[1][1]-point[0][1]
                #print(x_center)
                f.write(" {} ".format(item['label']))
                f.write(" {} ".format(x_center/w))
                f.write(" {} ".format(y_center/h))
                f.write(" {} ".format(width/w))
                f.write(" {} ".format(hight/h))
                f.write(" \n")
                
    #保存为绝对坐标形式 :label x1 y1 x2 y2
    def absolute_coordinate_txt(img_name,json_d,img_path):
        src_img=cv2.imread(img_path)
        h,w = src_img.shape[:2]
        txt_name = img_name.split(".")[0]+".txt"
        txt_path = os.path.join(txt_folder_path,txt_name)
        print("txt_path:\t",txt_path)
        with open(txt_path,'w') as f:
            for item in json_d["shapes"]:
                #print(item['points'])
                #print(item['label'])
                point=item['points']
                x1 = point[0][0]
                y1 = point[0][1]
                x2 = point[1][0]
                y2 = point[1][1]
                f.write(" {} ".format(item['label']))
                f.write(" {} ".format(x1))
                f.write(" {} ".format(y1))
                f.write(" {} ".format(x2))
                f.write(" {} ".format(y2))
                f.write(" \n")
    
    i=0
    for jsonfile in os.listdir(folder_path):
        temp_path=os.path.join(folder_path,jsonfile)
        
        i+=1
        if i>5:
            break
        #如果是一个子目录就继续
        if os.path.isdir(temp_path):
            continue
        print("json_path:\t",temp_path)
        jsonfile_path=temp_path
        with open(jsonfile_path, "r", encoding='utf-8') as f:
            json_d = json.load(f)
            img_name=json_d['imagePath'].split("\\")[-1].split(".")[0]+".jpg"
            img_path=os.path.join(img_folder_path,img_name)
            print("img_path:\t",img_path)
            relative_coordinate_txt(img_name,json_d,img_path)
            absolute_coordinate_txt(img_name,json_d,img_path)
    

    3.3 从txt查看标注结果

    import json
    import os
    import cv2
    img_folder_path=r'F:\imagedata\FOV\FOV_SRC_2\imgs'#图片存放文件夹
    folder_path=r"F:\imagedata\FOV\FOV_SRC_2\annotation"#标注数据的文件地址
    txt_folder_path = r"F:\imagedata\FOV\FOV_SRC_2\txtlabel"#转换后的txt标签文件存放的文件夹
    
    
    #相对坐标格式
    def show_label_from_txt(img_path,txt_path):
        window_name = ('src') 
        cv2.namedWindow(window_name,cv2.WINDOW_FREERATIO)
        src_img=cv2.imread(img_path)    
        h,w = src_img.shape[:2]
        font = cv2.FONT_HERSHEY_SIMPLEX
        with open(temp_path, "r", encoding='utf-8') as f:
            lines = f.readlines()
        for line in lines:
            data = line.split(' ')
            label = data[1]
            x1 = int((float(data[3]) - float(data[7])/2)*w)
            y1 = int((float(data[5]) - float(data[9])/2)*h)
            x2 = int((float(data[3]) + float(data[7])/2)*w)
            y2 = int((float(data[5]) + float(data[9])/2)*h)      
            p1 = (x1,y1)
            p2 = (x2,y2)
            cv2.rectangle(src_img, p1, p2, (0, 250, 0), 2)
            cv2.putText(src_img,label,p1,font,2,(0,255,255),3)
            cv2.imshow(window_name,src_img)
            cv2.waitKey(0)
        cv2.destroyAllWindows()
        return 
    
    i=0
    for txtfile in os.listdir(txt_folder_path):
        temp_path=os.path.join(txt_folder_path,txtfile)
        
        i+=1
        if i>15:
            break
        #如果是一个子目录就继续
        if os.path.isdir(temp_path):
            continue
        print("txt_path:\t",temp_path)
        img_name=txtfile.split("\\")[-1].split(".")[0]+".jpg"
        img_path=os.path.join(img_folder_path,img_name)
        show_label_from_txt(img_path,temp_path)
        
    
    image.png

    相关文章

      网友评论

        本文标题:labelme标注的json标签转txt格式

        本文链接:https://www.haomeiwen.com/subject/elaaiktx.html