Merge COCO annotation files. Args: input_extend: Path to input file to be extended. input_add: Path to input file to be added. output_file : Path to output file with merged annotations. indent: Argument passed to `json.dump`. See https://docs.python.org/3/library
(
img_root_list: List[str], input_list: List[str],
indent: Optional[int] = None,
)
| 254 | |
| 255 | |
| 256 | def coco_merge( |
| 257 | img_root_list: List[str], input_list: List[str], |
| 258 | indent: Optional[int] = None, |
| 259 | ) -> str: |
| 260 | """Merge COCO annotation files. |
| 261 | |
| 262 | Args: |
| 263 | input_extend: Path to input file to be extended. |
| 264 | input_add: Path to input file to be added. |
| 265 | output_file : Path to output file with merged annotations. |
| 266 | indent: Argument passed to `json.dump`. See https://docs.python.org/3/library/json.html#json.dump. |
| 267 | """ |
| 268 | data_list = [] |
| 269 | |
| 270 | for input in input_list: |
| 271 | data_extend = PetrelHelper.load_json(input) |
| 272 | data_list.append(data_extend) |
| 273 | |
| 274 | output= {'categories': data_list[0]['categories']} |
| 275 | |
| 276 | output["images"], output["annotations"] = [], [] |
| 277 | |
| 278 | for i, (data, img_root) in enumerate(zip(data_list, img_root_list)): |
| 279 | |
| 280 | print( |
| 281 | "Input {}: {} images, {} annotations".format( |
| 282 | i + 1, len(data["images"]), len(data["annotations"]) |
| 283 | ) |
| 284 | ) |
| 285 | |
| 286 | cat_id_map = {} |
| 287 | for new_cat in data["categories"]: |
| 288 | new_id = None |
| 289 | for output_cat in output["categories"]: |
| 290 | if new_cat["name"] == output_cat["name"]: |
| 291 | new_id = output_cat["id"] |
| 292 | break |
| 293 | |
| 294 | if new_id is not None: |
| 295 | cat_id_map[new_cat["id"]] = new_id |
| 296 | else: |
| 297 | new_cat_id = max(c["id"] for c in output["categories"]) + 1 |
| 298 | cat_id_map[new_cat["id"]] = new_cat_id |
| 299 | new_cat["id"] = new_cat_id |
| 300 | output["categories"].append(new_cat) |
| 301 | |
| 302 | img_id_map = {} |
| 303 | for image in data["images"]: |
| 304 | n_imgs = len(output["images"]) |
| 305 | img_id_map[image["id"]] = n_imgs |
| 306 | image["id"] = n_imgs |
| 307 | image["img_root"] = img_root |
| 308 | |
| 309 | output["images"].append(image) |
| 310 | |
| 311 | for annotation in data["annotations"]: |
| 312 | n_anns = len(output["annotations"]) |
| 313 | annotation["id"] = n_anns |