Python解析labelme生成的json文件(bbox标注)

json文件

{
  "version": "3.16.7",
  "imageWidth": 1024,
  "lineColor": [
    0,
    255,
    0,
    128
  ],
  "flags": {},
  "fillColor": [
    255,
    0,
    0,
    128
  ],
  "imageData": "/9j/4AAQSkZJRgABAQAAAQABAAD
  "imagePath": "../airplane/0a7cbe64b71d8026.jpg",
  "shapes": [
    {
      "fill_color": null,
      "line_color": null,
      "flags": {},
      "shape_type": "rectangle",
      "points": [
        [
          639.5679012345679,
          327.8641975308642
        ],
        [
          746.9753086419753,
          403.1728395061728
        ]
      ],
      "label": "cargo"
    }
  ],
  "imageHeight": 678
}

 

解析代码(生成yolo的标签文件)

#!/usr/bin/python3
# -*- coding: utf-8 -*-

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
    return (x,y,w,h)


def decode_json(json_floder_path,json_name):

    txt_name = '/home/deepnorth/A_codeTest/txt_label/' + json_name[0:-5] + '.txt'
    txt_file = open(txt_name, 'w')

    json_path = os.path.join(json_floder_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'] == 'cargo'):

            x1 = int(i['points'][0][0])
            y1 = int(i['points'][0][1])
            x2 = int(i['points'][1][0])
            y2 = int(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_floder_path = '/home/deepnorth/A_codeTest/label'
    json_names = os.listdir(json_floder_path)
    for json_name in json_names:
        decode_json(json_floder_path,json_name)

 

你可能感兴趣的:(数据集解析,json文件解析)