|
| 1 | +import csv |
| 2 | +import os |
| 3 | +from typing import Any, Callable, List, Optional, Tuple |
| 4 | + |
| 5 | +from PIL import Image |
| 6 | + |
| 7 | +from .utils import download_and_extract_archive |
| 8 | +from .vision import VisionDataset |
| 9 | + |
| 10 | + |
| 11 | +class Kitti(VisionDataset): |
| 12 | + """`KITTI <http://www.cvlibs.net/datasets/kitti>`_ Dataset. |
| 13 | +
|
| 14 | + Args: |
| 15 | + root (string): Root directory where images are downloaded to. |
| 16 | + Expects the following folder structure if download=False: |
| 17 | +
|
| 18 | + .. code:: |
| 19 | +
|
| 20 | + <root> |
| 21 | + └── Kitti |
| 22 | + └─ raw |
| 23 | + ├── training |
| 24 | + | ├── image_2 |
| 25 | + | └── label_2 |
| 26 | + └── testing |
| 27 | + └── image_2 |
| 28 | + train (bool, optional): Use ``train`` split if true, else ``test`` split. |
| 29 | + Defaults to ``train``. |
| 30 | + transform (callable, optional): A function/transform that takes in a PIL image |
| 31 | + and returns a transformed version. E.g, ``transforms.ToTensor`` |
| 32 | + target_transform (callable, optional): A function/transform that takes in the |
| 33 | + target and transforms it. |
| 34 | + transforms (callable, optional): A function/transform that takes input sample |
| 35 | + and its target as entry and returns a transformed version. |
| 36 | + download (bool, optional): If true, downloads the dataset from the internet and |
| 37 | + puts it in root directory. If dataset is already downloaded, it is not |
| 38 | + downloaded again. |
| 39 | +
|
| 40 | + """ |
| 41 | + |
| 42 | + data_url = "https://s3.eu-central-1.amazonaws.com/avg-kitti/" |
| 43 | + resources = [ |
| 44 | + "data_object_image_2.zip", |
| 45 | + "data_object_label_2.zip", |
| 46 | + ] |
| 47 | + image_dir_name = "image_2" |
| 48 | + labels_dir_name = "label_2" |
| 49 | + |
| 50 | + def __init__( |
| 51 | + self, |
| 52 | + root: str, |
| 53 | + train: bool = True, |
| 54 | + transform: Optional[Callable] = None, |
| 55 | + target_transform: Optional[Callable] = None, |
| 56 | + transforms: Optional[Callable] = None, |
| 57 | + download: bool = False, |
| 58 | + ): |
| 59 | + super().__init__( |
| 60 | + root, |
| 61 | + transform=transform, |
| 62 | + target_transform=target_transform, |
| 63 | + transforms=transforms, |
| 64 | + ) |
| 65 | + self.images = [] |
| 66 | + self.targets = [] |
| 67 | + self.root = root |
| 68 | + self.train = train |
| 69 | + self._location = "training" if self.train else "testing" |
| 70 | + |
| 71 | + if download: |
| 72 | + self.download() |
| 73 | + if not self._check_exists(): |
| 74 | + raise RuntimeError( |
| 75 | + "Dataset not found. You may use download=True to download it." |
| 76 | + ) |
| 77 | + |
| 78 | + image_dir = os.path.join(self._raw_folder, self._location, self.image_dir_name) |
| 79 | + if self.train: |
| 80 | + labels_dir = os.path.join(self._raw_folder, self._location, self.labels_dir_name) |
| 81 | + for img_file in os.listdir(image_dir): |
| 82 | + self.images.append(os.path.join(image_dir, img_file)) |
| 83 | + if self.train: |
| 84 | + self.targets.append( |
| 85 | + os.path.join(labels_dir, f"{img_file.split('.')[0]}.txt") |
| 86 | + ) |
| 87 | + |
| 88 | + def __getitem__(self, index: int) -> Tuple[Any, Any]: |
| 89 | + """Get item at a given index. |
| 90 | +
|
| 91 | + Args: |
| 92 | + index (int): Index |
| 93 | + Returns: |
| 94 | + tuple: (image, target), where |
| 95 | + target is a list of dictionaries with the following keys: |
| 96 | +
|
| 97 | + - type: str |
| 98 | + - truncated: float |
| 99 | + - occluded: int |
| 100 | + - alpha: float |
| 101 | + - bbox: float[4] |
| 102 | + - dimensions: float[3] |
| 103 | + - locations: float[3] |
| 104 | + - rotation_y: float |
| 105 | +
|
| 106 | + """ |
| 107 | + image = Image.open(self.images[index]) |
| 108 | + target = self._parse_target(index) if self.train else None |
| 109 | + if self.transforms: |
| 110 | + image, target = self.transforms(image, target) |
| 111 | + return image, target |
| 112 | + |
| 113 | + def _parse_target(self, index: int) -> List: |
| 114 | + target = [] |
| 115 | + with open(self.targets[index]) as inp: |
| 116 | + content = csv.reader(inp, delimiter=" ") |
| 117 | + for line in content: |
| 118 | + target.append({ |
| 119 | + "type": line[0], |
| 120 | + "truncated": float(line[1]), |
| 121 | + "occluded": int(line[2]), |
| 122 | + "alpha": float(line[3]), |
| 123 | + "bbox": [float(x) for x in line[4:8]], |
| 124 | + "dimensions": [float(x) for x in line[8:11]], |
| 125 | + "location": [float(x) for x in line[11:14]], |
| 126 | + "rotation_y": float(line[14]), |
| 127 | + }) |
| 128 | + return target |
| 129 | + |
| 130 | + def __len__(self) -> int: |
| 131 | + return len(self.images) |
| 132 | + |
| 133 | + @property |
| 134 | + def _raw_folder(self) -> str: |
| 135 | + return os.path.join(self.root, self.__class__.__name__, "raw") |
| 136 | + |
| 137 | + def _check_exists(self) -> bool: |
| 138 | + """Check if the data directory exists.""" |
| 139 | + folders = [self.image_dir_name] |
| 140 | + if self.train: |
| 141 | + folders.append(self.labels_dir_name) |
| 142 | + return all( |
| 143 | + os.path.isdir(os.path.join(self._raw_folder, self._location, fname)) |
| 144 | + for fname in folders |
| 145 | + ) |
| 146 | + |
| 147 | + def download(self) -> None: |
| 148 | + """Download the KITTI data if it doesn't exist already.""" |
| 149 | + |
| 150 | + if self._check_exists(): |
| 151 | + return |
| 152 | + |
| 153 | + os.makedirs(self._raw_folder, exist_ok=True) |
| 154 | + |
| 155 | + # download files |
| 156 | + for fname in self.resources: |
| 157 | + download_and_extract_archive( |
| 158 | + url=f"{self.data_url}{fname}", |
| 159 | + download_root=self._raw_folder, |
| 160 | + filename=fname, |
| 161 | + ) |
0 commit comments