folder.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import os
  2. import os.path
  3. from typing import Any, Callable, cast, Dict, List, Optional, Tuple
  4. from typing import 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: str) -> 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: str,
  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. ) -> List[Tuple[str, int]]:
  39. """Generates a list of samples of a form (path_to_sample, class).
  40. See :class:`DatasetFolder` for details.
  41. Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function
  42. by default.
  43. """
  44. directory = os.path.expanduser(directory)
  45. if class_to_idx is None:
  46. _, class_to_idx = find_classes(directory)
  47. elif not class_to_idx:
  48. raise ValueError("'class_to_index' must have at least one entry to collect any samples.")
  49. both_none = extensions is None and is_valid_file is None
  50. both_something = extensions is not None and is_valid_file is not None
  51. if both_none or both_something:
  52. raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time")
  53. if extensions is not None:
  54. def is_valid_file(x: str) -> bool:
  55. return has_file_allowed_extension(x, extensions) # type: ignore[arg-type]
  56. is_valid_file = cast(Callable[[str], bool], is_valid_file)
  57. instances = []
  58. available_classes = set()
  59. for target_class in sorted(class_to_idx.keys()):
  60. class_index = class_to_idx[target_class]
  61. target_dir = os.path.join(directory, target_class)
  62. if not os.path.isdir(target_dir):
  63. continue
  64. for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):
  65. for fname in sorted(fnames):
  66. path = os.path.join(root, fname)
  67. if is_valid_file(path):
  68. item = path, class_index
  69. instances.append(item)
  70. if target_class not in available_classes:
  71. available_classes.add(target_class)
  72. empty_classes = set(class_to_idx.keys()) - available_classes
  73. if empty_classes:
  74. msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. "
  75. if extensions is not None:
  76. msg += f"Supported extensions are: {extensions if isinstance(extensions, str) else ', '.join(extensions)}"
  77. raise FileNotFoundError(msg)
  78. return instances
  79. class DatasetFolder(VisionDataset):
  80. """A generic data loader.
  81. This default directory structure can be customized by overriding the
  82. :meth:`find_classes` method.
  83. Args:
  84. root (string): Root directory path.
  85. loader (callable): A function to load a sample given its path.
  86. extensions (tuple[string]): A list of allowed extensions.
  87. both extensions and is_valid_file should not be passed.
  88. transform (callable, optional): A function/transform that takes in
  89. a sample and returns a transformed version.
  90. E.g, ``transforms.RandomCrop`` for images.
  91. target_transform (callable, optional): A function/transform that takes
  92. in the target and transforms it.
  93. is_valid_file (callable, optional): A function that takes path of a file
  94. and check if the file is a valid file (used to check of corrupt files)
  95. both extensions and is_valid_file should not be passed.
  96. Attributes:
  97. classes (list): List of the class names sorted alphabetically.
  98. class_to_idx (dict): Dict with items (class_name, class_index).
  99. samples (list): List of (sample path, class_index) tuples
  100. targets (list): The class_index value for each image in the dataset
  101. """
  102. def __init__(
  103. self,
  104. root: str,
  105. loader: Callable[[str], Any],
  106. extensions: Optional[Tuple[str, ...]] = None,
  107. transform: Optional[Callable] = None,
  108. target_transform: Optional[Callable] = None,
  109. is_valid_file: Optional[Callable[[str], bool]] = None,
  110. ) -> None:
  111. super().__init__(root, transform=transform, target_transform=target_transform)
  112. classes, class_to_idx = self.find_classes(self.root)
  113. samples = self.make_dataset(self.root, class_to_idx, extensions, is_valid_file)
  114. self.loader = loader
  115. self.extensions = extensions
  116. self.classes = classes
  117. self.class_to_idx = class_to_idx
  118. self.samples = samples
  119. self.targets = [s[1] for s in samples]
  120. @staticmethod
  121. def make_dataset(
  122. directory: str,
  123. class_to_idx: Dict[str, int],
  124. extensions: Optional[Tuple[str, ...]] = None,
  125. is_valid_file: Optional[Callable[[str], bool]] = None,
  126. ) -> List[Tuple[str, int]]:
  127. """Generates a list of samples of a form (path_to_sample, class).
  128. This can be overridden to e.g. read files from a compressed zip file instead of from the disk.
  129. Args:
  130. directory (str): root dataset directory, corresponding to ``self.root``.
  131. class_to_idx (Dict[str, int]): Dictionary mapping class name to class index.
  132. extensions (optional): A list of allowed extensions.
  133. Either extensions or is_valid_file should be passed. Defaults to None.
  134. is_valid_file (optional): A function that takes path of a file
  135. and checks if the file is a valid file
  136. (used to check of corrupt files) both extensions and
  137. is_valid_file should not be passed. Defaults to None.
  138. Raises:
  139. ValueError: In case ``class_to_idx`` is empty.
  140. ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.
  141. FileNotFoundError: In case no valid file was found for any class.
  142. Returns:
  143. List[Tuple[str, int]]: samples of a form (path_to_sample, class)
  144. """
  145. if class_to_idx is None:
  146. # prevent potential bug since make_dataset() would use the class_to_idx logic of the
  147. # find_classes() function, instead of using that of the find_classes() method, which
  148. # is potentially overridden and thus could have a different logic.
  149. raise ValueError("The class_to_idx parameter cannot be None.")
  150. return make_dataset(directory, class_to_idx, extensions=extensions, is_valid_file=is_valid_file)
  151. def find_classes(self, directory: str) -> Tuple[List[str], Dict[str, int]]:
  152. """Find the class folders in a dataset structured as follows::
  153. directory/
  154. ├── class_x
  155. │ ├── xxx.ext
  156. │ ├── xxy.ext
  157. │ └── ...
  158. │ └── xxz.ext
  159. └── class_y
  160. ├── 123.ext
  161. ├── nsdf3.ext
  162. └── ...
  163. └── asd932_.ext
  164. This method can be overridden to only consider
  165. a subset of classes, or to adapt to a different dataset directory structure.
  166. Args:
  167. directory(str): Root directory path, corresponding to ``self.root``
  168. Raises:
  169. FileNotFoundError: If ``dir`` has no class folders.
  170. Returns:
  171. (Tuple[List[str], Dict[str, int]]): List of all classes and dictionary mapping each class to an index.
  172. """
  173. return find_classes(directory)
  174. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  175. """
  176. Args:
  177. index (int): Index
  178. Returns:
  179. tuple: (sample, target) where target is class_index of the target class.
  180. """
  181. path, target = self.samples[index]
  182. sample = self.loader(path)
  183. if self.transform is not None:
  184. sample = self.transform(sample)
  185. if self.target_transform is not None:
  186. target = self.target_transform(target)
  187. return sample, target
  188. def __len__(self) -> int:
  189. return len(self.samples)
  190. IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp")
  191. def pil_loader(path: str) -> Image.Image:
  192. # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
  193. with open(path, "rb") as f:
  194. img = Image.open(f)
  195. return img.convert("RGB")
  196. # TODO: specify the return type
  197. def accimage_loader(path: str) -> Any:
  198. import accimage
  199. try:
  200. return accimage.Image(path)
  201. except OSError:
  202. # Potentially a decoding problem, fall back to PIL.Image
  203. return pil_loader(path)
  204. def default_loader(path: str) -> Any:
  205. from torchvision import get_image_backend
  206. if get_image_backend() == "accimage":
  207. return accimage_loader(path)
  208. else:
  209. return pil_loader(path)
  210. class ImageFolder(DatasetFolder):
  211. """A generic data loader where the images are arranged in this way by default: ::
  212. root/dog/xxx.png
  213. root/dog/xxy.png
  214. root/dog/[...]/xxz.png
  215. root/cat/123.png
  216. root/cat/nsdf3.png
  217. root/cat/[...]/asd932_.png
  218. This class inherits from :class:`~torchvision.datasets.DatasetFolder` so
  219. the same methods can be overridden to customize the dataset.
  220. Args:
  221. root (string): Root directory path.
  222. transform (callable, optional): A function/transform that takes in an PIL image
  223. and returns a transformed version. E.g, ``transforms.RandomCrop``
  224. target_transform (callable, optional): A function/transform that takes in the
  225. target and transforms it.
  226. loader (callable, optional): A function to load an image given its path.
  227. is_valid_file (callable, optional): A function that takes path of an Image file
  228. and check if the file is a valid file (used to check of corrupt files)
  229. Attributes:
  230. classes (list): List of the class names sorted alphabetically.
  231. class_to_idx (dict): Dict with items (class_name, class_index).
  232. imgs (list): List of (image path, class_index) tuples
  233. """
  234. def __init__(
  235. self,
  236. root: str,
  237. transform: Optional[Callable] = None,
  238. target_transform: Optional[Callable] = None,
  239. loader: Callable[[str], Any] = default_loader,
  240. is_valid_file: Optional[Callable[[str], bool]] = None,
  241. ):
  242. super().__init__(
  243. root,
  244. loader,
  245. IMG_EXTENSIONS if is_valid_file is None else None,
  246. transform=transform,
  247. target_transform=target_transform,
  248. is_valid_file=is_valid_file,
  249. )
  250. self.imgs = self.samples