widerface.py 7.9 KB

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