|
| 1 | +import os |
| 2 | +import os.path |
| 3 | +import pathlib |
| 4 | +from typing import Any, Callable, Optional, Union, Tuple |
| 5 | +from typing import Sequence |
| 6 | + |
| 7 | +from PIL import Image |
| 8 | + |
| 9 | +from .utils import download_and_extract_archive, verify_str_arg |
| 10 | +from .vision import VisionDataset |
| 11 | + |
| 12 | + |
| 13 | +class OxfordIIITPet(VisionDataset): |
| 14 | + """`Oxford-IIIT Pet Dataset <https://www.robots.ox.ac.uk/~vgg/data/pets/>`_. |
| 15 | +
|
| 16 | + Args: |
| 17 | + root (string): Root directory of the dataset. |
| 18 | + split (string, optional): The dataset split, supports ``"trainval"`` (default) or ``"test"``. |
| 19 | + target_types (string, sequence of strings, optional): Types of target to use. Can be ``category`` (default) or |
| 20 | + ``segmentation``. Can also be a list to output a tuple with all specified target types. The types represent: |
| 21 | +
|
| 22 | + - ``category`` (int): Label for one of the 37 pet categories. |
| 23 | + - ``segmentation`` (PIL image): Segmentation trimap of the image. |
| 24 | +
|
| 25 | + If empty, ``None`` will be returned as target. |
| 26 | +
|
| 27 | + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed |
| 28 | + version. E.g, ``transforms.RandomCrop``. |
| 29 | + target_transform (callable, optional): A function/transform that takes in the target and transforms it. |
| 30 | + download (bool, optional): If True, downloads the dataset from the internet and puts it into ``root/dtd``. If |
| 31 | + dataset is already downloaded, it is not downloaded again. |
| 32 | + """ |
| 33 | + |
| 34 | + _RESOURCES = ( |
| 35 | + ("https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz", "5c4f3ee8e5d25df40f4fd59a7f44e54c"), |
| 36 | + ("https://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz", "95a8c909bbe2e81eed6a22bccdf3f68f"), |
| 37 | + ) |
| 38 | + _VALID_TARGET_TYPES = ("category", "segmentation") |
| 39 | + |
| 40 | + def __init__( |
| 41 | + self, |
| 42 | + root: str, |
| 43 | + split: str = "trainval", |
| 44 | + target_types: Union[Sequence[str], str] = "category", |
| 45 | + transforms: Optional[Callable] = None, |
| 46 | + transform: Optional[Callable] = None, |
| 47 | + target_transform: Optional[Callable] = None, |
| 48 | + download: bool = True, |
| 49 | + ): |
| 50 | + self._split = verify_str_arg(split, "split", ("trainval", "test")) |
| 51 | + if isinstance(target_types, str): |
| 52 | + target_types = [target_types] |
| 53 | + self._target_types = [ |
| 54 | + verify_str_arg(target_type, "target_types", self._VALID_TARGET_TYPES) for target_type in target_types |
| 55 | + ] |
| 56 | + |
| 57 | + super().__init__(root, transforms=transforms, transform=transform, target_transform=target_transform) |
| 58 | + self._base_folder = pathlib.Path(self.root) / "oxford-iiit-pet" |
| 59 | + self._images_folder = self._base_folder / "images" |
| 60 | + self._anns_folder = self._base_folder / "annotations" |
| 61 | + self._segs_folder = self._anns_folder / "trimaps" |
| 62 | + |
| 63 | + if download: |
| 64 | + self._download() |
| 65 | + |
| 66 | + if not self._check_exists(): |
| 67 | + raise RuntimeError("Dataset not found. You can use download=True to download it") |
| 68 | + |
| 69 | + image_ids = [] |
| 70 | + self._labels = [] |
| 71 | + with open(self._anns_folder / f"{self._split}.txt") as file: |
| 72 | + for line in file: |
| 73 | + image_id, label, *_ = line.strip().split() |
| 74 | + image_ids.append(image_id) |
| 75 | + self._labels.append(int(label) - 1) |
| 76 | + |
| 77 | + self.classes = [ |
| 78 | + " ".join(part.title() for part in raw_cls.split("_")) |
| 79 | + for raw_cls, _ in sorted( |
| 80 | + {(image_id.rsplit("_", 1)[0], label) for image_id, label in zip(image_ids, self._labels)}, |
| 81 | + key=lambda image_id_and_label: image_id_and_label[1], |
| 82 | + ) |
| 83 | + ] |
| 84 | + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) |
| 85 | + |
| 86 | + self._images = [self._images_folder / f"{image_id}.jpg" for image_id in image_ids] |
| 87 | + self._segs = [self._segs_folder / f"{image_id}.png" for image_id in image_ids] |
| 88 | + |
| 89 | + def __len__(self) -> int: |
| 90 | + return len(self._images) |
| 91 | + |
| 92 | + def __getitem__(self, idx: int) -> Tuple[Any, Any]: |
| 93 | + image = Image.open(self._images[idx]).convert("RGB") |
| 94 | + |
| 95 | + target: Any = [] |
| 96 | + for target_type in self._target_types: |
| 97 | + if target_type == "category": |
| 98 | + target.append(self._labels[idx]) |
| 99 | + else: # target_type == "segmentation" |
| 100 | + target.append(Image.open(self._segs[idx])) |
| 101 | + |
| 102 | + if not target: |
| 103 | + target = None |
| 104 | + elif len(target) == 1: |
| 105 | + target = target[0] |
| 106 | + else: |
| 107 | + target = tuple(target) |
| 108 | + |
| 109 | + if self.transforms: |
| 110 | + image, target = self.transforms(image, target) |
| 111 | + |
| 112 | + return image, target |
| 113 | + |
| 114 | + def _check_exists(self) -> bool: |
| 115 | + for folder in (self._images_folder, self._anns_folder): |
| 116 | + if not (os.path.exists(folder) and os.path.isdir(folder)): |
| 117 | + return False |
| 118 | + else: |
| 119 | + return True |
| 120 | + |
| 121 | + def _download(self) -> None: |
| 122 | + if self._check_exists(): |
| 123 | + return |
| 124 | + |
| 125 | + for url, md5 in self._RESOURCES: |
| 126 | + download_and_extract_archive(url, download_root=str(self._base_folder), md5=md5) |
0 commit comments