caltech.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import os
  2. import os.path
  3. from typing import Any, Callable, List, Optional, Tuple, Union
  4. from PIL import Image
  5. from .utils import download_and_extract_archive, verify_str_arg
  6. from .vision import VisionDataset
  7. class Caltech101(VisionDataset):
  8. """`Caltech 101 <https://data.caltech.edu/records/20086>`_ Dataset.
  9. .. warning::
  10. This class needs `scipy <https://docs.scipy.org/doc/>`_ to load target files from `.mat` format.
  11. Args:
  12. root (string): Root directory of dataset where directory
  13. ``caltech101`` exists or will be saved to if download is set to True.
  14. target_type (string or list, optional): Type of target to use, ``category`` or
  15. ``annotation``. Can also be a list to output a tuple with all specified
  16. target types. ``category`` represents the target class, and
  17. ``annotation`` is a list of points from a hand-generated outline.
  18. Defaults to ``category``.
  19. transform (callable, optional): A function/transform that takes in an PIL image
  20. and returns a transformed version. E.g, ``transforms.RandomCrop``
  21. target_transform (callable, optional): A function/transform that takes in the
  22. target and transforms it.
  23. download (bool, optional): If true, downloads the dataset from the internet and
  24. puts it in root directory. If dataset is already downloaded, it is not
  25. downloaded again.
  26. """
  27. def __init__(
  28. self,
  29. root: str,
  30. target_type: Union[List[str], str] = "category",
  31. transform: Optional[Callable] = None,
  32. target_transform: Optional[Callable] = None,
  33. download: bool = False,
  34. ) -> None:
  35. super().__init__(os.path.join(root, "caltech101"), transform=transform, target_transform=target_transform)
  36. os.makedirs(self.root, exist_ok=True)
  37. if isinstance(target_type, str):
  38. target_type = [target_type]
  39. self.target_type = [verify_str_arg(t, "target_type", ("category", "annotation")) for t in target_type]
  40. if download:
  41. self.download()
  42. if not self._check_integrity():
  43. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  44. self.categories = sorted(os.listdir(os.path.join(self.root, "101_ObjectCategories")))
  45. self.categories.remove("BACKGROUND_Google") # this is not a real class
  46. # For some reason, the category names in "101_ObjectCategories" and
  47. # "Annotations" do not always match. This is a manual map between the
  48. # two. Defaults to using same name, since most names are fine.
  49. name_map = {
  50. "Faces": "Faces_2",
  51. "Faces_easy": "Faces_3",
  52. "Motorbikes": "Motorbikes_16",
  53. "airplanes": "Airplanes_Side_2",
  54. }
  55. self.annotation_categories = list(map(lambda x: name_map[x] if x in name_map else x, self.categories))
  56. self.index: List[int] = []
  57. self.y = []
  58. for (i, c) in enumerate(self.categories):
  59. n = len(os.listdir(os.path.join(self.root, "101_ObjectCategories", c)))
  60. self.index.extend(range(1, n + 1))
  61. self.y.extend(n * [i])
  62. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  63. """
  64. Args:
  65. index (int): Index
  66. Returns:
  67. tuple: (image, target) where the type of target specified by target_type.
  68. """
  69. import scipy.io
  70. img = Image.open(
  71. os.path.join(
  72. self.root,
  73. "101_ObjectCategories",
  74. self.categories[self.y[index]],
  75. f"image_{self.index[index]:04d}.jpg",
  76. )
  77. )
  78. target: Any = []
  79. for t in self.target_type:
  80. if t == "category":
  81. target.append(self.y[index])
  82. elif t == "annotation":
  83. data = scipy.io.loadmat(
  84. os.path.join(
  85. self.root,
  86. "Annotations",
  87. self.annotation_categories[self.y[index]],
  88. f"annotation_{self.index[index]:04d}.mat",
  89. )
  90. )
  91. target.append(data["obj_contour"])
  92. target = tuple(target) if len(target) > 1 else target[0]
  93. if self.transform is not None:
  94. img = self.transform(img)
  95. if self.target_transform is not None:
  96. target = self.target_transform(target)
  97. return img, target
  98. def _check_integrity(self) -> bool:
  99. # can be more robust and check hash of files
  100. return os.path.exists(os.path.join(self.root, "101_ObjectCategories"))
  101. def __len__(self) -> int:
  102. return len(self.index)
  103. def download(self) -> None:
  104. if self._check_integrity():
  105. print("Files already downloaded and verified")
  106. return
  107. download_and_extract_archive(
  108. "https://drive.google.com/file/d/137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp",
  109. self.root,
  110. filename="101_ObjectCategories.tar.gz",
  111. md5="b224c7392d521a49829488ab0f1120d9",
  112. )
  113. download_and_extract_archive(
  114. "https://drive.google.com/file/d/175kQy3UsZ0wUEHZjqkUDdNVssr7bgh_m",
  115. self.root,
  116. filename="Annotations.tar",
  117. md5="6f83eeb1f24d99cab4eb377263132c91",
  118. )
  119. def extra_repr(self) -> str:
  120. return "Target type: {target_type}".format(**self.__dict__)
  121. class Caltech256(VisionDataset):
  122. """`Caltech 256 <https://data.caltech.edu/records/20087>`_ Dataset.
  123. Args:
  124. root (string): Root directory of dataset where directory
  125. ``caltech256`` exists or will be saved to if download is set to True.
  126. transform (callable, optional): A function/transform that takes in an PIL image
  127. and returns a transformed version. E.g, ``transforms.RandomCrop``
  128. target_transform (callable, optional): A function/transform that takes in the
  129. target and transforms it.
  130. download (bool, optional): If true, downloads the dataset from the internet and
  131. puts it in root directory. If dataset is already downloaded, it is not
  132. downloaded again.
  133. """
  134. def __init__(
  135. self,
  136. root: str,
  137. transform: Optional[Callable] = None,
  138. target_transform: Optional[Callable] = None,
  139. download: bool = False,
  140. ) -> None:
  141. super().__init__(os.path.join(root, "caltech256"), transform=transform, target_transform=target_transform)
  142. os.makedirs(self.root, exist_ok=True)
  143. if download:
  144. self.download()
  145. if not self._check_integrity():
  146. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  147. self.categories = sorted(os.listdir(os.path.join(self.root, "256_ObjectCategories")))
  148. self.index: List[int] = []
  149. self.y = []
  150. for (i, c) in enumerate(self.categories):
  151. n = len(
  152. [
  153. item
  154. for item in os.listdir(os.path.join(self.root, "256_ObjectCategories", c))
  155. if item.endswith(".jpg")
  156. ]
  157. )
  158. self.index.extend(range(1, n + 1))
  159. self.y.extend(n * [i])
  160. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  161. """
  162. Args:
  163. index (int): Index
  164. Returns:
  165. tuple: (image, target) where target is index of the target class.
  166. """
  167. img = Image.open(
  168. os.path.join(
  169. self.root,
  170. "256_ObjectCategories",
  171. self.categories[self.y[index]],
  172. f"{self.y[index] + 1:03d}_{self.index[index]:04d}.jpg",
  173. )
  174. )
  175. target = self.y[index]
  176. if self.transform is not None:
  177. img = self.transform(img)
  178. if self.target_transform is not None:
  179. target = self.target_transform(target)
  180. return img, target
  181. def _check_integrity(self) -> bool:
  182. # can be more robust and check hash of files
  183. return os.path.exists(os.path.join(self.root, "256_ObjectCategories"))
  184. def __len__(self) -> int:
  185. return len(self.index)
  186. def download(self) -> None:
  187. if self._check_integrity():
  188. print("Files already downloaded and verified")
  189. return
  190. download_and_extract_archive(
  191. "https://drive.google.com/file/d/1r6o0pSROcV1_VwT4oSjA2FBUSCWGuxLK",
  192. self.root,
  193. filename="256_ObjectCategories.tar",
  194. md5="67b4f42ca05d46448c6bb8ecd2220f6d",
  195. )