JSON转YOLOV5
import json
import os
import glob
import cv2
def mkdir(path):
if not os.path.exists(path):
os.mkdir(path)
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return x, y, w, h
def decode_json(json_path, txt_name):
txt_file = open(txt_name, 'w')
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'] == 'js'):
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, x2, y1, y2)
bbox = convert((img_w, img_h), bb)
txt_file.write( '0' + " " + " ".join([str(a) for a in bbox]) + '\n')
if __name__ == '__main__':
mkdir('labels')
jsonList = glob.glob('images/*.json')
for jsonPath in jsonList:
baseName = os.path.basename(jsonPath).split('.')[0]
txtName = f'labels/{baseName}.txt'
decode_json(jsonPath, txtName)