Skip to content

Commit 3a82a39

Browse files
committed
Generate yaml including class id
1 parent 3762c5e commit 3a82a39

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

general_json2yolo.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import contextlib
22
import json
3-
3+
import yaml
44
import cv2
55
import pandas as pd
66
from PIL import Image
@@ -254,13 +254,18 @@ def convert_coco_json(json_dir='../coco/annotations/', use_segments=False, cls91
254254
save_dir = make_dirs() # output directory
255255
coco80 = coco91_to_coco80_class()
256256

257+
categories_dict = {}
258+
257259
# Import json
258260
for json_file in sorted(Path(json_dir).resolve().glob('*.json')):
259261
fn = Path(save_dir) / 'labels' / json_file.stem.replace('instances_', '') # folder name
260262
fn.mkdir()
261263
with open(json_file) as f:
262264
data = json.load(f)
263265

266+
# Create categories_dict
267+
categories_dict = {item['id']: item['name'] for item in data['categories']}
268+
264269
# Create image dict
265270
images = {'%g' % x['id']: x for x in data['images']}
266271
# Create image-annotations dict
@@ -308,6 +313,16 @@ def convert_coco_json(json_dir='../coco/annotations/', use_segments=False, cls91
308313
line = *(segments[i] if use_segments else bboxes[i]), # cls, box or segments
309314
file.write(('%g ' * len(line)).rstrip() % line + '\n')
310315

316+
yaml_dict = {
317+
"names": {v: k for k, v in categories_dict.items()},
318+
# "path": "yolo_datasets",
319+
"train": "images/train",
320+
"val": "images/val"
321+
}
322+
323+
with open((Path(save_dir) / json_file.stem).with_suffix('.yaml'), "w") as f:
324+
yaml.dump(yaml_dict, f)
325+
311326

312327
def min_index(arr1, arr2):
313328
"""Find a pair of indexes with the shortest distance.

0 commit comments

Comments
 (0)