fgvc_aircraft.py 4.9 KB

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