Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

places365.py 7.3 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
  1. import os
  2. from os import path
  3. from pathlib import Path
  4. from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
  5. from urllib.parse import urljoin
  6. from .folder import default_loader
  7. from .utils import check_integrity, download_and_extract_archive, verify_str_arg
  8. from .vision import VisionDataset
  9. class Places365(VisionDataset):
  10. r"""`Places365 <http://places2.csail.mit.edu/index.html>`_ classification dataset.
  11. Args:
  12. root (str or ``pathlib.Path``): Root directory of the Places365 dataset.
  13. split (string, optional): The dataset split. Can be one of ``train-standard`` (default), ``train-challenge``,
  14. ``val``, ``test``.
  15. small (bool, optional): If ``True``, uses the small images, i.e. resized to 256 x 256 pixels, instead of the
  16. high resolution ones.
  17. download (bool, optional): If ``True``, downloads the dataset components and places them in ``root``. Already
  18. downloaded archives are not downloaded again.
  19. transform (callable, optional): A function/transform that takes in a 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. loader (callable, optional): A function to load an image given its path.
  24. Attributes:
  25. classes (list): List of the class names.
  26. class_to_idx (dict): Dict with items (class_name, class_index).
  27. imgs (list): List of (image path, class_index) tuples
  28. targets (list): The class_index value for each image in the dataset
  29. Raises:
  30. RuntimeError: If ``download is False`` and the meta files, i.e. the devkit, are not present or corrupted.
  31. RuntimeError: If ``download is True`` and the image archive is already extracted.
  32. """
  33. _SPLITS = ("train-standard", "train-challenge", "val", "test")
  34. _BASE_URL = "http://data.csail.mit.edu/places/places365/"
  35. # {variant: (archive, md5)}
  36. _DEVKIT_META = {
  37. "standard": ("filelist_places365-standard.tar", "35a0585fee1fa656440f3ab298f8479c"),
  38. "challenge": ("filelist_places365-challenge.tar", "70a8307e459c3de41690a7c76c931734"),
  39. }
  40. # (file, md5)
  41. _CATEGORIES_META = ("categories_places365.txt", "06c963b85866bd0649f97cb43dd16673")
  42. # {split: (file, md5)}
  43. _FILE_LIST_META = {
  44. "train-standard": ("places365_train_standard.txt", "30f37515461640559006b8329efbed1a"),
  45. "train-challenge": ("places365_train_challenge.txt", "b2931dc997b8c33c27e7329c073a6b57"),
  46. "val": ("places365_val.txt", "e9f2fd57bfd9d07630173f4e8708e4b1"),
  47. "test": ("places365_test.txt", "2fce8233fe493576d724142e45d93653"),
  48. }
  49. # {(split, small): (file, md5)}
  50. _IMAGES_META = {
  51. ("train-standard", False): ("train_large_places365standard.tar", "67e186b496a84c929568076ed01a8aa1"),
  52. ("train-challenge", False): ("train_large_places365challenge.tar", "605f18e68e510c82b958664ea134545f"),
  53. ("val", False): ("val_large.tar", "9b71c4993ad89d2d8bcbdc4aef38042f"),
  54. ("test", False): ("test_large.tar", "41a4b6b724b1d2cd862fb3871ed59913"),
  55. ("train-standard", True): ("train_256_places365standard.tar", "53ca1c756c3d1e7809517cc47c5561c5"),
  56. ("train-challenge", True): ("train_256_places365challenge.tar", "741915038a5e3471ec7332404dfb64ef"),
  57. ("val", True): ("val_256.tar", "e27b17d8d44f4af9a78502beb927f808"),
  58. ("test", True): ("test_256.tar", "f532f6ad7b582262a2ec8009075e186b"),
  59. }
  60. def __init__(
  61. self,
  62. root: Union[str, Path],
  63. split: str = "train-standard",
  64. small: bool = False,
  65. download: bool = False,
  66. transform: Optional[Callable] = None,
  67. target_transform: Optional[Callable] = None,
  68. loader: Callable[[str], Any] = default_loader,
  69. ) -> None:
  70. super().__init__(root, transform=transform, target_transform=target_transform)
  71. self.split = self._verify_split(split)
  72. self.small = small
  73. self.loader = loader
  74. self.classes, self.class_to_idx = self.load_categories(download)
  75. self.imgs, self.targets = self.load_file_list(download)
  76. if download:
  77. self.download_images()
  78. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  79. file, target = self.imgs[index]
  80. image = self.loader(file)
  81. if self.transforms is not None:
  82. image, target = self.transforms(image, target)
  83. return image, target
  84. def __len__(self) -> int:
  85. return len(self.imgs)
  86. @property
  87. def variant(self) -> str:
  88. return "challenge" if "challenge" in self.split else "standard"
  89. @property
  90. def images_dir(self) -> str:
  91. size = "256" if self.small else "large"
  92. if self.split.startswith("train"):
  93. dir = f"data_{size}_{self.variant}"
  94. else:
  95. dir = f"{self.split}_{size}"
  96. return path.join(self.root, dir)
  97. def load_categories(self, download: bool = True) -> Tuple[List[str], Dict[str, int]]:
  98. def process(line: str) -> Tuple[str, int]:
  99. cls, idx = line.split()
  100. return cls, int(idx)
  101. file, md5 = self._CATEGORIES_META
  102. file = path.join(self.root, file)
  103. if not self._check_integrity(file, md5, download):
  104. self.download_devkit()
  105. with open(file) as fh:
  106. class_to_idx = dict(process(line) for line in fh)
  107. return sorted(class_to_idx.keys()), class_to_idx
  108. def load_file_list(
  109. self, download: bool = True
  110. ) -> Tuple[List[Tuple[str, Union[int, None]]], List[Union[int, None]]]:
  111. def process(line: str, sep="/") -> Tuple[str, Union[int, None]]:
  112. image, idx = (line.split() + [None])[:2]
  113. image = cast(str, image)
  114. idx = int(idx) if idx is not None else None
  115. return path.join(self.images_dir, image.lstrip(sep).replace(sep, os.sep)), idx
  116. file, md5 = self._FILE_LIST_META[self.split]
  117. file = path.join(self.root, file)
  118. if not self._check_integrity(file, md5, download):
  119. self.download_devkit()
  120. with open(file) as fh:
  121. images = [process(line) for line in fh]
  122. _, targets = zip(*images)
  123. return images, list(targets)
  124. def download_devkit(self) -> None:
  125. file, md5 = self._DEVKIT_META[self.variant]
  126. download_and_extract_archive(urljoin(self._BASE_URL, file), self.root, md5=md5)
  127. def download_images(self) -> None:
  128. if path.exists(self.images_dir):
  129. return
  130. file, md5 = self._IMAGES_META[(self.split, self.small)]
  131. download_and_extract_archive(urljoin(self._BASE_URL, file), self.root, md5=md5)
  132. if self.split.startswith("train"):
  133. os.rename(self.images_dir.rsplit("_", 1)[0], self.images_dir)
  134. def extra_repr(self) -> str:
  135. return "\n".join(("Split: {split}", "Small: {small}")).format(**self.__dict__)
  136. def _verify_split(self, split: str) -> str:
  137. return verify_str_arg(split, "split", self._SPLITS)
  138. def _check_integrity(self, file: str, md5: str, download: bool) -> bool:
  139. integrity = check_integrity(file, md5=md5)
  140. if not integrity and not download:
  141. raise RuntimeError(
  142. f"The file {file} does not exist or is corrupted. You can set download=True to download it."
  143. )
  144. return integrity
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...