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

lsun.py 5.6 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
  1. import io
  2. import os.path
  3. import pickle
  4. import string
  5. from collections.abc import Iterable
  6. from pathlib import Path
  7. from typing import Any, Callable, cast, List, Optional, Tuple, Union
  8. from PIL import Image
  9. from .utils import iterable_to_str, verify_str_arg
  10. from .vision import VisionDataset
  11. class LSUNClass(VisionDataset):
  12. def __init__(
  13. self, root: str, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None
  14. ) -> None:
  15. import lmdb
  16. super().__init__(root, transform=transform, target_transform=target_transform)
  17. self.env = lmdb.open(root, max_readers=1, readonly=True, lock=False, readahead=False, meminit=False)
  18. with self.env.begin(write=False) as txn:
  19. self.length = txn.stat()["entries"]
  20. cache_file = "_cache_" + "".join(c for c in root if c in string.ascii_letters)
  21. if os.path.isfile(cache_file):
  22. self.keys = pickle.load(open(cache_file, "rb"))
  23. else:
  24. with self.env.begin(write=False) as txn:
  25. self.keys = [key for key in txn.cursor().iternext(keys=True, values=False)]
  26. pickle.dump(self.keys, open(cache_file, "wb"))
  27. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  28. img, target = None, None
  29. env = self.env
  30. with env.begin(write=False) as txn:
  31. imgbuf = txn.get(self.keys[index])
  32. buf = io.BytesIO()
  33. buf.write(imgbuf)
  34. buf.seek(0)
  35. img = Image.open(buf).convert("RGB")
  36. if self.transform is not None:
  37. img = self.transform(img)
  38. if self.target_transform is not None:
  39. target = self.target_transform(target)
  40. return img, target
  41. def __len__(self) -> int:
  42. return self.length
  43. class LSUN(VisionDataset):
  44. """`LSUN <https://paperswithcode.com/dataset/lsun>`_ dataset.
  45. You will need to install the ``lmdb`` package to use this dataset: run
  46. ``pip install lmdb``
  47. Args:
  48. root (str or ``pathlib.Path``): Root directory for the database files.
  49. classes (string or list): One of {'train', 'val', 'test'} or a list of
  50. categories to load. e,g. ['bedroom_train', 'church_outdoor_train'].
  51. transform (callable, optional): A function/transform that takes in a PIL image
  52. and returns a transformed version. E.g, ``transforms.RandomCrop``
  53. target_transform (callable, optional): A function/transform that takes in the
  54. target and transforms it.
  55. """
  56. def __init__(
  57. self,
  58. root: Union[str, Path],
  59. classes: Union[str, List[str]] = "train",
  60. transform: Optional[Callable] = None,
  61. target_transform: Optional[Callable] = None,
  62. ) -> None:
  63. super().__init__(root, transform=transform, target_transform=target_transform)
  64. self.classes = self._verify_classes(classes)
  65. # for each class, create an LSUNClassDataset
  66. self.dbs = []
  67. for c in self.classes:
  68. self.dbs.append(LSUNClass(root=os.path.join(root, f"{c}_lmdb"), transform=transform))
  69. self.indices = []
  70. count = 0
  71. for db in self.dbs:
  72. count += len(db)
  73. self.indices.append(count)
  74. self.length = count
  75. def _verify_classes(self, classes: Union[str, List[str]]) -> List[str]:
  76. categories = [
  77. "bedroom",
  78. "bridge",
  79. "church_outdoor",
  80. "classroom",
  81. "conference_room",
  82. "dining_room",
  83. "kitchen",
  84. "living_room",
  85. "restaurant",
  86. "tower",
  87. ]
  88. dset_opts = ["train", "val", "test"]
  89. try:
  90. classes = cast(str, classes)
  91. verify_str_arg(classes, "classes", dset_opts)
  92. if classes == "test":
  93. classes = [classes]
  94. else:
  95. classes = [c + "_" + classes for c in categories]
  96. except ValueError:
  97. if not isinstance(classes, Iterable):
  98. msg = "Expected type str or Iterable for argument classes, but got type {}."
  99. raise ValueError(msg.format(type(classes)))
  100. classes = list(classes)
  101. msg_fmtstr_type = "Expected type str for elements in argument classes, but got type {}."
  102. for c in classes:
  103. verify_str_arg(c, custom_msg=msg_fmtstr_type.format(type(c)))
  104. c_short = c.split("_")
  105. category, dset_opt = "_".join(c_short[:-1]), c_short[-1]
  106. msg_fmtstr = "Unknown value '{}' for {}. Valid values are {{{}}}."
  107. msg = msg_fmtstr.format(category, "LSUN class", iterable_to_str(categories))
  108. verify_str_arg(category, valid_values=categories, custom_msg=msg)
  109. msg = msg_fmtstr.format(dset_opt, "postfix", iterable_to_str(dset_opts))
  110. verify_str_arg(dset_opt, valid_values=dset_opts, custom_msg=msg)
  111. return classes
  112. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  113. """
  114. Args:
  115. index (int): Index
  116. Returns:
  117. tuple: Tuple (image, target) where target is the index of the target category.
  118. """
  119. target = 0
  120. sub = 0
  121. for ind in self.indices:
  122. if index < ind:
  123. break
  124. target += 1
  125. sub = ind
  126. db = self.dbs[target]
  127. index = index - sub
  128. if self.target_transform is not None:
  129. target = self.target_transform(target)
  130. img, _ = db[index]
  131. return img, target
  132. def __len__(self) -> int:
  133. return self.length
  134. def extra_repr(self) -> str:
  135. return "Classes: {classes}".format(**self.__dict__)
Tip!

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

Comments

Loading...