Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

widerface.py 8.1 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...