imagenet.py 7.9 KB

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