fgvc_aircraft.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. from __future__ import annotations
  2. import os
  3. from typing import Any, Callable, Optional, Tuple
  4. import PIL.Image
  5. from .utils import download_and_extract_archive, verify_str_arg
  6. from .vision import VisionDataset
  7. class FGVCAircraft(VisionDataset):
  8. """`FGVC Aircraft <https://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft/>`_ Dataset.
  9. The dataset contains 10,000 images of aircraft, with 100 images for each of 100
  10. different aircraft model variants, most of which are airplanes.
  11. Aircraft models are organized in a three-levels hierarchy. The three levels, from
  12. finer to coarser, are:
  13. - ``variant``, e.g. Boeing 737-700. A variant collapses all the models that are visually
  14. indistinguishable into one class. The dataset comprises 100 different variants.
  15. - ``family``, e.g. Boeing 737. The dataset comprises 70 different families.
  16. - ``manufacturer``, e.g. Boeing. The dataset comprises 30 different manufacturers.
  17. Args:
  18. root (string): Root directory of the FGVC Aircraft dataset.
  19. split (string, optional): The dataset split, supports ``train``, ``val``,
  20. ``trainval`` and ``test``.
  21. annotation_level (str, optional): The annotation level, supports ``variant``,
  22. ``family`` and ``manufacturer``.
  23. transform (callable, optional): A function/transform that takes in an PIL image
  24. and returns a transformed version. E.g, ``transforms.RandomCrop``
  25. target_transform (callable, optional): A function/transform that takes in the
  26. target and transforms it.
  27. download (bool, optional): If True, downloads the dataset from the internet and
  28. puts it in root directory. If dataset is already downloaded, it is not
  29. downloaded again.
  30. """
  31. _URL = "https://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft/archives/fgvc-aircraft-2013b.tar.gz"
  32. def __init__(
  33. self,
  34. root: str,
  35. split: str = "trainval",
  36. annotation_level: str = "variant",
  37. transform: Optional[Callable] = None,
  38. target_transform: Optional[Callable] = None,
  39. download: bool = False,
  40. ) -> None:
  41. super().__init__(root, transform=transform, target_transform=target_transform)
  42. self._split = verify_str_arg(split, "split", ("train", "val", "trainval", "test"))
  43. self._annotation_level = verify_str_arg(
  44. annotation_level, "annotation_level", ("variant", "family", "manufacturer")
  45. )
  46. self._data_path = os.path.join(self.root, "fgvc-aircraft-2013b")
  47. if download:
  48. self._download()
  49. if not self._check_exists():
  50. raise RuntimeError("Dataset not found. You can use download=True to download it")
  51. annotation_file = os.path.join(
  52. self._data_path,
  53. "data",
  54. {
  55. "variant": "variants.txt",
  56. "family": "families.txt",
  57. "manufacturer": "manufacturers.txt",
  58. }[self._annotation_level],
  59. )
  60. with open(annotation_file, "r") as f:
  61. self.classes = [line.strip() for line in f]
  62. self.class_to_idx = dict(zip(self.classes, range(len(self.classes))))
  63. image_data_folder = os.path.join(self._data_path, "data", "images")
  64. labels_file = os.path.join(self._data_path, "data", f"images_{self._annotation_level}_{self._split}.txt")
  65. self._image_files = []
  66. self._labels = []
  67. with open(labels_file, "r") as f:
  68. for line in f:
  69. image_name, label_name = line.strip().split(" ", 1)
  70. self._image_files.append(os.path.join(image_data_folder, f"{image_name}.jpg"))
  71. self._labels.append(self.class_to_idx[label_name])
  72. def __len__(self) -> int:
  73. return len(self._image_files)
  74. def __getitem__(self, idx: int) -> Tuple[Any, Any]:
  75. image_file, label = self._image_files[idx], self._labels[idx]
  76. image = PIL.Image.open(image_file).convert("RGB")
  77. if self.transform:
  78. image = self.transform(image)
  79. if self.target_transform:
  80. label = self.target_transform(label)
  81. return image, label
  82. def _download(self) -> None:
  83. """
  84. Download the FGVC Aircraft dataset archive and extract it under root.
  85. """
  86. if self._check_exists():
  87. return
  88. download_and_extract_archive(self._URL, self.root)
  89. def _check_exists(self) -> bool:
  90. return os.path.exists(self._data_path) and os.path.isdir(self._data_path)