celeba.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import csv
  2. import os
  3. from collections import namedtuple
  4. from typing import Any, Callable, List, Optional, Tuple, Union
  5. import PIL
  6. import torch
  7. from .utils import check_integrity, download_file_from_google_drive, extract_archive, verify_str_arg
  8. from .vision import VisionDataset
  9. CSV = namedtuple("CSV", ["header", "index", "data"])
  10. class CelebA(VisionDataset):
  11. """`Large-scale CelebFaces Attributes (CelebA) Dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`_ Dataset.
  12. Args:
  13. root (string): Root directory where images are downloaded to.
  14. split (string): One of {'train', 'valid', 'test', 'all'}.
  15. Accordingly dataset is selected.
  16. target_type (string or list, optional): Type of target to use, ``attr``, ``identity``, ``bbox``,
  17. or ``landmarks``. Can also be a list to output a tuple with all specified target types.
  18. The targets represent:
  19. - ``attr`` (Tensor shape=(40,) dtype=int): binary (0, 1) labels for attributes
  20. - ``identity`` (int): label for each person (data points with the same identity are the same person)
  21. - ``bbox`` (Tensor shape=(4,) dtype=int): bounding box (x, y, width, height)
  22. - ``landmarks`` (Tensor shape=(10,) dtype=int): landmark points (lefteye_x, lefteye_y, righteye_x,
  23. righteye_y, nose_x, nose_y, leftmouth_x, leftmouth_y, rightmouth_x, rightmouth_y)
  24. Defaults to ``attr``. If empty, ``None`` will be returned as target.
  25. transform (callable, optional): A function/transform that takes in an PIL image
  26. and returns a transformed version. E.g, ``transforms.PILToTensor``
  27. target_transform (callable, optional): A function/transform that takes in the
  28. target and transforms it.
  29. download (bool, optional): If true, downloads the dataset from the internet and
  30. puts it in root directory. If dataset is already downloaded, it is not
  31. downloaded again.
  32. """
  33. base_folder = "celeba"
  34. # There currently does not appear to be an easy way to extract 7z in python (without introducing additional
  35. # dependencies). The "in-the-wild" (not aligned+cropped) images are only in 7z, so they are not available
  36. # right now.
  37. file_list = [
  38. # File ID MD5 Hash Filename
  39. ("0B7EVK8r0v71pZjFTYXZWM3FlRnM", "00d2c5bc6d35e252742224ab0c1e8fcb", "img_align_celeba.zip"),
  40. # ("0B7EVK8r0v71pbWNEUjJKdDQ3dGc","b6cd7e93bc7a96c2dc33f819aa3ac651", "img_align_celeba_png.7z"),
  41. # ("0B7EVK8r0v71peklHb0pGdDl6R28", "b6cd7e93bc7a96c2dc33f819aa3ac651", "img_celeba.7z"),
  42. ("0B7EVK8r0v71pblRyaVFSWGxPY0U", "75e246fa4810816ffd6ee81facbd244c", "list_attr_celeba.txt"),
  43. ("1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS", "32bd1bd63d3c78cd57e08160ec5ed1e2", "identity_CelebA.txt"),
  44. ("0B7EVK8r0v71pbThiMVRxWXZ4dU0", "00566efa6fedff7a56946cd1c10f1c16", "list_bbox_celeba.txt"),
  45. ("0B7EVK8r0v71pd0FJY3Blby1HUTQ", "cc24ecafdb5b50baae59b03474781f8c", "list_landmarks_align_celeba.txt"),
  46. # ("0B7EVK8r0v71pTzJIdlJWdHczRlU", "063ee6ddb681f96bc9ca28c6febb9d1a", "list_landmarks_celeba.txt"),
  47. ("0B7EVK8r0v71pY0NSMzRuSXJEVkk", "d32c9cbf5e040fd4025c592c306e6668", "list_eval_partition.txt"),
  48. ]
  49. def __init__(
  50. self,
  51. root: str,
  52. split: str = "train",
  53. target_type: Union[List[str], str] = "attr",
  54. transform: Optional[Callable] = None,
  55. target_transform: Optional[Callable] = None,
  56. download: bool = False,
  57. ) -> None:
  58. super().__init__(root, transform=transform, target_transform=target_transform)
  59. self.split = split
  60. if isinstance(target_type, list):
  61. self.target_type = target_type
  62. else:
  63. self.target_type = [target_type]
  64. if not self.target_type and self.target_transform is not None:
  65. raise RuntimeError("target_transform is specified but target_type is empty")
  66. if download:
  67. self.download()
  68. if not self._check_integrity():
  69. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  70. split_map = {
  71. "train": 0,
  72. "valid": 1,
  73. "test": 2,
  74. "all": None,
  75. }
  76. split_ = split_map[verify_str_arg(split.lower(), "split", ("train", "valid", "test", "all"))]
  77. splits = self._load_csv("list_eval_partition.txt")
  78. identity = self._load_csv("identity_CelebA.txt")
  79. bbox = self._load_csv("list_bbox_celeba.txt", header=1)
  80. landmarks_align = self._load_csv("list_landmarks_align_celeba.txt", header=1)
  81. attr = self._load_csv("list_attr_celeba.txt", header=1)
  82. mask = slice(None) if split_ is None else (splits.data == split_).squeeze()
  83. if mask == slice(None): # if split == "all"
  84. self.filename = splits.index
  85. else:
  86. self.filename = [splits.index[i] for i in torch.squeeze(torch.nonzero(mask))]
  87. self.identity = identity.data[mask]
  88. self.bbox = bbox.data[mask]
  89. self.landmarks_align = landmarks_align.data[mask]
  90. self.attr = attr.data[mask]
  91. # map from {-1, 1} to {0, 1}
  92. self.attr = torch.div(self.attr + 1, 2, rounding_mode="floor")
  93. self.attr_names = attr.header
  94. def _load_csv(
  95. self,
  96. filename: str,
  97. header: Optional[int] = None,
  98. ) -> CSV:
  99. with open(os.path.join(self.root, self.base_folder, filename)) as csv_file:
  100. data = list(csv.reader(csv_file, delimiter=" ", skipinitialspace=True))
  101. if header is not None:
  102. headers = data[header]
  103. data = data[header + 1 :]
  104. else:
  105. headers = []
  106. indices = [row[0] for row in data]
  107. data = [row[1:] for row in data]
  108. data_int = [list(map(int, i)) for i in data]
  109. return CSV(headers, indices, torch.tensor(data_int))
  110. def _check_integrity(self) -> bool:
  111. for (_, md5, filename) in self.file_list:
  112. fpath = os.path.join(self.root, self.base_folder, filename)
  113. _, ext = os.path.splitext(filename)
  114. # Allow original archive to be deleted (zip and 7z)
  115. # Only need the extracted images
  116. if ext not in [".zip", ".7z"] and not check_integrity(fpath, md5):
  117. return False
  118. # Should check a hash of the images
  119. return os.path.isdir(os.path.join(self.root, self.base_folder, "img_align_celeba"))
  120. def download(self) -> None:
  121. if self._check_integrity():
  122. print("Files already downloaded and verified")
  123. return
  124. for (file_id, md5, filename) in self.file_list:
  125. download_file_from_google_drive(file_id, os.path.join(self.root, self.base_folder), filename, md5)
  126. extract_archive(os.path.join(self.root, self.base_folder, "img_align_celeba.zip"))
  127. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  128. X = PIL.Image.open(os.path.join(self.root, self.base_folder, "img_align_celeba", self.filename[index]))
  129. target: Any = []
  130. for t in self.target_type:
  131. if t == "attr":
  132. target.append(self.attr[index, :])
  133. elif t == "identity":
  134. target.append(self.identity[index, 0])
  135. elif t == "bbox":
  136. target.append(self.bbox[index, :])
  137. elif t == "landmarks":
  138. target.append(self.landmarks_align[index, :])
  139. else:
  140. # TODO: refactor with utils.verify_str_arg
  141. raise ValueError(f'Target type "{t}" is not recognized.')
  142. if self.transform is not None:
  143. X = self.transform(X)
  144. if target:
  145. target = tuple(target) if len(target) > 1 else target[0]
  146. if self.target_transform is not None:
  147. target = self.target_transform(target)
  148. else:
  149. target = None
  150. return X, target
  151. def __len__(self) -> int:
  152. return len(self.attr)
  153. def extra_repr(self) -> str:
  154. lines = ["Target type: {target_type}", "Split: {split}"]
  155. return "\n".join(lines).format(**self.__dict__)