widerface.py 7.9 KB

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