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

_optical_flow.py 21 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
  1. import itertools
  2. import os
  3. from abc import ABC, abstractmethod
  4. from glob import glob
  5. from pathlib import Path
  6. from typing import Any, Callable, List, Optional, Tuple, Union
  7. import numpy as np
  8. import torch
  9. from PIL import Image
  10. from ..io.image import decode_png, read_file
  11. from .folder import default_loader
  12. from .utils import _read_pfm, verify_str_arg
  13. from .vision import VisionDataset
  14. T1 = Tuple[Image.Image, Image.Image, Optional[np.ndarray], Optional[np.ndarray]]
  15. T2 = Tuple[Image.Image, Image.Image, Optional[np.ndarray]]
  16. __all__ = (
  17. "KittiFlow",
  18. "Sintel",
  19. "FlyingThings3D",
  20. "FlyingChairs",
  21. "HD1K",
  22. )
  23. class FlowDataset(ABC, VisionDataset):
  24. # Some datasets like Kitti have a built-in valid_flow_mask, indicating which flow values are valid
  25. # For those we return (img1, img2, flow, valid_flow_mask), and for the rest we return (img1, img2, flow),
  26. # and it's up to whatever consumes the dataset to decide what valid_flow_mask should be.
  27. _has_builtin_flow_mask = False
  28. def __init__(
  29. self,
  30. root: Union[str, Path],
  31. transforms: Optional[Callable] = None,
  32. loader: Callable[[str], Any] = default_loader,
  33. ) -> None:
  34. super().__init__(root=root)
  35. self.transforms = transforms
  36. self._flow_list: List[str] = []
  37. self._image_list: List[List[str]] = []
  38. self._loader = loader
  39. def _read_img(self, file_name: str) -> Union[Image.Image, torch.Tensor]:
  40. return self._loader(file_name)
  41. @abstractmethod
  42. def _read_flow(self, file_name: str):
  43. # Return the flow or a tuple with the flow and the valid_flow_mask if _has_builtin_flow_mask is True
  44. pass
  45. def __getitem__(self, index: int) -> Union[T1, T2]:
  46. img1 = self._read_img(self._image_list[index][0])
  47. img2 = self._read_img(self._image_list[index][1])
  48. if self._flow_list: # it will be empty for some dataset when split="test"
  49. flow = self._read_flow(self._flow_list[index])
  50. if self._has_builtin_flow_mask:
  51. flow, valid_flow_mask = flow
  52. else:
  53. valid_flow_mask = None
  54. else:
  55. flow = valid_flow_mask = None
  56. if self.transforms is not None:
  57. img1, img2, flow, valid_flow_mask = self.transforms(img1, img2, flow, valid_flow_mask)
  58. if self._has_builtin_flow_mask or valid_flow_mask is not None:
  59. # The `or valid_flow_mask is not None` part is here because the mask can be generated within a transform
  60. return img1, img2, flow, valid_flow_mask # type: ignore[return-value]
  61. else:
  62. return img1, img2, flow # type: ignore[return-value]
  63. def __len__(self) -> int:
  64. return len(self._image_list)
  65. def __rmul__(self, v: int) -> torch.utils.data.ConcatDataset:
  66. return torch.utils.data.ConcatDataset([self] * v)
  67. class Sintel(FlowDataset):
  68. """`Sintel <http://sintel.is.tue.mpg.de/>`_ Dataset for optical flow.
  69. The dataset is expected to have the following structure: ::
  70. root
  71. Sintel
  72. testing
  73. clean
  74. scene_1
  75. scene_2
  76. ...
  77. final
  78. scene_1
  79. scene_2
  80. ...
  81. training
  82. clean
  83. scene_1
  84. scene_2
  85. ...
  86. final
  87. scene_1
  88. scene_2
  89. ...
  90. flow
  91. scene_1
  92. scene_2
  93. ...
  94. Args:
  95. root (str or ``pathlib.Path``): Root directory of the Sintel Dataset.
  96. split (string, optional): The dataset split, either "train" (default) or "test"
  97. pass_name (string, optional): The pass to use, either "clean" (default), "final", or "both". See link above for
  98. details on the different passes.
  99. transforms (callable, optional): A function/transform that takes in
  100. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  101. ``valid_flow_mask`` is expected for consistency with other datasets which
  102. return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`.
  103. loader (callable, optional): A function to load an image given its path.
  104. By default, it uses PIL as its image loader, but users could also pass in
  105. ``torchvision.io.decode_image`` for decoding image data into tensors directly.
  106. """
  107. def __init__(
  108. self,
  109. root: Union[str, Path],
  110. split: str = "train",
  111. pass_name: str = "clean",
  112. transforms: Optional[Callable] = None,
  113. loader: Callable[[str], Any] = default_loader,
  114. ) -> None:
  115. super().__init__(root=root, transforms=transforms, loader=loader)
  116. verify_str_arg(split, "split", valid_values=("train", "test"))
  117. verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both"))
  118. passes = ["clean", "final"] if pass_name == "both" else [pass_name]
  119. root = Path(root) / "Sintel"
  120. flow_root = root / "training" / "flow"
  121. for pass_name in passes:
  122. split_dir = "training" if split == "train" else split
  123. image_root = root / split_dir / pass_name
  124. for scene in os.listdir(image_root):
  125. image_list = sorted(glob(str(image_root / scene / "*.png")))
  126. for i in range(len(image_list) - 1):
  127. self._image_list += [[image_list[i], image_list[i + 1]]]
  128. if split == "train":
  129. self._flow_list += sorted(glob(str(flow_root / scene / "*.flo")))
  130. def __getitem__(self, index: int) -> Union[T1, T2]:
  131. """Return example at given index.
  132. Args:
  133. index(int): The index of the example to retrieve
  134. Returns:
  135. tuple: A 3-tuple with ``(img1, img2, flow)``.
  136. The flow is a numpy array of shape (2, H, W) and the images are PIL images.
  137. ``flow`` is None if ``split="test"``.
  138. If a valid flow mask is generated within the ``transforms`` parameter,
  139. a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned.
  140. """
  141. return super().__getitem__(index)
  142. def _read_flow(self, file_name: str) -> np.ndarray:
  143. return _read_flo(file_name)
  144. class KittiFlow(FlowDataset):
  145. """`KITTI <http://www.cvlibs.net/datasets/kitti/eval_scene_flow.php?benchmark=flow>`__ dataset for optical flow (2015).
  146. The dataset is expected to have the following structure: ::
  147. root
  148. KittiFlow
  149. testing
  150. image_2
  151. training
  152. image_2
  153. flow_occ
  154. Args:
  155. root (str or ``pathlib.Path``): Root directory of the KittiFlow Dataset.
  156. split (string, optional): The dataset split, either "train" (default) or "test"
  157. transforms (callable, optional): A function/transform that takes in
  158. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  159. loader (callable, optional): A function to load an image given its path.
  160. By default, it uses PIL as its image loader, but users could also pass in
  161. ``torchvision.io.decode_image`` for decoding image data into tensors directly.
  162. """
  163. _has_builtin_flow_mask = True
  164. def __init__(
  165. self,
  166. root: Union[str, Path],
  167. split: str = "train",
  168. transforms: Optional[Callable] = None,
  169. loader: Callable[[str], Any] = default_loader,
  170. ) -> None:
  171. super().__init__(root=root, transforms=transforms, loader=loader)
  172. verify_str_arg(split, "split", valid_values=("train", "test"))
  173. root = Path(root) / "KittiFlow" / (split + "ing")
  174. images1 = sorted(glob(str(root / "image_2" / "*_10.png")))
  175. images2 = sorted(glob(str(root / "image_2" / "*_11.png")))
  176. if not images1 or not images2:
  177. raise FileNotFoundError(
  178. "Could not find the Kitti flow images. Please make sure the directory structure is correct."
  179. )
  180. for img1, img2 in zip(images1, images2):
  181. self._image_list += [[img1, img2]]
  182. if split == "train":
  183. self._flow_list = sorted(glob(str(root / "flow_occ" / "*_10.png")))
  184. def __getitem__(self, index: int) -> Union[T1, T2]:
  185. """Return example at given index.
  186. Args:
  187. index(int): The index of the example to retrieve
  188. Returns:
  189. tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)``
  190. where ``valid_flow_mask`` is a numpy boolean mask of shape (H, W)
  191. indicating which flow values are valid. The flow is a numpy array of
  192. shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if
  193. ``split="test"``.
  194. """
  195. return super().__getitem__(index)
  196. def _read_flow(self, file_name: str) -> Tuple[np.ndarray, np.ndarray]:
  197. return _read_16bits_png_with_flow_and_valid_mask(file_name)
  198. class FlyingChairs(FlowDataset):
  199. """`FlyingChairs <https://lmb.informatik.uni-freiburg.de/resources/datasets/FlyingChairs.en.html#flyingchairs>`_ Dataset for optical flow.
  200. You will also need to download the FlyingChairs_train_val.txt file from the dataset page.
  201. The dataset is expected to have the following structure: ::
  202. root
  203. FlyingChairs
  204. data
  205. 00001_flow.flo
  206. 00001_img1.ppm
  207. 00001_img2.ppm
  208. ...
  209. FlyingChairs_train_val.txt
  210. Args:
  211. root (str or ``pathlib.Path``): Root directory of the FlyingChairs Dataset.
  212. split (string, optional): The dataset split, either "train" (default) or "val"
  213. transforms (callable, optional): A function/transform that takes in
  214. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  215. ``valid_flow_mask`` is expected for consistency with other datasets which
  216. return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`.
  217. """
  218. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  219. super().__init__(root=root, transforms=transforms)
  220. verify_str_arg(split, "split", valid_values=("train", "val"))
  221. root = Path(root) / "FlyingChairs"
  222. images = sorted(glob(str(root / "data" / "*.ppm")))
  223. flows = sorted(glob(str(root / "data" / "*.flo")))
  224. split_file_name = "FlyingChairs_train_val.txt"
  225. if not os.path.exists(root / split_file_name):
  226. raise FileNotFoundError(
  227. "The FlyingChairs_train_val.txt file was not found - please download it from the dataset page (see docstring)."
  228. )
  229. split_list = np.loadtxt(str(root / split_file_name), dtype=np.int32)
  230. for i in range(len(flows)):
  231. split_id = split_list[i]
  232. if (split == "train" and split_id == 1) or (split == "val" and split_id == 2):
  233. self._flow_list += [flows[i]]
  234. self._image_list += [[images[2 * i], images[2 * i + 1]]]
  235. def __getitem__(self, index: int) -> Union[T1, T2]:
  236. """Return example at given index.
  237. Args:
  238. index(int): The index of the example to retrieve
  239. Returns:
  240. tuple: A 3-tuple with ``(img1, img2, flow)``.
  241. The flow is a numpy array of shape (2, H, W) and the images are PIL images.
  242. ``flow`` is None if ``split="val"``.
  243. If a valid flow mask is generated within the ``transforms`` parameter,
  244. a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned.
  245. """
  246. return super().__getitem__(index)
  247. def _read_flow(self, file_name: str) -> np.ndarray:
  248. return _read_flo(file_name)
  249. class FlyingThings3D(FlowDataset):
  250. """`FlyingThings3D <https://lmb.informatik.uni-freiburg.de/resources/datasets/SceneFlowDatasets.en.html>`_ dataset for optical flow.
  251. The dataset is expected to have the following structure: ::
  252. root
  253. FlyingThings3D
  254. frames_cleanpass
  255. TEST
  256. TRAIN
  257. frames_finalpass
  258. TEST
  259. TRAIN
  260. optical_flow
  261. TEST
  262. TRAIN
  263. Args:
  264. root (str or ``pathlib.Path``): Root directory of the intel FlyingThings3D Dataset.
  265. split (string, optional): The dataset split, either "train" (default) or "test"
  266. pass_name (string, optional): The pass to use, either "clean" (default) or "final" or "both". See link above for
  267. details on the different passes.
  268. camera (string, optional): Which camera to return images from. Can be either "left" (default) or "right" or "both".
  269. transforms (callable, optional): A function/transform that takes in
  270. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  271. ``valid_flow_mask`` is expected for consistency with other datasets which
  272. return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`.
  273. loader (callable, optional): A function to load an image given its path.
  274. By default, it uses PIL as its image loader, but users could also pass in
  275. ``torchvision.io.decode_image`` for decoding image data into tensors directly.
  276. """
  277. def __init__(
  278. self,
  279. root: Union[str, Path],
  280. split: str = "train",
  281. pass_name: str = "clean",
  282. camera: str = "left",
  283. transforms: Optional[Callable] = None,
  284. loader: Callable[[str], Any] = default_loader,
  285. ) -> None:
  286. super().__init__(root=root, transforms=transforms, loader=loader)
  287. verify_str_arg(split, "split", valid_values=("train", "test"))
  288. split = split.upper()
  289. verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both"))
  290. passes = {
  291. "clean": ["frames_cleanpass"],
  292. "final": ["frames_finalpass"],
  293. "both": ["frames_cleanpass", "frames_finalpass"],
  294. }[pass_name]
  295. verify_str_arg(camera, "camera", valid_values=("left", "right", "both"))
  296. cameras = ["left", "right"] if camera == "both" else [camera]
  297. root = Path(root) / "FlyingThings3D"
  298. directions = ("into_future", "into_past")
  299. for pass_name, camera, direction in itertools.product(passes, cameras, directions):
  300. image_dirs = sorted(glob(str(root / pass_name / split / "*/*")))
  301. image_dirs = sorted(Path(image_dir) / camera for image_dir in image_dirs)
  302. flow_dirs = sorted(glob(str(root / "optical_flow" / split / "*/*")))
  303. flow_dirs = sorted(Path(flow_dir) / direction / camera for flow_dir in flow_dirs)
  304. if not image_dirs or not flow_dirs:
  305. raise FileNotFoundError(
  306. "Could not find the FlyingThings3D flow images. "
  307. "Please make sure the directory structure is correct."
  308. )
  309. for image_dir, flow_dir in zip(image_dirs, flow_dirs):
  310. images = sorted(glob(str(image_dir / "*.png")))
  311. flows = sorted(glob(str(flow_dir / "*.pfm")))
  312. for i in range(len(flows) - 1):
  313. if direction == "into_future":
  314. self._image_list += [[images[i], images[i + 1]]]
  315. self._flow_list += [flows[i]]
  316. elif direction == "into_past":
  317. self._image_list += [[images[i + 1], images[i]]]
  318. self._flow_list += [flows[i + 1]]
  319. def __getitem__(self, index: int) -> Union[T1, T2]:
  320. """Return example at given index.
  321. Args:
  322. index(int): The index of the example to retrieve
  323. Returns:
  324. tuple: A 3-tuple with ``(img1, img2, flow)``.
  325. The flow is a numpy array of shape (2, H, W) and the images are PIL images.
  326. ``flow`` is None if ``split="test"``.
  327. If a valid flow mask is generated within the ``transforms`` parameter,
  328. a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned.
  329. """
  330. return super().__getitem__(index)
  331. def _read_flow(self, file_name: str) -> np.ndarray:
  332. return _read_pfm(file_name)
  333. class HD1K(FlowDataset):
  334. """`HD1K <http://hci-benchmark.iwr.uni-heidelberg.de/>`__ dataset for optical flow.
  335. The dataset is expected to have the following structure: ::
  336. root
  337. hd1k
  338. hd1k_challenge
  339. image_2
  340. hd1k_flow_gt
  341. flow_occ
  342. hd1k_input
  343. image_2
  344. Args:
  345. root (str or ``pathlib.Path``): Root directory of the HD1K Dataset.
  346. split (string, optional): The dataset split, either "train" (default) or "test"
  347. transforms (callable, optional): A function/transform that takes in
  348. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  349. loader (callable, optional): A function to load an image given its path.
  350. By default, it uses PIL as its image loader, but users could also pass in
  351. ``torchvision.io.decode_image`` for decoding image data into tensors directly.
  352. """
  353. _has_builtin_flow_mask = True
  354. def __init__(
  355. self,
  356. root: Union[str, Path],
  357. split: str = "train",
  358. transforms: Optional[Callable] = None,
  359. loader: Callable[[str], Any] = default_loader,
  360. ) -> None:
  361. super().__init__(root=root, transforms=transforms, loader=loader)
  362. verify_str_arg(split, "split", valid_values=("train", "test"))
  363. root = Path(root) / "hd1k"
  364. if split == "train":
  365. # There are 36 "sequences" and we don't want seq i to overlap with seq i + 1, so we need this for loop
  366. for seq_idx in range(36):
  367. flows = sorted(glob(str(root / "hd1k_flow_gt" / "flow_occ" / f"{seq_idx:06d}_*.png")))
  368. images = sorted(glob(str(root / "hd1k_input" / "image_2" / f"{seq_idx:06d}_*.png")))
  369. for i in range(len(flows) - 1):
  370. self._flow_list += [flows[i]]
  371. self._image_list += [[images[i], images[i + 1]]]
  372. else:
  373. images1 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*10.png")))
  374. images2 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*11.png")))
  375. for image1, image2 in zip(images1, images2):
  376. self._image_list += [[image1, image2]]
  377. if not self._image_list:
  378. raise FileNotFoundError(
  379. "Could not find the HD1K images. Please make sure the directory structure is correct."
  380. )
  381. def _read_flow(self, file_name: str) -> Tuple[np.ndarray, np.ndarray]:
  382. return _read_16bits_png_with_flow_and_valid_mask(file_name)
  383. def __getitem__(self, index: int) -> Union[T1, T2]:
  384. """Return example at given index.
  385. Args:
  386. index(int): The index of the example to retrieve
  387. Returns:
  388. tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` where ``valid_flow_mask``
  389. is a numpy boolean mask of shape (H, W)
  390. indicating which flow values are valid. The flow is a numpy array of
  391. shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if
  392. ``split="test"``.
  393. """
  394. return super().__getitem__(index)
  395. def _read_flo(file_name: str) -> np.ndarray:
  396. """Read .flo file in Middlebury format"""
  397. # Code adapted from:
  398. # http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
  399. # Everything needs to be in little Endian according to
  400. # https://vision.middlebury.edu/flow/code/flow-code/README.txt
  401. with open(file_name, "rb") as f:
  402. magic = np.fromfile(f, "c", count=4).tobytes()
  403. if magic != b"PIEH":
  404. raise ValueError("Magic number incorrect. Invalid .flo file")
  405. w = int(np.fromfile(f, "<i4", count=1))
  406. h = int(np.fromfile(f, "<i4", count=1))
  407. data = np.fromfile(f, "<f4", count=2 * w * h)
  408. return data.reshape(h, w, 2).transpose(2, 0, 1)
  409. def _read_16bits_png_with_flow_and_valid_mask(file_name: str) -> Tuple[np.ndarray, np.ndarray]:
  410. flow_and_valid = decode_png(read_file(file_name)).to(torch.float32)
  411. flow, valid_flow_mask = flow_and_valid[:2, :, :], flow_and_valid[2, :, :]
  412. flow = (flow - 2**15) / 64 # This conversion is explained somewhere on the kitti archive
  413. valid_flow_mask = valid_flow_mask.bool()
  414. # For consistency with other datasets, we convert to numpy
  415. return flow.numpy(), valid_flow_mask.numpy()
Tip!

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

Comments

Loading...