Skip to content

Instantly share code, notes, and snippets.

@PaleNeutron
Created December 20, 2020 11:17
Show Gist options
  • Save PaleNeutron/a6d228e6184673af2c7a6c342b98a2fc to your computer and use it in GitHub Desktop.
Save PaleNeutron/a6d228e6184673af2c7a6c342b98a2fc to your computer and use it in GitHub Desktop.
Convert Labelme json to YOLO format
# -*- coding: utf-8 -*-
'''
LabelMe JSON format -> YOLO txt format
save dataset in dataset/
output will be saved in result/
'''
import json
import os
def convert(size, box):
"""Each row of yolo format is class x_center y_center width height format"""
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
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 read_classes(classes_file_path):
with open(classes_file_path) as f:
classes = f.read().split()
return {cls: i for i, cls in enumerate(classes)}
if __name__ == '__main__':
"""-------------------------------------------------------------------"""
""" Configure Paths"""
mypath = "./dataset/"
outpath = "./result/"
classes_file_path = "./classes.names"
classes = read_classes(classes_file_path)
# list_file = open('%s_list.txt'%(wd), 'w')
""" Get input json file list """
json_name_list = []
for file in os.listdir(mypath):
if file.endswith(".json"):
json_name_list.append(file)
""" Process """
for json_name in json_name_list:
txt_name = json_name.rstrip(".json") + ".txt"
""" Open input text files """
txt_path = mypath + json_name
print("Input:" + txt_path)
txt_file = open(txt_path, "r")
""" Open output text files """
txt_outpath = outpath + txt_name
print("Output:" + txt_outpath)
txt_outfile = open(txt_outpath, "w")
""" Convert the data to YOLO format """
json_file = json.load(txt_file)
for shape in json_file["shapes"]:
if "label" in shape:
points = shape["points"]
cls = shape["label"]
cls_id = classes[cls]
x_all = [p[0] for p in points]
y_all = [p[1] for p in points]
xmin = min(x_all)
xmax = max(x_all)
ymin = min(y_all)
ymax = max(y_all)
img_path = json_file["imagePath"]
w = json_file["imageWidth"]
h = json_file["imageHeight"]
print(w, h)
print(xmin, xmax, ymin, ymax)
b = (xmin, xmax, ymin, ymax)
bb = convert((w, h), b)
print(bb)
txt_outfile.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
txt_outfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment