imagenette.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. from pathlib import Path
  2. from typing import Any, Callable, Optional, Tuple
  3. from PIL import Image
  4. from .folder import find_classes, make_dataset
  5. from .utils import download_and_extract_archive, verify_str_arg
  6. from .vision import VisionDataset
  7. class Imagenette(VisionDataset):
  8. """`Imagenette <https://github.com/fastai/imagenette#imagenette-1>`_ image classification dataset.
  9. Args:
  10. root (string): Root directory of the Imagenette dataset.
  11. split (string, optional): The dataset split. Supports ``"train"`` (default), and ``"val"``.
  12. size (string, optional): The image size. Supports ``"full"`` (default), ``"320px"``, and ``"160px"``.
  13. download (bool, optional): If ``True``, downloads the dataset components and places them in ``root``. Already
  14. downloaded archives are not downloaded again.
  15. transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed
  16. version, e.g. ``transforms.RandomCrop``.
  17. target_transform (callable, optional): A function/transform that takes in the target and transforms it.
  18. Attributes:
  19. classes (list): List of the class name tuples.
  20. class_to_idx (dict): Dict with items (class name, class index).
  21. wnids (list): List of the WordNet IDs.
  22. wnid_to_idx (dict): Dict with items (WordNet ID, class index).
  23. """
  24. _ARCHIVES = {
  25. "full": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2.tgz", "fe2fc210e6bb7c5664d602c3cd71e612"),
  26. "320px": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-320.tgz", "3df6f0d01a2c9592104656642f5e78a3"),
  27. "160px": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-160.tgz", "e793b78cc4c9e9a4ccc0c1155377a412"),
  28. }
  29. _WNID_TO_CLASS = {
  30. "n01440764": ("tench", "Tinca tinca"),
  31. "n02102040": ("English springer", "English springer spaniel"),
  32. "n02979186": ("cassette player",),
  33. "n03000684": ("chain saw", "chainsaw"),
  34. "n03028079": ("church", "church building"),
  35. "n03394916": ("French horn", "horn"),
  36. "n03417042": ("garbage truck", "dustcart"),
  37. "n03425413": ("gas pump", "gasoline pump", "petrol pump", "island dispenser"),
  38. "n03445777": ("golf ball",),
  39. "n03888257": ("parachute", "chute"),
  40. }
  41. def __init__(
  42. self,
  43. root: str,
  44. split: str = "train",
  45. size: str = "full",
  46. download=False,
  47. transform: Optional[Callable] = None,
  48. target_transform: Optional[Callable] = None,
  49. ) -> None:
  50. super().__init__(root, transform=transform, target_transform=target_transform)
  51. self._split = verify_str_arg(split, "split", ["train", "val"])
  52. self._size = verify_str_arg(size, "size", ["full", "320px", "160px"])
  53. self._url, self._md5 = self._ARCHIVES[self._size]
  54. self._size_root = Path(self.root) / Path(self._url).stem
  55. self._image_root = str(self._size_root / self._split)
  56. if download:
  57. self._download()
  58. elif not self._check_exists():
  59. raise RuntimeError("Dataset not found. You can use download=True to download it.")
  60. self.wnids, self.wnid_to_idx = find_classes(self._image_root)
  61. self.classes = [self._WNID_TO_CLASS[wnid] for wnid in self.wnids]
  62. self.class_to_idx = {
  63. class_name: idx for wnid, idx in self.wnid_to_idx.items() for class_name in self._WNID_TO_CLASS[wnid]
  64. }
  65. self._samples = make_dataset(self._image_root, self.wnid_to_idx, extensions=".jpeg")
  66. def _check_exists(self) -> bool:
  67. return self._size_root.exists()
  68. def _download(self):
  69. if self._check_exists():
  70. raise RuntimeError(
  71. f"The directory {self._size_root} already exists. "
  72. f"If you want to re-download or re-extract the images, delete the directory."
  73. )
  74. download_and_extract_archive(self._url, self.root, md5=self._md5)
  75. def __getitem__(self, idx: int) -> Tuple[Any, Any]:
  76. path, label = self._samples[idx]
  77. image = Image.open(path).convert("RGB")
  78. if self.transform is not None:
  79. image = self.transform(image)
  80. if self.target_transform is not None:
  81. label = self.target_transform(label)
  82. return image, label
  83. def __len__(self) -> int:
  84. return len(self._samples)