Read json file with entries {classname: index} and return an array of class names in order. If parent_path is provided, load and map all children to their ids. Args: path (str): path to class ids json file. File must be in the format {"class1": id1, "class2": id2
(path, parent_path=None, subset_path=None)
| 343 | |
| 344 | |
| 345 | def get_class_names(path, parent_path=None, subset_path=None): |
| 346 | """ |
| 347 | Read json file with entries {classname: index} and return |
| 348 | an array of class names in order. |
| 349 | If parent_path is provided, load and map all children to their ids. |
| 350 | Args: |
| 351 | path (str): path to class ids json file. |
| 352 | File must be in the format {"class1": id1, "class2": id2, ...} |
| 353 | parent_path (Optional[str]): path to parent-child json file. |
| 354 | File must be in the format {"parent1": ["child1", "child2", ...], ...} |
| 355 | subset_path (Optional[str]): path to text file containing a subset |
| 356 | of class names, separated by newline characters. |
| 357 | Returns: |
| 358 | class_names (list of strs): list of class names. |
| 359 | class_parents (dict): a dictionary where key is the name of the parent class |
| 360 | and value is a list of ids of the children classes. |
| 361 | subset_ids (list of ints): list of ids of the classes provided in the |
| 362 | subset file. |
| 363 | """ |
| 364 | try: |
| 365 | with g_pathmgr.open(path, "r") as f: |
| 366 | class2idx = json.load(f) |
| 367 | except Exception as err: |
| 368 | print("Fail to load file from {} with error {}".format(path, err)) |
| 369 | return |
| 370 | |
| 371 | max_key = max(class2idx.values()) |
| 372 | class_names = [None] * (max_key + 1) |
| 373 | |
| 374 | for k, i in class2idx.items(): |
| 375 | class_names[i] = k |
| 376 | |
| 377 | class_parent = None |
| 378 | if parent_path is not None and parent_path != "": |
| 379 | try: |
| 380 | with g_pathmgr.open(parent_path, "r") as f: |
| 381 | d_parent = json.load(f) |
| 382 | except EnvironmentError as err: |
| 383 | print( |
| 384 | "Fail to load file from {} with error {}".format( |
| 385 | parent_path, err |
| 386 | ) |
| 387 | ) |
| 388 | return |
| 389 | class_parent = {} |
| 390 | for parent, children in d_parent.items(): |
| 391 | indices = [ |
| 392 | class2idx[c] for c in children if class2idx.get(c) is not None |
| 393 | ] |
| 394 | class_parent[parent] = indices |
| 395 | |
| 396 | subset_ids = None |
| 397 | if subset_path is not None and subset_path != "": |
| 398 | try: |
| 399 | with g_pathmgr.open(subset_path, "r") as f: |
| 400 | subset = f.read().split("\n") |
| 401 | subset_ids = [ |
| 402 | class2idx[name] |