imagenet.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. import os
  2. import shutil
  3. import tempfile
  4. from collections.abc import Iterator
  5. from contextlib import contextmanager
  6. from pathlib import Path
  7. from typing import Any, Optional, Union
  8. import torch
  9. from .folder import ImageFolder
  10. from .utils import check_integrity, extract_archive, verify_str_arg
  11. ARCHIVE_META = {
  12. "train": ("ILSVRC2012_img_train.tar", "1d675b47d978889d74fa0da5fadfb00e"),
  13. "val": ("ILSVRC2012_img_val.tar", "29b22e2961454d5413ddabcf34fc5622"),
  14. "devkit": ("ILSVRC2012_devkit_t12.tar.gz", "fa75699e90414af021442c21a62c3abf"),
  15. }
  16. META_FILE = "meta.bin"
  17. class ImageNet(ImageFolder):
  18. """`ImageNet <http://image-net.org/>`_ 2012 Classification Dataset.
  19. .. note::
  20. Before using this class, it is required to download ImageNet 2012 dataset from
  21. `here <https://image-net.org/challenges/LSVRC/2012/2012-downloads.php>`_ and
  22. place the files ``ILSVRC2012_devkit_t12.tar.gz`` and ``ILSVRC2012_img_train.tar``
  23. or ``ILSVRC2012_img_val.tar`` based on ``split`` in the root directory.
  24. Args:
  25. root (str or ``pathlib.Path``): Root directory of the ImageNet Dataset.
  26. split (string, optional): The dataset split, supports ``train``, or ``val``.
  27. transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader,
  28. and returns a transformed version. E.g, ``transforms.RandomCrop``
  29. target_transform (callable, optional): A function/transform that takes in the
  30. target and transforms it.
  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. Attributes:
  35. classes (list): List of the class name tuples.
  36. class_to_idx (dict): Dict with items (class_name, class_index).
  37. wnids (list): List of the WordNet IDs.
  38. wnid_to_idx (dict): Dict with items (wordnet_id, class_index).
  39. imgs (list): List of (image path, class_index) tuples
  40. targets (list): The class_index value for each image in the dataset
  41. """
  42. def __init__(self, root: Union[str, Path], split: str = "train", **kwargs: Any) -> None:
  43. root = self.root = os.path.expanduser(root)
  44. self.split = verify_str_arg(split, "split", ("train", "val"))
  45. self.parse_archives()
  46. wnid_to_classes = load_meta_file(self.root)[0]
  47. super().__init__(self.split_folder, **kwargs)
  48. self.root = root
  49. self.wnids = self.classes
  50. self.wnid_to_idx = self.class_to_idx
  51. self.classes = [wnid_to_classes[wnid] for wnid in self.wnids]
  52. self.class_to_idx = {cls: idx for idx, clss in enumerate(self.classes) for cls in clss}
  53. def parse_archives(self) -> None:
  54. if not check_integrity(os.path.join(self.root, META_FILE)):
  55. parse_devkit_archive(self.root)
  56. if not os.path.isdir(self.split_folder):
  57. if self.split == "train":
  58. parse_train_archive(self.root)
  59. elif self.split == "val":
  60. parse_val_archive(self.root)
  61. @property
  62. def split_folder(self) -> str:
  63. return os.path.join(self.root, self.split)
  64. def extra_repr(self) -> str:
  65. return "Split: {split}".format(**self.__dict__)
  66. def load_meta_file(root: Union[str, Path], file: Optional[str] = None) -> tuple[dict[str, str], list[str]]:
  67. if file is None:
  68. file = META_FILE
  69. file = os.path.join(root, file)
  70. if check_integrity(file):
  71. return torch.load(file, weights_only=True)
  72. else:
  73. msg = (
  74. "The meta file {} is not present in the root directory or is corrupted. "
  75. "This file is automatically created by the ImageNet dataset."
  76. )
  77. raise RuntimeError(msg.format(file, root))
  78. def _verify_archive(root: Union[str, Path], file: str, md5: str) -> None:
  79. if not check_integrity(os.path.join(root, file), md5):
  80. msg = (
  81. "The archive {} is not present in the root directory or is corrupted. "
  82. "You need to download it externally and place it in {}."
  83. )
  84. raise RuntimeError(msg.format(file, root))
  85. def parse_devkit_archive(root: Union[str, Path], file: Optional[str] = None) -> None:
  86. """Parse the devkit archive of the ImageNet2012 classification dataset and save
  87. the meta information in a binary file.
  88. Args:
  89. root (str or ``pathlib.Path``): Root directory containing the devkit archive
  90. file (str, optional): Name of devkit archive. Defaults to
  91. 'ILSVRC2012_devkit_t12.tar.gz'
  92. """
  93. import scipy.io as sio
  94. def parse_meta_mat(devkit_root: str) -> tuple[dict[int, str], dict[str, tuple[str, ...]]]:
  95. metafile = os.path.join(devkit_root, "data", "meta.mat")
  96. meta = sio.loadmat(metafile, squeeze_me=True)["synsets"]
  97. nums_children = list(zip(*meta))[4]
  98. meta = [meta[idx] for idx, num_children in enumerate(nums_children) if num_children == 0]
  99. idcs, wnids, classes = list(zip(*meta))[:3]
  100. classes = [tuple(clss.split(", ")) for clss in classes]
  101. idx_to_wnid = {idx: wnid for idx, wnid in zip(idcs, wnids)}
  102. wnid_to_classes = {wnid: clss for wnid, clss in zip(wnids, classes)}
  103. return idx_to_wnid, wnid_to_classes
  104. def parse_val_groundtruth_txt(devkit_root: str) -> list[int]:
  105. file = os.path.join(devkit_root, "data", "ILSVRC2012_validation_ground_truth.txt")
  106. with open(file) as txtfh:
  107. val_idcs = txtfh.readlines()
  108. return [int(val_idx) for val_idx in val_idcs]
  109. @contextmanager
  110. def get_tmp_dir() -> Iterator[str]:
  111. tmp_dir = tempfile.mkdtemp()
  112. try:
  113. yield tmp_dir
  114. finally:
  115. shutil.rmtree(tmp_dir)
  116. archive_meta = ARCHIVE_META["devkit"]
  117. if file is None:
  118. file = archive_meta[0]
  119. md5 = archive_meta[1]
  120. _verify_archive(root, file, md5)
  121. with get_tmp_dir() as tmp_dir:
  122. extract_archive(os.path.join(root, file), tmp_dir)
  123. devkit_root = os.path.join(tmp_dir, "ILSVRC2012_devkit_t12")
  124. idx_to_wnid, wnid_to_classes = parse_meta_mat(devkit_root)
  125. val_idcs = parse_val_groundtruth_txt(devkit_root)
  126. val_wnids = [idx_to_wnid[idx] for idx in val_idcs]
  127. torch.save((wnid_to_classes, val_wnids), os.path.join(root, META_FILE))
  128. def parse_train_archive(root: Union[str, Path], file: Optional[str] = None, folder: str = "train") -> None:
  129. """Parse the train images archive of the ImageNet2012 classification dataset and
  130. prepare it for usage with the ImageNet dataset.
  131. Args:
  132. root (str or ``pathlib.Path``): Root directory containing the train images archive
  133. file (str, optional): Name of train images archive. Defaults to
  134. 'ILSVRC2012_img_train.tar'
  135. folder (str, optional): Optional name for train images folder. Defaults to
  136. 'train'
  137. """
  138. archive_meta = ARCHIVE_META["train"]
  139. if file is None:
  140. file = archive_meta[0]
  141. md5 = archive_meta[1]
  142. _verify_archive(root, file, md5)
  143. train_root = os.path.join(root, folder)
  144. extract_archive(os.path.join(root, file), train_root)
  145. archives = [os.path.join(train_root, archive) for archive in os.listdir(train_root)]
  146. for archive in archives:
  147. extract_archive(archive, os.path.splitext(archive)[0], remove_finished=True)
  148. def parse_val_archive(
  149. root: Union[str, Path], file: Optional[str] = None, wnids: Optional[list[str]] = None, folder: str = "val"
  150. ) -> None:
  151. """Parse the validation images archive of the ImageNet2012 classification dataset
  152. and prepare it for usage with the ImageNet dataset.
  153. Args:
  154. root (str or ``pathlib.Path``): Root directory containing the validation images archive
  155. file (str, optional): Name of validation images archive. Defaults to
  156. 'ILSVRC2012_img_val.tar'
  157. wnids (list, optional): List of WordNet IDs of the validation images. If None
  158. is given, the IDs are loaded from the meta file in the root directory
  159. folder (str, optional): Optional name for validation images folder. Defaults to
  160. 'val'
  161. """
  162. archive_meta = ARCHIVE_META["val"]
  163. if file is None:
  164. file = archive_meta[0]
  165. md5 = archive_meta[1]
  166. if wnids is None:
  167. wnids = load_meta_file(root)[1]
  168. _verify_archive(root, file, md5)
  169. val_root = os.path.join(root, folder)
  170. extract_archive(os.path.join(root, file), val_root)
  171. images = sorted(os.path.join(val_root, image) for image in os.listdir(val_root))
  172. for wnid in set(wnids):
  173. os.mkdir(os.path.join(val_root, wnid))
  174. for wnid, img_file in zip(wnids, images):
  175. shutil.move(img_file, os.path.join(val_root, wnid, os.path.basename(img_file)))