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

caltech.py 8.6 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
  1. import os
  2. import os.path
  3. from pathlib import Path
  4. from typing import Any, Callable, List, Optional, Tuple, Union
  5. from PIL import Image
  6. from .utils import download_and_extract_archive, verify_str_arg
  7. from .vision import VisionDataset
  8. class Caltech101(VisionDataset):
  9. """`Caltech 101 <https://data.caltech.edu/records/20086>`_ Dataset.
  10. .. warning::
  11. This class needs `scipy <https://docs.scipy.org/doc/>`_ to load target files from `.mat` format.
  12. Args:
  13. root (str or ``pathlib.Path``): Root directory of dataset where directory
  14. ``caltech101`` exists or will be saved to if download is set to True.
  15. target_type (string or list, optional): Type of target to use, ``category`` or
  16. ``annotation``. Can also be a list to output a tuple with all specified
  17. target types. ``category`` represents the target class, and
  18. ``annotation`` is a list of points from a hand-generated outline.
  19. Defaults to ``category``.
  20. transform (callable, optional): A function/transform that takes in a PIL image
  21. and returns a transformed version. E.g, ``transforms.RandomCrop``
  22. target_transform (callable, optional): A function/transform that takes in the
  23. target and transforms it.
  24. download (bool, optional): If true, downloads the dataset from the internet and
  25. puts it in root directory. If dataset is already downloaded, it is not
  26. downloaded again.
  27. .. warning::
  28. To download the dataset `gdown <https://github.com/wkentaro/gdown>`_ is required.
  29. """
  30. def __init__(
  31. self,
  32. root: Union[str, Path],
  33. target_type: Union[List[str], str] = "category",
  34. transform: Optional[Callable] = None,
  35. target_transform: Optional[Callable] = None,
  36. download: bool = False,
  37. ) -> None:
  38. super().__init__(os.path.join(root, "caltech101"), transform=transform, target_transform=target_transform)
  39. os.makedirs(self.root, exist_ok=True)
  40. if isinstance(target_type, str):
  41. target_type = [target_type]
  42. self.target_type = [verify_str_arg(t, "target_type", ("category", "annotation")) for t in target_type]
  43. if download:
  44. self.download()
  45. if not self._check_integrity():
  46. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  47. self.categories = sorted(os.listdir(os.path.join(self.root, "101_ObjectCategories")))
  48. self.categories.remove("BACKGROUND_Google") # this is not a real class
  49. # For some reason, the category names in "101_ObjectCategories" and
  50. # "Annotations" do not always match. This is a manual map between the
  51. # two. Defaults to using same name, since most names are fine.
  52. name_map = {
  53. "Faces": "Faces_2",
  54. "Faces_easy": "Faces_3",
  55. "Motorbikes": "Motorbikes_16",
  56. "airplanes": "Airplanes_Side_2",
  57. }
  58. self.annotation_categories = list(map(lambda x: name_map[x] if x in name_map else x, self.categories))
  59. self.index: List[int] = []
  60. self.y = []
  61. for (i, c) in enumerate(self.categories):
  62. n = len(os.listdir(os.path.join(self.root, "101_ObjectCategories", c)))
  63. self.index.extend(range(1, n + 1))
  64. self.y.extend(n * [i])
  65. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  66. """
  67. Args:
  68. index (int): Index
  69. Returns:
  70. tuple: (image, target) where the type of target specified by target_type.
  71. """
  72. import scipy.io
  73. img = Image.open(
  74. os.path.join(
  75. self.root,
  76. "101_ObjectCategories",
  77. self.categories[self.y[index]],
  78. f"image_{self.index[index]:04d}.jpg",
  79. )
  80. )
  81. target: Any = []
  82. for t in self.target_type:
  83. if t == "category":
  84. target.append(self.y[index])
  85. elif t == "annotation":
  86. data = scipy.io.loadmat(
  87. os.path.join(
  88. self.root,
  89. "Annotations",
  90. self.annotation_categories[self.y[index]],
  91. f"annotation_{self.index[index]:04d}.mat",
  92. )
  93. )
  94. target.append(data["obj_contour"])
  95. target = tuple(target) if len(target) > 1 else target[0]
  96. if self.transform is not None:
  97. img = self.transform(img)
  98. if self.target_transform is not None:
  99. target = self.target_transform(target)
  100. return img, target
  101. def _check_integrity(self) -> bool:
  102. # can be more robust and check hash of files
  103. return os.path.exists(os.path.join(self.root, "101_ObjectCategories"))
  104. def __len__(self) -> int:
  105. return len(self.index)
  106. def download(self) -> None:
  107. if self._check_integrity():
  108. return
  109. download_and_extract_archive(
  110. "https://drive.google.com/file/d/137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp",
  111. self.root,
  112. filename="101_ObjectCategories.tar.gz",
  113. md5="b224c7392d521a49829488ab0f1120d9",
  114. )
  115. download_and_extract_archive(
  116. "https://drive.google.com/file/d/175kQy3UsZ0wUEHZjqkUDdNVssr7bgh_m",
  117. self.root,
  118. filename="Annotations.tar",
  119. md5="6f83eeb1f24d99cab4eb377263132c91",
  120. )
  121. def extra_repr(self) -> str:
  122. return "Target type: {target_type}".format(**self.__dict__)
  123. class Caltech256(VisionDataset):
  124. """`Caltech 256 <https://data.caltech.edu/records/20087>`_ Dataset.
  125. Args:
  126. root (str or ``pathlib.Path``): Root directory of dataset where directory
  127. ``caltech256`` exists or will be saved to if download is set to True.
  128. transform (callable, optional): A function/transform that takes in a PIL image
  129. and returns a transformed version. E.g, ``transforms.RandomCrop``
  130. target_transform (callable, optional): A function/transform that takes in the
  131. target and transforms it.
  132. download (bool, optional): If true, downloads the dataset from the internet and
  133. puts it in root directory. If dataset is already downloaded, it is not
  134. downloaded again.
  135. """
  136. def __init__(
  137. self,
  138. root: str,
  139. transform: Optional[Callable] = None,
  140. target_transform: Optional[Callable] = None,
  141. download: bool = False,
  142. ) -> None:
  143. super().__init__(os.path.join(root, "caltech256"), transform=transform, target_transform=target_transform)
  144. os.makedirs(self.root, exist_ok=True)
  145. if download:
  146. self.download()
  147. if not self._check_integrity():
  148. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  149. self.categories = sorted(os.listdir(os.path.join(self.root, "256_ObjectCategories")))
  150. self.index: List[int] = []
  151. self.y = []
  152. for (i, c) in enumerate(self.categories):
  153. n = len(
  154. [
  155. item
  156. for item in os.listdir(os.path.join(self.root, "256_ObjectCategories", c))
  157. if item.endswith(".jpg")
  158. ]
  159. )
  160. self.index.extend(range(1, n + 1))
  161. self.y.extend(n * [i])
  162. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  163. """
  164. Args:
  165. index (int): Index
  166. Returns:
  167. tuple: (image, target) where target is index of the target class.
  168. """
  169. img = Image.open(
  170. os.path.join(
  171. self.root,
  172. "256_ObjectCategories",
  173. self.categories[self.y[index]],
  174. f"{self.y[index] + 1:03d}_{self.index[index]:04d}.jpg",
  175. )
  176. )
  177. target = self.y[index]
  178. if self.transform is not None:
  179. img = self.transform(img)
  180. if self.target_transform is not None:
  181. target = self.target_transform(target)
  182. return img, target
  183. def _check_integrity(self) -> bool:
  184. # can be more robust and check hash of files
  185. return os.path.exists(os.path.join(self.root, "256_ObjectCategories"))
  186. def __len__(self) -> int:
  187. return len(self.index)
  188. def download(self) -> None:
  189. if self._check_integrity():
  190. return
  191. download_and_extract_archive(
  192. "https://drive.google.com/file/d/1r6o0pSROcV1_VwT4oSjA2FBUSCWGuxLK",
  193. self.root,
  194. filename="256_ObjectCategories.tar",
  195. md5="67b4f42ca05d46448c6bb8ecd2220f6d",
  196. )
Tip!

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

Comments

Loading...