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

_stereo_matching.py 48 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
  1. import functools
  2. import json
  3. import os
  4. import random
  5. import shutil
  6. from abc import ABC, abstractmethod
  7. from glob import glob
  8. from pathlib import Path
  9. from typing import Callable, cast, List, Optional, Tuple, Union
  10. import numpy as np
  11. from PIL import Image
  12. from .utils import _read_pfm, download_and_extract_archive, verify_str_arg
  13. from .vision import VisionDataset
  14. T1 = Tuple[Image.Image, Image.Image, Optional[np.ndarray], np.ndarray]
  15. T2 = Tuple[Image.Image, Image.Image, Optional[np.ndarray]]
  16. __all__ = ()
  17. _read_pfm_file = functools.partial(_read_pfm, slice_channels=1)
  18. class StereoMatchingDataset(ABC, VisionDataset):
  19. """Base interface for Stereo matching datasets"""
  20. _has_built_in_disparity_mask = False
  21. def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None) -> None:
  22. """
  23. Args:
  24. root(str): Root directory of the dataset.
  25. transforms(callable, optional): A function/transform that takes in Tuples of
  26. (images, disparities, valid_masks) and returns a transformed version of each of them.
  27. images is a Tuple of (``PIL.Image``, ``PIL.Image``)
  28. disparities is a Tuple of (``np.ndarray``, ``np.ndarray``) with shape (1, H, W)
  29. valid_masks is a Tuple of (``np.ndarray``, ``np.ndarray``) with shape (H, W)
  30. In some cases, when a dataset does not provide disparities, the ``disparities`` and
  31. ``valid_masks`` can be Tuples containing None values.
  32. For training splits generally the datasets provide a minimal guarantee of
  33. images: (``PIL.Image``, ``PIL.Image``)
  34. disparities: (``np.ndarray``, ``None``) with shape (1, H, W)
  35. Optionally, based on the dataset, it can return a ``mask`` as well:
  36. valid_masks: (``np.ndarray | None``, ``None``) with shape (H, W)
  37. For some test splits, the datasets provides outputs that look like:
  38. imgaes: (``PIL.Image``, ``PIL.Image``)
  39. disparities: (``None``, ``None``)
  40. Optionally, based on the dataset, it can return a ``mask`` as well:
  41. valid_masks: (``None``, ``None``)
  42. """
  43. super().__init__(root=root)
  44. self.transforms = transforms
  45. self._images = [] # type: ignore
  46. self._disparities = [] # type: ignore
  47. def _read_img(self, file_path: Union[str, Path]) -> Image.Image:
  48. img = Image.open(file_path)
  49. if img.mode != "RGB":
  50. img = img.convert("RGB") # type: ignore [assignment]
  51. return img
  52. def _scan_pairs(
  53. self,
  54. paths_left_pattern: str,
  55. paths_right_pattern: Optional[str] = None,
  56. ) -> List[Tuple[str, Optional[str]]]:
  57. left_paths = list(sorted(glob(paths_left_pattern)))
  58. right_paths: List[Union[None, str]]
  59. if paths_right_pattern:
  60. right_paths = list(sorted(glob(paths_right_pattern)))
  61. else:
  62. right_paths = list(None for _ in left_paths)
  63. if not left_paths:
  64. raise FileNotFoundError(f"Could not find any files matching the patterns: {paths_left_pattern}")
  65. if not right_paths:
  66. raise FileNotFoundError(f"Could not find any files matching the patterns: {paths_right_pattern}")
  67. if len(left_paths) != len(right_paths):
  68. raise ValueError(
  69. f"Found {len(left_paths)} left files but {len(right_paths)} right files using:\n "
  70. f"left pattern: {paths_left_pattern}\n"
  71. f"right pattern: {paths_right_pattern}\n"
  72. )
  73. paths = list((left, right) for left, right in zip(left_paths, right_paths))
  74. return paths
  75. @abstractmethod
  76. def _read_disparity(self, file_path: str) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
  77. # function that returns a disparity map and an occlusion map
  78. pass
  79. def __getitem__(self, index: int) -> Union[T1, T2]:
  80. """Return example at given index.
  81. Args:
  82. index(int): The index of the example to retrieve
  83. Returns:
  84. tuple: A 3 or 4-tuple with ``(img_left, img_right, disparity, Optional[valid_mask])`` where ``valid_mask``
  85. can be a numpy boolean mask of shape (H, W) if the dataset provides a file
  86. indicating which disparity pixels are valid. The disparity is a numpy array of
  87. shape (1, H, W) and the images are PIL images. ``disparity`` is None for
  88. datasets on which for ``split="test"`` the authors did not provide annotations.
  89. """
  90. img_left = self._read_img(self._images[index][0])
  91. img_right = self._read_img(self._images[index][1])
  92. dsp_map_left, valid_mask_left = self._read_disparity(self._disparities[index][0])
  93. dsp_map_right, valid_mask_right = self._read_disparity(self._disparities[index][1])
  94. imgs = (img_left, img_right)
  95. dsp_maps = (dsp_map_left, dsp_map_right)
  96. valid_masks = (valid_mask_left, valid_mask_right)
  97. if self.transforms is not None:
  98. (
  99. imgs,
  100. dsp_maps,
  101. valid_masks,
  102. ) = self.transforms(imgs, dsp_maps, valid_masks)
  103. if self._has_built_in_disparity_mask or valid_masks[0] is not None:
  104. return imgs[0], imgs[1], dsp_maps[0], cast(np.ndarray, valid_masks[0])
  105. else:
  106. return imgs[0], imgs[1], dsp_maps[0]
  107. def __len__(self) -> int:
  108. return len(self._images)
  109. class CarlaStereo(StereoMatchingDataset):
  110. """
  111. Carla simulator data linked in the `CREStereo github repo <https://github.com/megvii-research/CREStereo>`_.
  112. The dataset is expected to have the following structure: ::
  113. root
  114. carla-highres
  115. trainingF
  116. scene1
  117. img0.png
  118. img1.png
  119. disp0GT.pfm
  120. disp1GT.pfm
  121. calib.txt
  122. scene2
  123. img0.png
  124. img1.png
  125. disp0GT.pfm
  126. disp1GT.pfm
  127. calib.txt
  128. ...
  129. Args:
  130. root (str or ``pathlib.Path``): Root directory where `carla-highres` is located.
  131. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  132. """
  133. def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None) -> None:
  134. super().__init__(root, transforms)
  135. root = Path(root) / "carla-highres"
  136. left_image_pattern = str(root / "trainingF" / "*" / "im0.png")
  137. right_image_pattern = str(root / "trainingF" / "*" / "im1.png")
  138. imgs = self._scan_pairs(left_image_pattern, right_image_pattern)
  139. self._images = imgs
  140. left_disparity_pattern = str(root / "trainingF" / "*" / "disp0GT.pfm")
  141. right_disparity_pattern = str(root / "trainingF" / "*" / "disp1GT.pfm")
  142. disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  143. self._disparities = disparities
  144. def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
  145. disparity_map = _read_pfm_file(file_path)
  146. disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
  147. valid_mask = None
  148. return disparity_map, valid_mask
  149. def __getitem__(self, index: int) -> T1:
  150. """Return example at given index.
  151. Args:
  152. index(int): The index of the example to retrieve
  153. Returns:
  154. tuple: A 3-tuple with ``(img_left, img_right, disparity)``.
  155. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  156. If a ``valid_mask`` is generated within the ``transforms`` parameter,
  157. a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  158. """
  159. return cast(T1, super().__getitem__(index))
  160. class Kitti2012Stereo(StereoMatchingDataset):
  161. """
  162. KITTI dataset from the `2012 stereo evaluation benchmark <http://www.cvlibs.net/datasets/kitti/eval_stereo_flow.php>`_.
  163. Uses the RGB images for consistency with KITTI 2015.
  164. The dataset is expected to have the following structure: ::
  165. root
  166. Kitti2012
  167. testing
  168. colored_0
  169. 1_10.png
  170. 2_10.png
  171. ...
  172. colored_1
  173. 1_10.png
  174. 2_10.png
  175. ...
  176. training
  177. colored_0
  178. 1_10.png
  179. 2_10.png
  180. ...
  181. colored_1
  182. 1_10.png
  183. 2_10.png
  184. ...
  185. disp_noc
  186. 1.png
  187. 2.png
  188. ...
  189. calib
  190. Args:
  191. root (str or ``pathlib.Path``): Root directory where `Kitti2012` is located.
  192. split (string, optional): The dataset split of scenes, either "train" (default) or "test".
  193. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  194. """
  195. _has_built_in_disparity_mask = True
  196. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  197. super().__init__(root, transforms)
  198. verify_str_arg(split, "split", valid_values=("train", "test"))
  199. root = Path(root) / "Kitti2012" / (split + "ing")
  200. left_img_pattern = str(root / "colored_0" / "*_10.png")
  201. right_img_pattern = str(root / "colored_1" / "*_10.png")
  202. self._images = self._scan_pairs(left_img_pattern, right_img_pattern)
  203. if split == "train":
  204. disparity_pattern = str(root / "disp_noc" / "*.png")
  205. self._disparities = self._scan_pairs(disparity_pattern, None)
  206. else:
  207. self._disparities = list((None, None) for _ in self._images)
  208. def _read_disparity(self, file_path: str) -> Tuple[Optional[np.ndarray], None]:
  209. # test split has no disparity maps
  210. if file_path is None:
  211. return None, None
  212. disparity_map = np.asarray(Image.open(file_path)) / 256.0
  213. # unsqueeze the disparity map into (C, H, W) format
  214. disparity_map = disparity_map[None, :, :]
  215. valid_mask = None
  216. return disparity_map, valid_mask
  217. def __getitem__(self, index: int) -> T1:
  218. """Return example at given index.
  219. Args:
  220. index(int): The index of the example to retrieve
  221. Returns:
  222. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  223. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  224. ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not
  225. generate a valid mask.
  226. Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test.
  227. """
  228. return cast(T1, super().__getitem__(index))
  229. class Kitti2015Stereo(StereoMatchingDataset):
  230. """
  231. KITTI dataset from the `2015 stereo evaluation benchmark <http://www.cvlibs.net/datasets/kitti/eval_scene_flow.php>`_.
  232. The dataset is expected to have the following structure: ::
  233. root
  234. Kitti2015
  235. testing
  236. image_2
  237. img1.png
  238. img2.png
  239. ...
  240. image_3
  241. img1.png
  242. img2.png
  243. ...
  244. training
  245. image_2
  246. img1.png
  247. img2.png
  248. ...
  249. image_3
  250. img1.png
  251. img2.png
  252. ...
  253. disp_occ_0
  254. img1.png
  255. img2.png
  256. ...
  257. disp_occ_1
  258. img1.png
  259. img2.png
  260. ...
  261. calib
  262. Args:
  263. root (str or ``pathlib.Path``): Root directory where `Kitti2015` is located.
  264. split (string, optional): The dataset split of scenes, either "train" (default) or "test".
  265. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  266. """
  267. _has_built_in_disparity_mask = True
  268. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  269. super().__init__(root, transforms)
  270. verify_str_arg(split, "split", valid_values=("train", "test"))
  271. root = Path(root) / "Kitti2015" / (split + "ing")
  272. left_img_pattern = str(root / "image_2" / "*.png")
  273. right_img_pattern = str(root / "image_3" / "*.png")
  274. self._images = self._scan_pairs(left_img_pattern, right_img_pattern)
  275. if split == "train":
  276. left_disparity_pattern = str(root / "disp_occ_0" / "*.png")
  277. right_disparity_pattern = str(root / "disp_occ_1" / "*.png")
  278. self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  279. else:
  280. self._disparities = list((None, None) for _ in self._images)
  281. def _read_disparity(self, file_path: str) -> Tuple[Optional[np.ndarray], None]:
  282. # test split has no disparity maps
  283. if file_path is None:
  284. return None, None
  285. disparity_map = np.asarray(Image.open(file_path)) / 256.0
  286. # unsqueeze the disparity map into (C, H, W) format
  287. disparity_map = disparity_map[None, :, :]
  288. valid_mask = None
  289. return disparity_map, valid_mask
  290. def __getitem__(self, index: int) -> T1:
  291. """Return example at given index.
  292. Args:
  293. index(int): The index of the example to retrieve
  294. Returns:
  295. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  296. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  297. ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not
  298. generate a valid mask.
  299. Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test.
  300. """
  301. return cast(T1, super().__getitem__(index))
  302. class Middlebury2014Stereo(StereoMatchingDataset):
  303. """Publicly available scenes from the Middlebury dataset `2014 version <https://vision.middlebury.edu/stereo/data/scenes2014/>`.
  304. The dataset mostly follows the original format, without containing the ambient subdirectories. : ::
  305. root
  306. Middlebury2014
  307. train
  308. scene1-{perfect,imperfect}
  309. calib.txt
  310. im{0,1}.png
  311. im1E.png
  312. im1L.png
  313. disp{0,1}.pfm
  314. disp{0,1}-n.png
  315. disp{0,1}-sd.pfm
  316. disp{0,1}y.pfm
  317. scene2-{perfect,imperfect}
  318. calib.txt
  319. im{0,1}.png
  320. im1E.png
  321. im1L.png
  322. disp{0,1}.pfm
  323. disp{0,1}-n.png
  324. disp{0,1}-sd.pfm
  325. disp{0,1}y.pfm
  326. ...
  327. additional
  328. scene1-{perfect,imperfect}
  329. calib.txt
  330. im{0,1}.png
  331. im1E.png
  332. im1L.png
  333. disp{0,1}.pfm
  334. disp{0,1}-n.png
  335. disp{0,1}-sd.pfm
  336. disp{0,1}y.pfm
  337. ...
  338. test
  339. scene1
  340. calib.txt
  341. im{0,1}.png
  342. scene2
  343. calib.txt
  344. im{0,1}.png
  345. ...
  346. Args:
  347. root (str or ``pathlib.Path``): Root directory of the Middleburry 2014 Dataset.
  348. split (string, optional): The dataset split of scenes, either "train" (default), "test", or "additional"
  349. use_ambient_views (boolean, optional): Whether to use different expose or lightning views when possible.
  350. The dataset samples with equal probability between ``[im1.png, im1E.png, im1L.png]``.
  351. calibration (string, optional): Whether or not to use the calibrated (default) or uncalibrated scenes.
  352. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  353. download (boolean, optional): Whether or not to download the dataset in the ``root`` directory.
  354. """
  355. splits = {
  356. "train": [
  357. "Adirondack",
  358. "Jadeplant",
  359. "Motorcycle",
  360. "Piano",
  361. "Pipes",
  362. "Playroom",
  363. "Playtable",
  364. "Recycle",
  365. "Shelves",
  366. "Vintage",
  367. ],
  368. "additional": [
  369. "Backpack",
  370. "Bicycle1",
  371. "Cable",
  372. "Classroom1",
  373. "Couch",
  374. "Flowers",
  375. "Mask",
  376. "Shopvac",
  377. "Sticks",
  378. "Storage",
  379. "Sword1",
  380. "Sword2",
  381. "Umbrella",
  382. ],
  383. "test": [
  384. "Plants",
  385. "Classroom2E",
  386. "Classroom2",
  387. "Australia",
  388. "DjembeL",
  389. "CrusadeP",
  390. "Crusade",
  391. "Hoops",
  392. "Bicycle2",
  393. "Staircase",
  394. "Newkuba",
  395. "AustraliaP",
  396. "Djembe",
  397. "Livingroom",
  398. "Computer",
  399. ],
  400. }
  401. _has_built_in_disparity_mask = True
  402. def __init__(
  403. self,
  404. root: Union[str, Path],
  405. split: str = "train",
  406. calibration: Optional[str] = "perfect",
  407. use_ambient_views: bool = False,
  408. transforms: Optional[Callable] = None,
  409. download: bool = False,
  410. ) -> None:
  411. super().__init__(root, transforms)
  412. verify_str_arg(split, "split", valid_values=("train", "test", "additional"))
  413. self.split = split
  414. if calibration:
  415. verify_str_arg(calibration, "calibration", valid_values=("perfect", "imperfect", "both", None)) # type: ignore
  416. if split == "test":
  417. raise ValueError("Split 'test' has only no calibration settings, please set `calibration=None`.")
  418. else:
  419. if split != "test":
  420. raise ValueError(
  421. f"Split '{split}' has calibration settings, however None was provided as an argument."
  422. f"\nSetting calibration to 'perfect' for split '{split}'. Available calibration settings are: 'perfect', 'imperfect', 'both'.",
  423. )
  424. if download:
  425. self._download_dataset(root)
  426. root = Path(root) / "Middlebury2014"
  427. if not os.path.exists(root / split):
  428. raise FileNotFoundError(f"The {split} directory was not found in the provided root directory")
  429. split_scenes = self.splits[split]
  430. # check that the provided root folder contains the scene splits
  431. if not any(
  432. # using startswith to account for perfect / imperfect calibrartion
  433. scene.startswith(s)
  434. for scene in os.listdir(root / split)
  435. for s in split_scenes
  436. ):
  437. raise FileNotFoundError(f"Provided root folder does not contain any scenes from the {split} split.")
  438. calibrartion_suffixes = {
  439. None: [""],
  440. "perfect": ["-perfect"],
  441. "imperfect": ["-imperfect"],
  442. "both": ["-perfect", "-imperfect"],
  443. }[calibration]
  444. for calibration_suffix in calibrartion_suffixes:
  445. scene_pattern = "*" + calibration_suffix
  446. left_img_pattern = str(root / split / scene_pattern / "im0.png")
  447. right_img_pattern = str(root / split / scene_pattern / "im1.png")
  448. self._images += self._scan_pairs(left_img_pattern, right_img_pattern)
  449. if split == "test":
  450. self._disparities = list((None, None) for _ in self._images)
  451. else:
  452. left_dispartity_pattern = str(root / split / scene_pattern / "disp0.pfm")
  453. right_dispartity_pattern = str(root / split / scene_pattern / "disp1.pfm")
  454. self._disparities += self._scan_pairs(left_dispartity_pattern, right_dispartity_pattern)
  455. self.use_ambient_views = use_ambient_views
  456. def _read_img(self, file_path: Union[str, Path]) -> Image.Image:
  457. """
  458. Function that reads either the original right image or an augmented view when ``use_ambient_views`` is True.
  459. When ``use_ambient_views`` is True, the dataset will return at random one of ``[im1.png, im1E.png, im1L.png]``
  460. as the right image.
  461. """
  462. ambient_file_paths: List[Union[str, Path]] # make mypy happy
  463. if not isinstance(file_path, Path):
  464. file_path = Path(file_path)
  465. if file_path.name == "im1.png" and self.use_ambient_views:
  466. base_path = file_path.parent
  467. # initialize sampleable container
  468. ambient_file_paths = list(base_path / view_name for view_name in ["im1E.png", "im1L.png"])
  469. # double check that we're not going to try to read from an invalid file path
  470. ambient_file_paths = list(filter(lambda p: os.path.exists(p), ambient_file_paths))
  471. # keep the original image as an option as well for uniform sampling between base views
  472. ambient_file_paths.append(file_path)
  473. file_path = random.choice(ambient_file_paths) # type: ignore
  474. return super()._read_img(file_path)
  475. def _read_disparity(self, file_path: str) -> Union[Tuple[None, None], Tuple[np.ndarray, np.ndarray]]:
  476. # test split has not disparity maps
  477. if file_path is None:
  478. return None, None
  479. disparity_map = _read_pfm_file(file_path)
  480. disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
  481. disparity_map[disparity_map == np.inf] = 0 # remove infinite disparities
  482. valid_mask = (disparity_map > 0).squeeze(0) # mask out invalid disparities
  483. return disparity_map, valid_mask
  484. def _download_dataset(self, root: Union[str, Path]) -> None:
  485. base_url = "https://vision.middlebury.edu/stereo/data/scenes2014/zip"
  486. # train and additional splits have 2 different calibration settings
  487. root = Path(root) / "Middlebury2014"
  488. split_name = self.split
  489. if split_name != "test":
  490. for split_scene in self.splits[split_name]:
  491. split_root = root / split_name
  492. for calibration in ["perfect", "imperfect"]:
  493. scene_name = f"{split_scene}-{calibration}"
  494. scene_url = f"{base_url}/{scene_name}.zip"
  495. # download the scene only if it doesn't exist
  496. if not (split_root / scene_name).exists():
  497. download_and_extract_archive(
  498. url=scene_url,
  499. filename=f"{scene_name}.zip",
  500. download_root=str(split_root),
  501. remove_finished=True,
  502. )
  503. else:
  504. os.makedirs(root / "test")
  505. if any(s not in os.listdir(root / "test") for s in self.splits["test"]):
  506. # test split is downloaded from a different location
  507. test_set_url = "https://vision.middlebury.edu/stereo/submit3/zip/MiddEval3-data-F.zip"
  508. # the unzip is going to produce a directory MiddEval3 with two subdirectories trainingF and testF
  509. # we want to move the contents from testF into the directory
  510. download_and_extract_archive(url=test_set_url, download_root=str(root), remove_finished=True)
  511. for scene_dir, scene_names, _ in os.walk(str(root / "MiddEval3/testF")):
  512. for scene in scene_names:
  513. scene_dst_dir = root / "test"
  514. scene_src_dir = Path(scene_dir) / scene
  515. os.makedirs(scene_dst_dir, exist_ok=True)
  516. shutil.move(str(scene_src_dir), str(scene_dst_dir))
  517. # cleanup MiddEval3 directory
  518. shutil.rmtree(str(root / "MiddEval3"))
  519. def __getitem__(self, index: int) -> T2:
  520. """Return example at given index.
  521. Args:
  522. index(int): The index of the example to retrieve
  523. Returns:
  524. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  525. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  526. ``valid_mask`` is implicitly ``None`` for `split=test`.
  527. """
  528. return cast(T2, super().__getitem__(index))
  529. class CREStereo(StereoMatchingDataset):
  530. """Synthetic dataset used in training the `CREStereo <https://arxiv.org/pdf/2203.11483.pdf>`_ architecture.
  531. Dataset details on the official paper `repo <https://github.com/megvii-research/CREStereo>`_.
  532. The dataset is expected to have the following structure: ::
  533. root
  534. CREStereo
  535. tree
  536. img1_left.jpg
  537. img1_right.jpg
  538. img1_left.disp.jpg
  539. img1_right.disp.jpg
  540. img2_left.jpg
  541. img2_right.jpg
  542. img2_left.disp.jpg
  543. img2_right.disp.jpg
  544. ...
  545. shapenet
  546. img1_left.jpg
  547. img1_right.jpg
  548. img1_left.disp.jpg
  549. img1_right.disp.jpg
  550. ...
  551. reflective
  552. img1_left.jpg
  553. img1_right.jpg
  554. img1_left.disp.jpg
  555. img1_right.disp.jpg
  556. ...
  557. hole
  558. img1_left.jpg
  559. img1_right.jpg
  560. img1_left.disp.jpg
  561. img1_right.disp.jpg
  562. ...
  563. Args:
  564. root (str): Root directory of the dataset.
  565. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  566. """
  567. _has_built_in_disparity_mask = True
  568. def __init__(
  569. self,
  570. root: Union[str, Path],
  571. transforms: Optional[Callable] = None,
  572. ) -> None:
  573. super().__init__(root, transforms)
  574. root = Path(root) / "CREStereo"
  575. dirs = ["shapenet", "reflective", "tree", "hole"]
  576. for s in dirs:
  577. left_image_pattern = str(root / s / "*_left.jpg")
  578. right_image_pattern = str(root / s / "*_right.jpg")
  579. imgs = self._scan_pairs(left_image_pattern, right_image_pattern)
  580. self._images += imgs
  581. left_disparity_pattern = str(root / s / "*_left.disp.png")
  582. right_disparity_pattern = str(root / s / "*_right.disp.png")
  583. disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  584. self._disparities += disparities
  585. def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
  586. disparity_map = np.asarray(Image.open(file_path), dtype=np.float32)
  587. # unsqueeze the disparity map into (C, H, W) format
  588. disparity_map = disparity_map[None, :, :] / 32.0
  589. valid_mask = None
  590. return disparity_map, valid_mask
  591. def __getitem__(self, index: int) -> T1:
  592. """Return example at given index.
  593. Args:
  594. index(int): The index of the example to retrieve
  595. Returns:
  596. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  597. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  598. ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not
  599. generate a valid mask.
  600. """
  601. return cast(T1, super().__getitem__(index))
  602. class FallingThingsStereo(StereoMatchingDataset):
  603. """`FallingThings <https://research.nvidia.com/publication/2018-06_falling-things-synthetic-dataset-3d-object-detection-and-pose-estimation>`_ dataset.
  604. The dataset is expected to have the following structure: ::
  605. root
  606. FallingThings
  607. single
  608. dir1
  609. scene1
  610. _object_settings.json
  611. _camera_settings.json
  612. image1.left.depth.png
  613. image1.right.depth.png
  614. image1.left.jpg
  615. image1.right.jpg
  616. image2.left.depth.png
  617. image2.right.depth.png
  618. image2.left.jpg
  619. image2.right
  620. ...
  621. scene2
  622. ...
  623. mixed
  624. scene1
  625. _object_settings.json
  626. _camera_settings.json
  627. image1.left.depth.png
  628. image1.right.depth.png
  629. image1.left.jpg
  630. image1.right.jpg
  631. image2.left.depth.png
  632. image2.right.depth.png
  633. image2.left.jpg
  634. image2.right
  635. ...
  636. scene2
  637. ...
  638. Args:
  639. root (str or ``pathlib.Path``): Root directory where FallingThings is located.
  640. variant (string): Which variant to use. Either "single", "mixed", or "both".
  641. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  642. """
  643. def __init__(self, root: Union[str, Path], variant: str = "single", transforms: Optional[Callable] = None) -> None:
  644. super().__init__(root, transforms)
  645. root = Path(root) / "FallingThings"
  646. verify_str_arg(variant, "variant", valid_values=("single", "mixed", "both"))
  647. variants = {
  648. "single": ["single"],
  649. "mixed": ["mixed"],
  650. "both": ["single", "mixed"],
  651. }[variant]
  652. split_prefix = {
  653. "single": Path("*") / "*",
  654. "mixed": Path("*"),
  655. }
  656. for s in variants:
  657. left_img_pattern = str(root / s / split_prefix[s] / "*.left.jpg")
  658. right_img_pattern = str(root / s / split_prefix[s] / "*.right.jpg")
  659. self._images += self._scan_pairs(left_img_pattern, right_img_pattern)
  660. left_disparity_pattern = str(root / s / split_prefix[s] / "*.left.depth.png")
  661. right_disparity_pattern = str(root / s / split_prefix[s] / "*.right.depth.png")
  662. self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  663. def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
  664. # (H, W) image
  665. depth = np.asarray(Image.open(file_path))
  666. # as per https://research.nvidia.com/sites/default/files/pubs/2018-06_Falling-Things/readme_0.txt
  667. # in order to extract disparity from depth maps
  668. camera_settings_path = Path(file_path).parent / "_camera_settings.json"
  669. with open(camera_settings_path, "r") as f:
  670. # inverse of depth-from-disparity equation: depth = (baseline * focal) / (disparity * pixel_constant)
  671. intrinsics = json.load(f)
  672. focal = intrinsics["camera_settings"][0]["intrinsic_settings"]["fx"]
  673. baseline, pixel_constant = 6, 100 # pixel constant is inverted
  674. disparity_map = (baseline * focal * pixel_constant) / depth.astype(np.float32)
  675. # unsqueeze disparity to (C, H, W)
  676. disparity_map = disparity_map[None, :, :]
  677. valid_mask = None
  678. return disparity_map, valid_mask
  679. def __getitem__(self, index: int) -> T1:
  680. """Return example at given index.
  681. Args:
  682. index(int): The index of the example to retrieve
  683. Returns:
  684. tuple: A 3-tuple with ``(img_left, img_right, disparity)``.
  685. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  686. If a ``valid_mask`` is generated within the ``transforms`` parameter,
  687. a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  688. """
  689. return cast(T1, super().__getitem__(index))
  690. class SceneFlowStereo(StereoMatchingDataset):
  691. """Dataset interface for `Scene Flow <https://lmb.informatik.uni-freiburg.de/resources/datasets/SceneFlowDatasets.en.html>`_ datasets.
  692. This interface provides access to the `FlyingThings3D, `Monkaa` and `Driving` datasets.
  693. The dataset is expected to have the following structure: ::
  694. root
  695. SceneFlow
  696. Monkaa
  697. frames_cleanpass
  698. scene1
  699. left
  700. img1.png
  701. img2.png
  702. right
  703. img1.png
  704. img2.png
  705. scene2
  706. left
  707. img1.png
  708. img2.png
  709. right
  710. img1.png
  711. img2.png
  712. frames_finalpass
  713. scene1
  714. left
  715. img1.png
  716. img2.png
  717. right
  718. img1.png
  719. img2.png
  720. ...
  721. ...
  722. disparity
  723. scene1
  724. left
  725. img1.pfm
  726. img2.pfm
  727. right
  728. img1.pfm
  729. img2.pfm
  730. FlyingThings3D
  731. ...
  732. ...
  733. Args:
  734. root (str or ``pathlib.Path``): Root directory where SceneFlow is located.
  735. variant (string): Which dataset variant to user, "FlyingThings3D" (default), "Monkaa" or "Driving".
  736. pass_name (string): Which pass to use, "clean" (default), "final" or "both".
  737. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  738. """
  739. def __init__(
  740. self,
  741. root: Union[str, Path],
  742. variant: str = "FlyingThings3D",
  743. pass_name: str = "clean",
  744. transforms: Optional[Callable] = None,
  745. ) -> None:
  746. super().__init__(root, transforms)
  747. root = Path(root) / "SceneFlow"
  748. verify_str_arg(variant, "variant", valid_values=("FlyingThings3D", "Driving", "Monkaa"))
  749. verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both"))
  750. passes = {
  751. "clean": ["frames_cleanpass"],
  752. "final": ["frames_finalpass"],
  753. "both": ["frames_cleanpass", "frames_finalpass"],
  754. }[pass_name]
  755. root = root / variant
  756. prefix_directories = {
  757. "Monkaa": Path("*"),
  758. "FlyingThings3D": Path("*") / "*" / "*",
  759. "Driving": Path("*") / "*" / "*",
  760. }
  761. for p in passes:
  762. left_image_pattern = str(root / p / prefix_directories[variant] / "left" / "*.png")
  763. right_image_pattern = str(root / p / prefix_directories[variant] / "right" / "*.png")
  764. self._images += self._scan_pairs(left_image_pattern, right_image_pattern)
  765. left_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "left" / "*.pfm")
  766. right_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "right" / "*.pfm")
  767. self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  768. def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
  769. disparity_map = _read_pfm_file(file_path)
  770. disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
  771. valid_mask = None
  772. return disparity_map, valid_mask
  773. def __getitem__(self, index: int) -> T1:
  774. """Return example at given index.
  775. Args:
  776. index(int): The index of the example to retrieve
  777. Returns:
  778. tuple: A 3-tuple with ``(img_left, img_right, disparity)``.
  779. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  780. If a ``valid_mask`` is generated within the ``transforms`` parameter,
  781. a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  782. """
  783. return cast(T1, super().__getitem__(index))
  784. class SintelStereo(StereoMatchingDataset):
  785. """Sintel `Stereo Dataset <http://sintel.is.tue.mpg.de/stereo>`_.
  786. The dataset is expected to have the following structure: ::
  787. root
  788. Sintel
  789. training
  790. final_left
  791. scene1
  792. img1.png
  793. img2.png
  794. ...
  795. ...
  796. final_right
  797. scene2
  798. img1.png
  799. img2.png
  800. ...
  801. ...
  802. disparities
  803. scene1
  804. img1.png
  805. img2.png
  806. ...
  807. ...
  808. occlusions
  809. scene1
  810. img1.png
  811. img2.png
  812. ...
  813. ...
  814. outofframe
  815. scene1
  816. img1.png
  817. img2.png
  818. ...
  819. ...
  820. Args:
  821. root (str or ``pathlib.Path``): Root directory where Sintel Stereo is located.
  822. pass_name (string): The name of the pass to use, either "final", "clean" or "both".
  823. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  824. """
  825. _has_built_in_disparity_mask = True
  826. def __init__(self, root: Union[str, Path], pass_name: str = "final", transforms: Optional[Callable] = None) -> None:
  827. super().__init__(root, transforms)
  828. verify_str_arg(pass_name, "pass_name", valid_values=("final", "clean", "both"))
  829. root = Path(root) / "Sintel"
  830. pass_names = {
  831. "final": ["final"],
  832. "clean": ["clean"],
  833. "both": ["final", "clean"],
  834. }[pass_name]
  835. for p in pass_names:
  836. left_img_pattern = str(root / "training" / f"{p}_left" / "*" / "*.png")
  837. right_img_pattern = str(root / "training" / f"{p}_right" / "*" / "*.png")
  838. self._images += self._scan_pairs(left_img_pattern, right_img_pattern)
  839. disparity_pattern = str(root / "training" / "disparities" / "*" / "*.png")
  840. self._disparities += self._scan_pairs(disparity_pattern, None)
  841. def _get_occlussion_mask_paths(self, file_path: str) -> Tuple[str, str]:
  842. # helper function to get the occlusion mask paths
  843. # a path will look like .../.../.../training/disparities/scene1/img1.png
  844. # we want to get something like .../.../.../training/occlusions/scene1/img1.png
  845. fpath = Path(file_path)
  846. basename = fpath.name
  847. scenedir = fpath.parent
  848. # the parent of the scenedir is actually the disparity dir
  849. sampledir = scenedir.parent.parent
  850. occlusion_path = str(sampledir / "occlusions" / scenedir.name / basename)
  851. outofframe_path = str(sampledir / "outofframe" / scenedir.name / basename)
  852. if not os.path.exists(occlusion_path):
  853. raise FileNotFoundError(f"Occlusion mask {occlusion_path} does not exist")
  854. if not os.path.exists(outofframe_path):
  855. raise FileNotFoundError(f"Out of frame mask {outofframe_path} does not exist")
  856. return occlusion_path, outofframe_path
  857. def _read_disparity(self, file_path: str) -> Union[Tuple[None, None], Tuple[np.ndarray, np.ndarray]]:
  858. if file_path is None:
  859. return None, None
  860. # disparity decoding as per Sintel instructions in the README provided with the dataset
  861. disparity_map = np.asarray(Image.open(file_path), dtype=np.float32)
  862. r, g, b = np.split(disparity_map, 3, axis=-1)
  863. disparity_map = r * 4 + g / (2**6) + b / (2**14)
  864. # reshape into (C, H, W) format
  865. disparity_map = np.transpose(disparity_map, (2, 0, 1))
  866. # find the appropriate file paths
  867. occlued_mask_path, out_of_frame_mask_path = self._get_occlussion_mask_paths(file_path)
  868. # occlusion masks
  869. valid_mask = np.asarray(Image.open(occlued_mask_path)) == 0
  870. # out of frame masks
  871. off_mask = np.asarray(Image.open(out_of_frame_mask_path)) == 0
  872. # combine the masks together
  873. valid_mask = np.logical_and(off_mask, valid_mask)
  874. return disparity_map, valid_mask
  875. def __getitem__(self, index: int) -> T2:
  876. """Return example at given index.
  877. Args:
  878. index(int): The index of the example to retrieve
  879. Returns:
  880. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  881. The disparity is a numpy array of shape (1, H, W) and the images are PIL images whilst
  882. the valid_mask is a numpy array of shape (H, W).
  883. """
  884. return cast(T2, super().__getitem__(index))
  885. class InStereo2k(StereoMatchingDataset):
  886. """`InStereo2k <https://github.com/YuhuaXu/StereoDataset>`_ dataset.
  887. The dataset is expected to have the following structure: ::
  888. root
  889. InStereo2k
  890. train
  891. scene1
  892. left.png
  893. right.png
  894. left_disp.png
  895. right_disp.png
  896. ...
  897. scene2
  898. ...
  899. test
  900. scene1
  901. left.png
  902. right.png
  903. left_disp.png
  904. right_disp.png
  905. ...
  906. scene2
  907. ...
  908. Args:
  909. root (str or ``pathlib.Path``): Root directory where InStereo2k is located.
  910. split (string): Either "train" or "test".
  911. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  912. """
  913. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  914. super().__init__(root, transforms)
  915. root = Path(root) / "InStereo2k" / split
  916. verify_str_arg(split, "split", valid_values=("train", "test"))
  917. left_img_pattern = str(root / "*" / "left.png")
  918. right_img_pattern = str(root / "*" / "right.png")
  919. self._images = self._scan_pairs(left_img_pattern, right_img_pattern)
  920. left_disparity_pattern = str(root / "*" / "left_disp.png")
  921. right_disparity_pattern = str(root / "*" / "right_disp.png")
  922. self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  923. def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
  924. disparity_map = np.asarray(Image.open(file_path), dtype=np.float32)
  925. # unsqueeze disparity to (C, H, W)
  926. disparity_map = disparity_map[None, :, :] / 1024.0
  927. valid_mask = None
  928. return disparity_map, valid_mask
  929. def __getitem__(self, index: int) -> T1:
  930. """Return example at given index.
  931. Args:
  932. index(int): The index of the example to retrieve
  933. Returns:
  934. tuple: A 3-tuple with ``(img_left, img_right, disparity)``.
  935. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  936. If a ``valid_mask`` is generated within the ``transforms`` parameter,
  937. a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  938. """
  939. return cast(T1, super().__getitem__(index))
  940. class ETH3DStereo(StereoMatchingDataset):
  941. """ETH3D `Low-Res Two-View <https://www.eth3d.net/datasets>`_ dataset.
  942. The dataset is expected to have the following structure: ::
  943. root
  944. ETH3D
  945. two_view_training
  946. scene1
  947. im1.png
  948. im0.png
  949. images.txt
  950. cameras.txt
  951. calib.txt
  952. scene2
  953. im1.png
  954. im0.png
  955. images.txt
  956. cameras.txt
  957. calib.txt
  958. ...
  959. two_view_training_gt
  960. scene1
  961. disp0GT.pfm
  962. mask0nocc.png
  963. scene2
  964. disp0GT.pfm
  965. mask0nocc.png
  966. ...
  967. two_view_testing
  968. scene1
  969. im1.png
  970. im0.png
  971. images.txt
  972. cameras.txt
  973. calib.txt
  974. scene2
  975. im1.png
  976. im0.png
  977. images.txt
  978. cameras.txt
  979. calib.txt
  980. ...
  981. Args:
  982. root (str or ``pathlib.Path``): Root directory of the ETH3D Dataset.
  983. split (string, optional): The dataset split of scenes, either "train" (default) or "test".
  984. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  985. """
  986. _has_built_in_disparity_mask = True
  987. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  988. super().__init__(root, transforms)
  989. verify_str_arg(split, "split", valid_values=("train", "test"))
  990. root = Path(root) / "ETH3D"
  991. img_dir = "two_view_training" if split == "train" else "two_view_test"
  992. anot_dir = "two_view_training_gt"
  993. left_img_pattern = str(root / img_dir / "*" / "im0.png")
  994. right_img_pattern = str(root / img_dir / "*" / "im1.png")
  995. self._images = self._scan_pairs(left_img_pattern, right_img_pattern)
  996. if split == "test":
  997. self._disparities = list((None, None) for _ in self._images)
  998. else:
  999. disparity_pattern = str(root / anot_dir / "*" / "disp0GT.pfm")
  1000. self._disparities = self._scan_pairs(disparity_pattern, None)
  1001. def _read_disparity(self, file_path: str) -> Union[Tuple[None, None], Tuple[np.ndarray, np.ndarray]]:
  1002. # test split has no disparity maps
  1003. if file_path is None:
  1004. return None, None
  1005. disparity_map = _read_pfm_file(file_path)
  1006. disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
  1007. mask_path = Path(file_path).parent / "mask0nocc.png"
  1008. valid_mask = Image.open(mask_path)
  1009. valid_mask = np.asarray(valid_mask).astype(bool)
  1010. return disparity_map, valid_mask
  1011. def __getitem__(self, index: int) -> T2:
  1012. """Return example at given index.
  1013. Args:
  1014. index(int): The index of the example to retrieve
  1015. Returns:
  1016. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  1017. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  1018. ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not
  1019. generate a valid mask.
  1020. Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test.
  1021. """
  1022. return cast(T2, super().__getitem__(index))
Tip!

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

Comments

Loading...