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

folder.py 13 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
  1. import os
  2. import os.path
  3. from pathlib import Path
  4. from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
  5. from PIL import Image
  6. from .vision import VisionDataset
  7. def has_file_allowed_extension(filename: str, extensions: Union[str, Tuple[str, ...]]) -> bool:
  8. """Checks if a file is an allowed extension.
  9. Args:
  10. filename (string): path to a file
  11. extensions (tuple of strings): extensions to consider (lowercase)
  12. Returns:
  13. bool: True if the filename ends with one of given extensions
  14. """
  15. return filename.lower().endswith(extensions if isinstance(extensions, str) else tuple(extensions))
  16. def is_image_file(filename: str) -> bool:
  17. """Checks if a file is an allowed image extension.
  18. Args:
  19. filename (string): path to a file
  20. Returns:
  21. bool: True if the filename ends with a known image extension
  22. """
  23. return has_file_allowed_extension(filename, IMG_EXTENSIONS)
  24. def find_classes(directory: Union[str, Path]) -> Tuple[List[str], Dict[str, int]]:
  25. """Finds the class folders in a dataset.
  26. See :class:`DatasetFolder` for details.
  27. """
  28. classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir())
  29. if not classes:
  30. raise FileNotFoundError(f"Couldn't find any class folder in {directory}.")
  31. class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}
  32. return classes, class_to_idx
  33. def make_dataset(
  34. directory: Union[str, Path],
  35. class_to_idx: Optional[Dict[str, int]] = None,
  36. extensions: Optional[Union[str, Tuple[str, ...]]] = None,
  37. is_valid_file: Optional[Callable[[str], bool]] = None,
  38. allow_empty: bool = False,
  39. ) -> List[Tuple[str, int]]:
  40. """Generates a list of samples of a form (path_to_sample, class).
  41. See :class:`DatasetFolder` for details.
  42. Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function
  43. by default.
  44. """
  45. directory = os.path.expanduser(directory)
  46. if class_to_idx is None:
  47. _, class_to_idx = find_classes(directory)
  48. elif not class_to_idx:
  49. raise ValueError("'class_to_index' must have at least one entry to collect any samples.")
  50. both_none = extensions is None and is_valid_file is None
  51. both_something = extensions is not None and is_valid_file is not None
  52. if both_none or both_something:
  53. raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time")
  54. if extensions is not None:
  55. def is_valid_file(x: str) -> bool:
  56. return has_file_allowed_extension(x, extensions) # type: ignore[arg-type]
  57. is_valid_file = cast(Callable[[str], bool], is_valid_file)
  58. instances = []
  59. available_classes = set()
  60. for target_class in sorted(class_to_idx.keys()):
  61. class_index = class_to_idx[target_class]
  62. target_dir = os.path.join(directory, target_class)
  63. if not os.path.isdir(target_dir):
  64. continue
  65. for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):
  66. for fname in sorted(fnames):
  67. path = os.path.join(root, fname)
  68. if is_valid_file(path):
  69. item = path, class_index
  70. instances.append(item)
  71. if target_class not in available_classes:
  72. available_classes.add(target_class)
  73. empty_classes = set(class_to_idx.keys()) - available_classes
  74. if empty_classes and not allow_empty:
  75. msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. "
  76. if extensions is not None:
  77. msg += f"Supported extensions are: {extensions if isinstance(extensions, str) else ', '.join(extensions)}"
  78. raise FileNotFoundError(msg)
  79. return instances
  80. class DatasetFolder(VisionDataset):
  81. """A generic data loader.
  82. This default directory structure can be customized by overriding the
  83. :meth:`find_classes` method.
  84. Args:
  85. root (str or ``pathlib.Path``): Root directory path.
  86. loader (callable): A function to load a sample given its path.
  87. extensions (tuple[string]): A list of allowed extensions.
  88. both extensions and is_valid_file should not be passed.
  89. transform (callable, optional): A function/transform that takes in
  90. a sample and returns a transformed version.
  91. E.g, ``transforms.RandomCrop`` for images.
  92. target_transform (callable, optional): A function/transform that takes
  93. in the target and transforms it.
  94. is_valid_file (callable, optional): A function that takes path of a file
  95. and check if the file is a valid file (used to check of corrupt files)
  96. both extensions and is_valid_file should not be passed.
  97. allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
  98. An error is raised on empty folders if False (default).
  99. Attributes:
  100. classes (list): List of the class names sorted alphabetically.
  101. class_to_idx (dict): Dict with items (class_name, class_index).
  102. samples (list): List of (sample path, class_index) tuples
  103. targets (list): The class_index value for each image in the dataset
  104. """
  105. def __init__(
  106. self,
  107. root: Union[str, Path],
  108. loader: Callable[[str], Any],
  109. extensions: Optional[Tuple[str, ...]] = None,
  110. transform: Optional[Callable] = None,
  111. target_transform: Optional[Callable] = None,
  112. is_valid_file: Optional[Callable[[str], bool]] = None,
  113. allow_empty: bool = False,
  114. ) -> None:
  115. super().__init__(root, transform=transform, target_transform=target_transform)
  116. classes, class_to_idx = self.find_classes(self.root)
  117. samples = self.make_dataset(
  118. self.root,
  119. class_to_idx=class_to_idx,
  120. extensions=extensions,
  121. is_valid_file=is_valid_file,
  122. allow_empty=allow_empty,
  123. )
  124. self.loader = loader
  125. self.extensions = extensions
  126. self.classes = classes
  127. self.class_to_idx = class_to_idx
  128. self.samples = samples
  129. self.targets = [s[1] for s in samples]
  130. @staticmethod
  131. def make_dataset(
  132. directory: Union[str, Path],
  133. class_to_idx: Dict[str, int],
  134. extensions: Optional[Tuple[str, ...]] = None,
  135. is_valid_file: Optional[Callable[[str], bool]] = None,
  136. allow_empty: bool = False,
  137. ) -> List[Tuple[str, int]]:
  138. """Generates a list of samples of a form (path_to_sample, class).
  139. This can be overridden to e.g. read files from a compressed zip file instead of from the disk.
  140. Args:
  141. directory (str): root dataset directory, corresponding to ``self.root``.
  142. class_to_idx (Dict[str, int]): Dictionary mapping class name to class index.
  143. extensions (optional): A list of allowed extensions.
  144. Either extensions or is_valid_file should be passed. Defaults to None.
  145. is_valid_file (optional): A function that takes path of a file
  146. and checks if the file is a valid file
  147. (used to check of corrupt files) both extensions and
  148. is_valid_file should not be passed. Defaults to None.
  149. allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
  150. An error is raised on empty folders if False (default).
  151. Raises:
  152. ValueError: In case ``class_to_idx`` is empty.
  153. ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.
  154. FileNotFoundError: In case no valid file was found for any class.
  155. Returns:
  156. List[Tuple[str, int]]: samples of a form (path_to_sample, class)
  157. """
  158. if class_to_idx is None:
  159. # prevent potential bug since make_dataset() would use the class_to_idx logic of the
  160. # find_classes() function, instead of using that of the find_classes() method, which
  161. # is potentially overridden and thus could have a different logic.
  162. raise ValueError("The class_to_idx parameter cannot be None.")
  163. return make_dataset(
  164. directory, class_to_idx, extensions=extensions, is_valid_file=is_valid_file, allow_empty=allow_empty
  165. )
  166. def find_classes(self, directory: Union[str, Path]) -> Tuple[List[str], Dict[str, int]]:
  167. """Find the class folders in a dataset structured as follows::
  168. directory/
  169. ├── class_x
  170. │ ├── xxx.ext
  171. │ ├── xxy.ext
  172. │ └── ...
  173. │ └── xxz.ext
  174. └── class_y
  175. ├── 123.ext
  176. ├── nsdf3.ext
  177. └── ...
  178. └── asd932_.ext
  179. This method can be overridden to only consider
  180. a subset of classes, or to adapt to a different dataset directory structure.
  181. Args:
  182. directory(str): Root directory path, corresponding to ``self.root``
  183. Raises:
  184. FileNotFoundError: If ``dir`` has no class folders.
  185. Returns:
  186. (Tuple[List[str], Dict[str, int]]): List of all classes and dictionary mapping each class to an index.
  187. """
  188. return find_classes(directory)
  189. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  190. """
  191. Args:
  192. index (int): Index
  193. Returns:
  194. tuple: (sample, target) where target is class_index of the target class.
  195. """
  196. path, target = self.samples[index]
  197. sample = self.loader(path)
  198. if self.transform is not None:
  199. sample = self.transform(sample)
  200. if self.target_transform is not None:
  201. target = self.target_transform(target)
  202. return sample, target
  203. def __len__(self) -> int:
  204. return len(self.samples)
  205. IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp")
  206. def pil_loader(path: Union[str, Path]) -> Image.Image:
  207. # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
  208. with open(path, "rb") as f:
  209. img = Image.open(f)
  210. return img.convert("RGB")
  211. # TODO: specify the return type
  212. def accimage_loader(path: Union[str, Path]) -> Any:
  213. import accimage
  214. try:
  215. return accimage.Image(path)
  216. except OSError:
  217. # Potentially a decoding problem, fall back to PIL.Image
  218. return pil_loader(path)
  219. def default_loader(path: Union[str, Path]) -> Any:
  220. from torchvision import get_image_backend
  221. if get_image_backend() == "accimage":
  222. return accimage_loader(path)
  223. else:
  224. return pil_loader(path)
  225. class ImageFolder(DatasetFolder):
  226. """A generic data loader where the images are arranged in this way by default: ::
  227. root/dog/xxx.png
  228. root/dog/xxy.png
  229. root/dog/[...]/xxz.png
  230. root/cat/123.png
  231. root/cat/nsdf3.png
  232. root/cat/[...]/asd932_.png
  233. This class inherits from :class:`~torchvision.datasets.DatasetFolder` so
  234. the same methods can be overridden to customize the dataset.
  235. Args:
  236. root (str or ``pathlib.Path``): Root directory path.
  237. transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader,
  238. and returns a transformed version. E.g, ``transforms.RandomCrop``
  239. target_transform (callable, optional): A function/transform that takes in the
  240. target and transforms it.
  241. loader (callable, optional): A function to load an image given its path.
  242. is_valid_file (callable, optional): A function that takes path of an Image file
  243. and check if the file is a valid file (used to check of corrupt files)
  244. allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
  245. An error is raised on empty folders if False (default).
  246. Attributes:
  247. classes (list): List of the class names sorted alphabetically.
  248. class_to_idx (dict): Dict with items (class_name, class_index).
  249. imgs (list): List of (image path, class_index) tuples
  250. """
  251. def __init__(
  252. self,
  253. root: Union[str, Path],
  254. transform: Optional[Callable] = None,
  255. target_transform: Optional[Callable] = None,
  256. loader: Callable[[str], Any] = default_loader,
  257. is_valid_file: Optional[Callable[[str], bool]] = None,
  258. allow_empty: bool = False,
  259. ):
  260. super().__init__(
  261. root,
  262. loader,
  263. IMG_EXTENSIONS if is_valid_file is None else None,
  264. transform=transform,
  265. target_transform=target_transform,
  266. is_valid_file=is_valid_file,
  267. allow_empty=allow_empty,
  268. )
  269. self.imgs = self.samples
Tip!

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

Comments

Loading...