lsun.py 5.5 KB

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