|
| 1 | +import os |
| 2 | +import cv2 |
| 3 | +import shutil |
| 4 | +import numpy as np |
| 5 | +from tqdm import tqdm |
| 6 | +from urllib.request import urlretrieve |
| 7 | + |
| 8 | + |
| 9 | +class OxfordPetDataset(torch.utils.data.Dataset): |
| 10 | + |
| 11 | + def __init__(self, root, mode="train", transform=None): |
| 12 | + |
| 13 | + assert mode in {"train", "valid", "test"} |
| 14 | + |
| 15 | + self.root = root |
| 16 | + self.mode = mode |
| 17 | + self.transform = transform |
| 18 | + |
| 19 | + self._download_dataset() # download only if it does not exist |
| 20 | + |
| 21 | + self.images_directory = os.path.join(self.root, "images") |
| 22 | + self.masks_directory = os.path.join(self.root, "annotations", "trimaps") |
| 23 | + |
| 24 | + self.filenames = self._read_split() # read train/valid/test splits |
| 25 | + |
| 26 | + def __len__(self): |
| 27 | + return len(self.filenames) |
| 28 | + |
| 29 | + def __getitem__(self, idx): |
| 30 | + |
| 31 | + filename = self.filenames[idx] |
| 32 | + image_path = os.path.join(self.images_directory, filename + ".jpg") |
| 33 | + mask_path = os.path.join(self.masks_directory, filename + ".png") |
| 34 | + |
| 35 | + image = cv2.imread(image_path) |
| 36 | + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) |
| 37 | + |
| 38 | + trimap = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED) |
| 39 | + mask = self._preprocess_mask(trimap) |
| 40 | + |
| 41 | + sample = dict(image=image, mask=mask, trimap=trimap) |
| 42 | + if self.transform is not None: |
| 43 | + sample = self.transform(**sample) |
| 44 | + |
| 45 | + return sample |
| 46 | + |
| 47 | + @staticmethod |
| 48 | + def _preprocess_mask(mask): |
| 49 | + mask = mask.astype(np.float32) |
| 50 | + mask[mask == 2.0] = 0.0 |
| 51 | + mask[(mask == 1.0) | (mask == 3.0)] = 1.0 |
| 52 | + return mask |
| 53 | + |
| 54 | + def _read_split(self): |
| 55 | + split_filename = "test.txt" if self.mode == "test" else "trainval.txt" |
| 56 | + split_filepath = os.path.join(self.root, "annotations", split_filename) |
| 57 | + with open(split_filepath) as f: |
| 58 | + split_data = f.read().strip("\n").split("\n") |
| 59 | + filenames = [x.split(" ")[0] for x in split_data] |
| 60 | + if self.mode == "train": # 90% for train |
| 61 | + filenames = [x for i, x in enumerate(filenames) if i % 10 != 0] |
| 62 | + elif self.mode == "valid": # 10% for validation |
| 63 | + filenames = [x for i, x in enumerate(filenames) if i % 10 == 0] |
| 64 | + return filenames |
| 65 | + |
| 66 | + def _download_dataset(self): |
| 67 | + |
| 68 | + # load images |
| 69 | + filepath = os.path.join(self.root, "images.tar.gz") |
| 70 | + download_url( |
| 71 | + url="https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz", filepath=filepath, |
| 72 | + ) |
| 73 | + extract_archive(filepath) |
| 74 | + |
| 75 | + # load annotations |
| 76 | + filepath = os.path.join(self.root, "annotations.tar.gz") |
| 77 | + download_url( |
| 78 | + url="https://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz", filepath=filepath, |
| 79 | + ) |
| 80 | + extract_archive(filepath) |
| 81 | + |
| 82 | + |
| 83 | +class SimpleOxfordPetDataset(OxfordPetDataset): |
| 84 | + """Dataset for example without augmentations and transforms""" |
| 85 | + |
| 86 | + def __getitem__(self, *args, **kwargs): |
| 87 | + |
| 88 | + sample = super().__getitem__(*args, **kwargs) |
| 89 | + |
| 90 | + # resize images |
| 91 | + image = cv2.resize(sample["image"], (256, 256), cv2.INTER_LINEAR) |
| 92 | + mask = cv2.resize(sample["mask"], (256, 256), cv2.INTER_NEAREST) |
| 93 | + trimap = cv2.resize(sample["trimap"], (256, 256), cv2.INTER_NEAREST) |
| 94 | + |
| 95 | + # convert to other format HWC -> CHW |
| 96 | + sample["image"] = np.moveaxis(image, -1, 0) |
| 97 | + sample["mask"] = np.expand_dims(mask, 0) |
| 98 | + sample["trimap"] = np.expand_dims(trimap, 0) |
| 99 | + |
| 100 | + return sample |
| 101 | + |
| 102 | + |
| 103 | +class TqdmUpTo(tqdm): |
| 104 | + def update_to(self, b=1, bsize=1, tsize=None): |
| 105 | + if tsize is not None: |
| 106 | + self.total = tsize |
| 107 | + self.update(b * bsize - self.n) |
| 108 | + |
| 109 | + |
| 110 | +def download_url(url, filepath): |
| 111 | + directory = os.path.dirname(os.path.abspath(filepath)) |
| 112 | + os.makedirs(directory, exist_ok=True) |
| 113 | + if os.path.exists(filepath): |
| 114 | + return |
| 115 | + |
| 116 | + with TqdmUpTo(unit="B", unit_scale=True, unit_divisor=1024, miniters=1, desc=os.path.basename(filepath)) as t: |
| 117 | + urlretrieve(url, filename=filepath, reporthook=t.update_to, data=None) |
| 118 | + t.total = t.n |
| 119 | + |
| 120 | + |
| 121 | +def extract_archive(filepath): |
| 122 | + extract_dir = os.path.dirname(os.path.abspath(filepath)) |
| 123 | + dst_dir = os.path.splitext(filepath)[0] |
| 124 | + if not os.path.exists(dst_dir): |
| 125 | + shutil.unpack_archive(filepath, extract_dir) |
0 commit comments