cars.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import numpy as np
  2. from os.path import join
  3. from nabirds.utils import _MetaInfo
  4. from .base import BaseAnnotations
  5. class CARS_Annotations(BaseAnnotations):
  6. name="CARS"
  7. @property
  8. def meta(self):
  9. info = _MetaInfo(
  10. images_folder="images",
  11. images_file="images.txt",
  12. labels_file="labels.txt",
  13. split_file="tr_ID.txt",
  14. bounding_boxes="bounding_boxes.txt",
  15. bounding_box_dtype=np.dtype([(v, np.int32) for v in "xywh"]),
  16. parts_file=join("parts", "part_locs.txt"),
  17. part_names_file=join("parts", "parts.txt"),
  18. )
  19. info.structure = [
  20. [info.images_file, "_images"],
  21. [info.labels_file, "labels"],
  22. [info.split_file, "_split"],
  23. [info.parts_file, "_part_locs"],
  24. [info.part_names_file, "_part_names"],
  25. [info.bounding_boxes, "_bounding_boxes"],
  26. ]
  27. return info
  28. def __init__(self, *args, **kwargs):
  29. super(CARS_Annotations, self).__init__(*args, **kwargs)
  30. # set labels from [1..N] to [0..N-1]
  31. self.labels -= 1
  32. def _load_split(self):
  33. assert self._split is not None, "Train-test split was not loaded!"
  34. uuid_to_split = {uuid: int(split) for uuid, split in zip(self.uuids, self._split)}
  35. self.train_split = np.array([uuid_to_split[uuid] for uuid in self.uuids], dtype=bool)
  36. self.test_split = np.logical_not(self.train_split)
  37. def _load_parts(self):
  38. self.part_names = {}
  39. # load only if present
  40. if self.has_parts:
  41. super(CARS_Annotations, self)._load_parts(idx_offset=1)
  42. self._load_bounding_boxes()
  43. def _load_bounding_boxes(self):
  44. assert self._bounding_boxes is not None, "Bouding boxes were not loaded!"
  45. uuid_to_bbox = {}
  46. for content in [i.split() for i in self._bounding_boxes]:
  47. uuid, bbox = content[0], content[1:]
  48. uuid_to_bbox[uuid] = [float(i) for i in bbox]
  49. self.bounding_boxes = np.array(
  50. [tuple(uuid_to_bbox[uuid]) for uuid in self.uuids],
  51. dtype=self.meta.bounding_box_dtype)
  52. def parts(self, *args, **kwargs):
  53. if self.has_parts:
  54. return super(CARS_Annotations, self).parts(*args, **kwargs)
  55. return None
  56. def bounding_box(self, uuid):
  57. return self.bounding_boxes[self.uuid_to_idx[uuid]].copy()