widerface.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. import os
  2. from os.path import abspath, expanduser
  3. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  4. import torch
  5. from PIL import Image
  6. from .utils import download_and_extract_archive, download_file_from_google_drive, extract_archive, verify_str_arg
  7. from .vision import VisionDataset
  8. class WIDERFace(VisionDataset):
  9. """`WIDERFace <http://shuoyang1213.me/WIDERFACE/>`_ Dataset.
  10. Args:
  11. root (string): Root directory where images and annotations are downloaded to.
  12. Expects the following folder structure if download=False:
  13. .. code::
  14. <root>
  15. └── widerface
  16. ├── wider_face_split ('wider_face_split.zip' if compressed)
  17. ├── WIDER_train ('WIDER_train.zip' if compressed)
  18. ├── WIDER_val ('WIDER_val.zip' if compressed)
  19. └── WIDER_test ('WIDER_test.zip' if compressed)
  20. split (string): The dataset split to use. One of {``train``, ``val``, ``test``}.
  21. Defaults to ``train``.
  22. transform (callable, optional): A function/transform that takes in a PIL image
  23. and returns a transformed version. E.g, ``transforms.RandomCrop``
  24. target_transform (callable, optional): A function/transform that takes in the
  25. target and transforms it.
  26. download (bool, optional): If true, downloads the dataset from the internet and
  27. puts it in root directory. If dataset is already downloaded, it is not
  28. downloaded again.
  29. .. warning::
  30. To download the dataset `gdown <https://github.com/wkentaro/gdown>`_ is required.
  31. """
  32. BASE_FOLDER = "widerface"
  33. FILE_LIST = [
  34. # File ID MD5 Hash Filename
  35. ("15hGDLhsx8bLgLcIRD5DhYt5iBxnjNF1M", "3fedf70df600953d25982bcd13d91ba2", "WIDER_train.zip"),
  36. ("1GUCogbp16PMGa39thoMMeWxp7Rp5oM8Q", "dfa7d7e790efa35df3788964cf0bbaea", "WIDER_val.zip"),
  37. ("1HIfDbVEWKmsYKJZm4lchTBDLW5N7dY5T", "e5d8f4248ed24c334bbd12f49c29dd40", "WIDER_test.zip"),
  38. ]
  39. ANNOTATIONS_FILE = (
  40. "http://shuoyang1213.me/WIDERFACE/support/bbx_annotation/wider_face_split.zip",
  41. "0e3767bcf0e326556d407bf5bff5d27c",
  42. "wider_face_split.zip",
  43. )
  44. def __init__(
  45. self,
  46. root: str,
  47. split: str = "train",
  48. transform: Optional[Callable] = None,
  49. target_transform: Optional[Callable] = None,
  50. download: bool = False,
  51. ) -> None:
  52. super().__init__(
  53. root=os.path.join(root, self.BASE_FOLDER), transform=transform, target_transform=target_transform
  54. )
  55. # check arguments
  56. self.split = verify_str_arg(split, "split", ("train", "val", "test"))
  57. if download:
  58. self.download()
  59. if not self._check_integrity():
  60. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download and prepare it")
  61. self.img_info: List[Dict[str, Union[str, Dict[str, torch.Tensor]]]] = []
  62. if self.split in ("train", "val"):
  63. self.parse_train_val_annotations_file()
  64. else:
  65. self.parse_test_annotations_file()
  66. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  67. """
  68. Args:
  69. index (int): Index
  70. Returns:
  71. tuple: (image, target) where target is a dict of annotations for all faces in the image.
  72. target=None for the test split.
  73. """
  74. # stay consistent with other datasets and return a PIL Image
  75. img = Image.open(self.img_info[index]["img_path"])
  76. if self.transform is not None:
  77. img = self.transform(img)
  78. target = None if self.split == "test" else self.img_info[index]["annotations"]
  79. if self.target_transform is not None:
  80. target = self.target_transform(target)
  81. return img, target
  82. def __len__(self) -> int:
  83. return len(self.img_info)
  84. def extra_repr(self) -> str:
  85. lines = ["Split: {split}"]
  86. return "\n".join(lines).format(**self.__dict__)
  87. def parse_train_val_annotations_file(self) -> None:
  88. filename = "wider_face_train_bbx_gt.txt" if self.split == "train" else "wider_face_val_bbx_gt.txt"
  89. filepath = os.path.join(self.root, "wider_face_split", filename)
  90. with open(filepath) as f:
  91. lines = f.readlines()
  92. file_name_line, num_boxes_line, box_annotation_line = True, False, False
  93. num_boxes, box_counter = 0, 0
  94. labels = []
  95. for line in lines:
  96. line = line.rstrip()
  97. if file_name_line:
  98. img_path = os.path.join(self.root, "WIDER_" + self.split, "images", line)
  99. img_path = abspath(expanduser(img_path))
  100. file_name_line = False
  101. num_boxes_line = True
  102. elif num_boxes_line:
  103. num_boxes = int(line)
  104. num_boxes_line = False
  105. box_annotation_line = True
  106. elif box_annotation_line:
  107. box_counter += 1
  108. line_split = line.split(" ")
  109. line_values = [int(x) for x in line_split]
  110. labels.append(line_values)
  111. if box_counter >= num_boxes:
  112. box_annotation_line = False
  113. file_name_line = True
  114. labels_tensor = torch.tensor(labels)
  115. self.img_info.append(
  116. {
  117. "img_path": img_path,
  118. "annotations": {
  119. "bbox": labels_tensor[:, 0:4].clone(), # x, y, width, height
  120. "blur": labels_tensor[:, 4].clone(),
  121. "expression": labels_tensor[:, 5].clone(),
  122. "illumination": labels_tensor[:, 6].clone(),
  123. "occlusion": labels_tensor[:, 7].clone(),
  124. "pose": labels_tensor[:, 8].clone(),
  125. "invalid": labels_tensor[:, 9].clone(),
  126. },
  127. }
  128. )
  129. box_counter = 0
  130. labels.clear()
  131. else:
  132. raise RuntimeError(f"Error parsing annotation file {filepath}")
  133. def parse_test_annotations_file(self) -> None:
  134. filepath = os.path.join(self.root, "wider_face_split", "wider_face_test_filelist.txt")
  135. filepath = abspath(expanduser(filepath))
  136. with open(filepath) as f:
  137. lines = f.readlines()
  138. for line in lines:
  139. line = line.rstrip()
  140. img_path = os.path.join(self.root, "WIDER_test", "images", line)
  141. img_path = abspath(expanduser(img_path))
  142. self.img_info.append({"img_path": img_path})
  143. def _check_integrity(self) -> bool:
  144. # Allow original archive to be deleted (zip). Only need the extracted images
  145. all_files = self.FILE_LIST.copy()
  146. all_files.append(self.ANNOTATIONS_FILE)
  147. for (_, md5, filename) in all_files:
  148. file, ext = os.path.splitext(filename)
  149. extracted_dir = os.path.join(self.root, file)
  150. if not os.path.exists(extracted_dir):
  151. return False
  152. return True
  153. def download(self) -> None:
  154. if self._check_integrity():
  155. print("Files already downloaded and verified")
  156. return
  157. # download and extract image data
  158. for (file_id, md5, filename) in self.FILE_LIST:
  159. download_file_from_google_drive(file_id, self.root, filename, md5)
  160. filepath = os.path.join(self.root, filename)
  161. extract_archive(filepath)
  162. # download and extract annotation files
  163. download_and_extract_archive(
  164. url=self.ANNOTATIONS_FILE[0], download_root=self.root, md5=self.ANNOTATIONS_FILE[1]
  165. )