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

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

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

Comments

Loading...