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