Skip to content

Instantly share code, notes, and snippets.

@InputBlackBoxOutput
Created March 23, 2022 10:09
Show Gist options
  • Save InputBlackBoxOutput/9165e44891a4ac3a6b472f9abadb83cc to your computer and use it in GitHub Desktop.
Save InputBlackBoxOutput/9165e44891a4ac3a6b472f9abadb83cc to your computer and use it in GitHub Desktop.
labelImg: Convert annotations in JSON to YOLO format
import glob
import json
import cv2
LUT = {"class0": 0, "class1": 1, "class2": 2}
for each_file in glob.glob("data/*.json"):
with open(each_file) as json_file:
data = json.load(json_file)[0]
print(data["image"])
img = cv2.imread("data/" + data["image"])
height = img.shape[0]
width = img.shape[1]
print(height, width)
label = data["annotations"][0]['label']
x = data["annotations"][0]['coordinates']['x']
y = data["annotations"][0]['coordinates']['y']
annotation_width = data["annotations"][0]['coordinates']['width']
annotation_height = data["annotations"][0]['coordinates']['height']
annotation_yolo = f"{LUT[label]} {x/width} {y/height} {annotation_width/width} {annotation_height/height}"
print(annotation_yolo)
with open(data["image"][:-3] + "txt", 'w') as txt_file:
txt_file.write(annotation_yolo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment