def create_annotations(directory, img_dir): annotations = {} for dir_name in os.listdir(directory): if not (dir_name == "images"): for _, _, files in os.walk(os.path.join(directory, dir_name)): mat = scipy.io.loadmat(os.path.join(directory, dir_name, ANNOTATION_FILE)) for i, img_file in enumerate(sorted(files)): if not (img_file.endswith(".mat")): new_img_file = dir_name + "_" + img_file image = { "name": new_img_file, "objects": [] } for segmentation in mat["polygons"][0][i]: if segmentation.any(): image["objects"].append(segmentation.tolist()) annotations[new_img_file] = image shutil.move(os.path.join(directory, dir_name, img_file), os.path.join(img_dir, new_img_file)) with open(os.path.join(directory, SAVE_FILE), 'w') as output_json_file: json.dump(annotations, output_json_file) for dir_name in os.listdir(directory): if not (dir_name == "images" or dir_name == "annotations.json"): shutil.rmtree(os.path.join(directory, dir_name))