11import contextlib
22import json
3+ import shutil
34
5+ import yaml
46import cv2
57import pandas as pd
68from PIL import Image
@@ -254,13 +256,18 @@ def convert_coco_json(json_dir='../coco/annotations/', use_segments=False, cls91
254256 save_dir = make_dirs () # output directory
255257 coco80 = coco91_to_coco80_class ()
256258
259+ categories_dict = {}
260+
257261 # Import json
258- for json_file in sorted (Path (json_dir ).resolve ().glob ('*.json' )):
259- fn = Path (save_dir ) / 'labels' / json_file .stem .replace ('instances_' , '' ) # folder name
262+ for json_file in sorted (Path (json_dir ).resolve ().glob ('*coco* .json' )):
263+ fn = Path (save_dir ) / 'labels' / json_file .stem .replace ('instances_' , '' ). replace ( '_coco' , '' ) # folder name
260264 fn .mkdir ()
261265 with open (json_file ) as f :
262266 data = json .load (f )
263267
268+ # Create categories_dict
269+ categories_dict = {item ['id' ] - 1 : item ['name' ] for item in data ['categories' ]}
270+
264271 # Create image dict
265272 images = {'%g' % x ['id' ]: x for x in data ['images' ]}
266273 # Create image-annotations dict
@@ -308,9 +315,20 @@ def convert_coco_json(json_dir='../coco/annotations/', use_segments=False, cls91
308315 line = * (segments [i ] if use_segments else bboxes [i ]), # cls, box or segments
309316 file .write (('%g ' * len (line )).rstrip () % line + '\n ' )
310317
318+ yaml_dict = {
319+ "names" : {k : v for k , v in categories_dict .items ()},
320+ # "path": "yolo_datasets",
321+ "train" : "images/train" ,
322+ "val" : "images/val"
323+ }
324+
325+ with open ((Path (save_dir ) / json_file .stem ).with_suffix ('.yaml' ), "w" ) as f :
326+ yaml .dump (yaml_dict , f )
327+ shutil .copy ((Path (save_dir ) / json_file .stem ).with_suffix ('.yaml' ), (Path (save_dir ) / 'classes' ).with_suffix ('.yaml' ))
328+
311329
312330def min_index (arr1 , arr2 ):
313- """Find a pair of indexes with the shortest distance.
331+ """Find a pair of indexes with the shortest distance.
314332 Args:
315333 arr1: (N, 2).
316334 arr2: (M, 2).
@@ -324,12 +342,12 @@ def min_index(arr1, arr2):
324342def merge_multi_segment (segments ):
325343 """Merge multi segments to one list.
326344 Find the coordinates with min distance between each segment,
327- then connect these coordinates with one thin line to merge all
345+ then connect these coordinates with one thin line to merge all
328346 segments into one.
329347
330348 Args:
331349 segments(List(List)): original segmentations in coco's json file.
332- like [segmentation1, segmentation2,...],
350+ like [segmentation1, segmentation2,...],
333351 each segmentation is a list of coordinates.
334352 """
335353 s = []
0 commit comments