(annotation_paths: List[str],
label2id: Dict[str, int],
output_jsonpath: str,
extract_num_from_imgid: bool = True)
| 83 | |
| 84 | |
| 85 | def convert_xmls_to_cocojson(annotation_paths: List[str], |
| 86 | label2id: Dict[str, int], |
| 87 | output_jsonpath: str, |
| 88 | extract_num_from_imgid: bool = True): |
| 89 | output_json_dict = { |
| 90 | "images": [], |
| 91 | "type": "instances", |
| 92 | "annotations": [], |
| 93 | "categories": [] |
| 94 | } |
| 95 | bnd_id = 1 # START_BOUNDING_BOX_ID, TODO input as args ? |
| 96 | print('Start converting !') |
| 97 | for a_path in tqdm(annotation_paths): |
| 98 | # Read annotation xml |
| 99 | ann_tree = ET.parse(a_path) |
| 100 | ann_root = ann_tree.getroot() |
| 101 | |
| 102 | img_info = get_image_info(annotation_root=ann_root, |
| 103 | extract_num_from_imgid=extract_num_from_imgid) |
| 104 | img_id = img_info['id'] |
| 105 | output_json_dict['images'].append(img_info) |
| 106 | |
| 107 | for obj in ann_root.findall('object'): |
| 108 | ann = get_coco_annotation_from_obj(obj=obj, label2id=label2id) |
| 109 | ann.update({'image_id': img_id, 'id': bnd_id}) |
| 110 | output_json_dict['annotations'].append(ann) |
| 111 | bnd_id = bnd_id + 1 |
| 112 | |
| 113 | for label, label_id in label2id.items(): |
| 114 | category_info = {'supercategory': 'none', 'id': label_id, 'name': label} |
| 115 | output_json_dict['categories'].append(category_info) |
| 116 | |
| 117 | with open(output_jsonpath, 'w') as f: |
| 118 | output_json = json.dumps(output_json_dict) |
| 119 | f.write(output_json) |
| 120 | |
| 121 | |
| 122 | def main(): |
no test coverage detected