Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

fgvc_aircraft.py 4.9 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
  1. from __future__ import annotations
  2. import os
  3. from pathlib import Path
  4. from typing import Any, Callable, Optional, Tuple, Union
  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: Union[str, Path],
  39. split: str = "trainval",
  40. annotation_level: str = "variant",
  41. transform: Optional[Callable] = None,
  42. target_transform: Optional[Callable] = 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, "r") 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, "r") 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)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...