-
Notifications
You must be signed in to change notification settings - Fork 117
/
evaluate_stereo.py
executable file
·843 lines (658 loc) · 31.2 KB
/
evaluate_stereo.py
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
import time
import numpy as np
import torch
import torch.nn.functional as F
from torchvision.transforms.functional import hflip
import os
import skimage.io
import cv2
from PIL import Image
from glob import glob
from loss.stereo_metric import d1_metric, thres_metric
from dataloader.stereo.datasets import (FlyingThings3D, KITTI15,
ETH3DStereo, MiddleburyEval3)
from dataloader.stereo import transforms
from utils.utils import InputPadder
from utils.file_io import write_pfm
from utils.visualization import vis_disparity
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
@torch.no_grad()
def create_kitti_submission(model,
output_path='output',
padding_factor=16,
attn_splits_list=False,
corr_radius_list=False,
prop_radius_list=False,
attn_type=None,
num_reg_refine=1,
inference_size=None,
):
""" create submission for the KITTI leaderboard """
model.eval()
val_transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
]
val_transform = transforms.Compose(val_transform_list)
test_dataset = KITTI15(mode='testing', transform=val_transform)
num_samples = len(test_dataset)
print('Number of test samples: %d' % num_samples)
if not os.path.exists(output_path):
os.makedirs(output_path)
for i, sample in enumerate(test_dataset):
left = sample['left'].to(device).unsqueeze(0) # [1, 3, H, W]
right = sample['right'].to(device).unsqueeze(0) # [1, 3, H, W]
left_name = sample['left_name']
if inference_size is None:
padder = InputPadder(left.shape, padding_factor=padding_factor)
left, right = padder.pad(left, right)
else:
ori_size = left.shape[-2:]
left = F.interpolate(left, size=inference_size, mode='bilinear',
align_corners=True)
right = F.interpolate(right, size=inference_size, mode='bilinear',
align_corners=True)
pred_disp = model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)['flow_preds'][-1] # [1, H, W]
# remove padding
if inference_size is None:
pred_disp = padder.unpad(pred_disp)[0] # [H, W]
else:
# resize back
pred_disp = F.interpolate(pred_disp.unsqueeze(1), size=ori_size, mode='bilinear',
align_corners=True).squeeze(1)[0] # [H, W]
pred_disp = pred_disp * ori_size[-1] / float(inference_size[-1])
save_name = os.path.join(output_path, left_name)
skimage.io.imsave(save_name, (pred_disp.cpu().numpy() * 256.).astype(np.uint16))
@torch.no_grad()
def create_eth3d_submission(model,
output_path='output',
padding_factor=16,
attn_type=None,
attn_splits_list=False,
corr_radius_list=False,
prop_radius_list=False,
num_reg_refine=1,
inference_size=None,
submission_mode='train',
save_vis_disp=False,
):
""" create submission for the eth3d stereo leaderboard """
model.eval()
val_transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
]
val_transform = transforms.Compose(val_transform_list)
test_dataset = ETH3DStereo(mode=submission_mode,
transform=val_transform,
save_filename=True
)
num_samples = len(test_dataset)
print('Number of test samples: %d' % num_samples)
if not os.path.exists(output_path):
os.makedirs(output_path)
fixed_inference_size = inference_size
for i, sample in enumerate(test_dataset):
left = sample['left'].to(device).unsqueeze(0) # [1, 3, H, W]
right = sample['right'].to(device).unsqueeze(0) # [1, 3, H, W]
left_name = sample['left_name']
nearest_size = [int(np.ceil(left.size(-2) / padding_factor)) * padding_factor,
int(np.ceil(left.size(-1) / padding_factor)) * padding_factor]
# resize to nearest size or specified size
inference_size = nearest_size if fixed_inference_size is None else fixed_inference_size
assert isinstance(inference_size, list) or isinstance(inference_size, tuple)
ori_size = left.shape[-2:]
if inference_size[0] != ori_size[0] or inference_size[1] != ori_size[1]:
left = F.interpolate(left, size=inference_size, mode='bilinear',
align_corners=True)
right = F.interpolate(right, size=inference_size, mode='bilinear',
align_corners=True)
# warpup to measure inference time
if i == 0:
for _ in range(5):
model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)
torch.cuda.synchronize()
time_start = time.perf_counter()
pred_disp = model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)['flow_preds'][-1] # [1, H, W]
torch.cuda.synchronize()
inference_time = time.perf_counter() - time_start
# resize back
if inference_size[0] != ori_size[0] or inference_size[1] != ori_size[1]:
pred_disp = F.interpolate(pred_disp.unsqueeze(1), size=ori_size, mode='bilinear',
align_corners=True).squeeze(1)[0] # [H, W]
pred_disp = pred_disp * ori_size[-1] / float(inference_size[-1])
filename = os.path.basename(os.path.dirname(left_name))
if save_vis_disp:
save_name = os.path.join(output_path, filename + '.png')
disp = vis_disparity(pred_disp.cpu().numpy())
cv2.imwrite(save_name, disp)
else:
save_disp_name = os.path.join(output_path, filename + '.pfm')
# save disp
write_pfm(save_disp_name, pred_disp.cpu().numpy())
# save runtime
save_runtime_name = os.path.join(output_path, filename + '.txt')
with open(save_runtime_name, 'w') as f:
f.write('runtime ' + str(inference_time))
@torch.no_grad()
def create_middlebury_submission(model,
output_path='output',
padding_factor=16,
attn_type=None,
attn_splits_list=False,
corr_radius_list=False,
prop_radius_list=False,
num_reg_refine=1,
inference_size=None,
submission_mode='train',
save_vis_disp=False,
):
""" create submission for the Middlebury leaderboard """
model.eval()
val_transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
]
val_transform = transforms.Compose(val_transform_list)
test_dataset = MiddleburyEval3(mode=submission_mode,
resolution='F',
transform=val_transform,
save_filename=True,
)
num_samples = len(test_dataset)
print('Number of test samples: %d' % num_samples)
if not os.path.exists(output_path):
os.makedirs(output_path)
for i, sample in enumerate(test_dataset):
left = sample['left'].to(device).unsqueeze(0) # [1, 3, H, W]
right = sample['right'].to(device).unsqueeze(0) # [1, 3, H, W]
left_name = sample['left_name']
if inference_size is None:
padder = InputPadder(left.shape, padding_factor=padding_factor)
left, right = padder.pad(left, right)
else:
ori_size = left.shape[-2:]
left = F.interpolate(left, size=inference_size, mode='bilinear',
align_corners=True)
right = F.interpolate(right, size=inference_size, mode='bilinear',
align_corners=True)
# warpup to measure inference time
if i == 0:
for _ in range(5):
model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)
torch.cuda.synchronize()
time_start = time.perf_counter()
pred_disp = model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
task='stereo',
)['flow_preds'][-1] # [1, H, W]
torch.cuda.synchronize()
inference_time = time.perf_counter() - time_start
# remove padding
if inference_size is None:
pred_disp = padder.unpad(pred_disp)[0] # [H, W]
else:
# resize back
pred_disp = F.interpolate(pred_disp.unsqueeze(1), size=ori_size, mode='bilinear',
align_corners=True).squeeze(1)[0] # [H, W]
pred_disp = pred_disp * ori_size[-1] / float(inference_size[-1])
filename = os.path.basename(os.path.dirname(left_name)) # works for both windows and linux
if save_vis_disp:
save_name = os.path.join(output_path, filename + '.png')
disp = vis_disparity(pred_disp.cpu().numpy())
cv2.imwrite(save_name, disp)
else:
save_disp_dir = os.path.join(output_path, filename)
os.makedirs(save_disp_dir, exist_ok=True)
save_disp_name = os.path.join(save_disp_dir, 'disp0GMStereo.pfm')
# save disp
write_pfm(save_disp_name, pred_disp.cpu().numpy())
# save runtime
save_runtime_name = os.path.join(save_disp_dir, 'timeGMStereo.txt')
with open(save_runtime_name, 'w') as f:
f.write(str(inference_time))
@torch.no_grad()
def validate_things(model,
max_disp=400,
padding_factor=16,
inference_size=None,
attn_type=None,
num_iters_per_scale=None,
attn_splits_list=None,
corr_radius_list=None,
prop_radius_list=None,
num_reg_refine=1,
):
model.eval()
results = {}
val_transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
]
val_transform = transforms.Compose(val_transform_list)
val_dataset = FlyingThings3D(mode='TEST', transform=val_transform)
num_samples = len(val_dataset)
print('=> %d samples found in the validation set' % num_samples)
val_epe = 0
val_d1 = 0
valid_samples = 0
for i, sample in enumerate(val_dataset):
if i % 1000 == 0:
print('=> Validating %d/%d' % (i, num_samples))
left = sample['left'].to(device).unsqueeze(0) # [1, 3, H, W]
right = sample['right'].to(device).unsqueeze(0) # [1, 3, H, W]
gt_disp = sample['disp'].to(device) # [H, W]
if inference_size is None:
padder = InputPadder(left.shape, padding_factor=padding_factor)
left, right = padder.pad(left, right)
else:
ori_size = left.shape[-2:]
left = F.interpolate(left, size=inference_size, mode='bilinear',
align_corners=True)
right = F.interpolate(right, size=inference_size, mode='bilinear',
align_corners=True)
mask = (gt_disp > 0) & (gt_disp < max_disp)
if not mask.any():
continue
valid_samples += 1
with torch.no_grad():
pred_disp = model(left, right,
attn_type=attn_type,
num_iters_per_scale=num_iters_per_scale,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)['flow_preds'][-1] # [1, H, W]
# remove padding
if inference_size is None:
pred_disp = padder.unpad(pred_disp)[0] # [H, W]
else:
# resize back
pred_disp = F.interpolate(pred_disp.unsqueeze(1), size=ori_size, mode='bilinear',
align_corners=True).squeeze(1)[0] # [H, W]
pred_disp = pred_disp * ori_size[-1] / float(inference_size[-1])
epe = F.l1_loss(gt_disp[mask], pred_disp[mask], reduction='mean')
d1 = d1_metric(pred_disp, gt_disp, mask)
val_epe += epe.item()
val_d1 += d1.item()
mean_epe = val_epe / valid_samples
mean_d1 = val_d1 / valid_samples
print('Validation things EPE: %.3f, D1: %.4f' % (
mean_epe, mean_d1))
results['things_epe'] = mean_epe
results['things_d1'] = mean_d1
return results
@torch.no_grad()
def validate_kitti15(model,
padding_factor=16,
inference_size=None,
attn_type=None,
attn_splits_list=None,
corr_radius_list=None,
prop_radius_list=None,
num_reg_refine=1,
count_time=False,
debug=False,
):
model.eval()
results = {}
val_transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
]
val_transform = transforms.Compose(val_transform_list)
val_dataset = KITTI15(transform=val_transform,
)
num_samples = len(val_dataset)
print('=> %d samples found in the validation set' % num_samples)
val_epe = 0
val_d1 = 0
val_thres3 = 0
if count_time:
total_time = 0
num_runs = 100
valid_samples = 0
for i, sample in enumerate(val_dataset):
if debug and i > 10:
break
if i % 100 == 0:
print('=> Validating %d/%d' % (i, num_samples))
left = sample['left'].to(device).unsqueeze(0) # [1, 3, H, W]
right = sample['right'].to(device).unsqueeze(0) # [1, 3, H, W]
gt_disp = sample['disp'].to(device) # [H, W]
if inference_size is None:
padder = InputPadder(left.shape, padding_factor=padding_factor)
left, right = padder.pad(left, right)
else:
ori_size = left.shape[-2:]
left = F.interpolate(left, size=inference_size, mode='bilinear',
align_corners=True)
right = F.interpolate(right, size=inference_size, mode='bilinear',
align_corners=True)
mask = gt_disp > 0
if not mask.any():
continue
valid_samples += 1
if count_time and i >= 5:
torch.cuda.synchronize()
time_start = time.perf_counter()
with torch.no_grad():
pred_disp = model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)['flow_preds'][-1] # [1, H, W]
if count_time and i >= 5:
torch.cuda.synchronize()
total_time += time.perf_counter() - time_start
if i >= num_runs + 4:
break
# remove padding
if inference_size is None:
pred_disp = padder.unpad(pred_disp)[0] # [H, W]
else:
# resize back
pred_disp = F.interpolate(pred_disp.unsqueeze(1), size=ori_size, mode='bilinear',
align_corners=True).squeeze(1)[0] # [H, W]
pred_disp = pred_disp * ori_size[-1] / float(inference_size[-1])
epe = F.l1_loss(gt_disp[mask], pred_disp[mask], reduction='mean')
d1 = d1_metric(pred_disp, gt_disp, mask)
thres3 = thres_metric(pred_disp, gt_disp, mask, 3.0)
val_epe += epe.item()
val_d1 += d1.item()
val_thres3 += thres3.item()
mean_epe = val_epe / valid_samples
mean_d1 = val_d1 / valid_samples
mean_thres3 = val_thres3 / valid_samples
print('Validation KITTI15 EPE: %.3f, D1: %.4f, 3px: %.4f' % (
mean_epe, mean_d1, mean_thres3))
results['kitti15_epe'] = mean_epe
results['kitti15_d1'] = mean_d1
results['kitti15_3px'] = mean_thres3
if count_time:
print('Time: %.6fs' % (total_time / num_runs))
return results
@torch.no_grad()
def validate_eth3d(model,
padding_factor=16,
inference_size=None,
attn_type=None,
attn_splits_list=None,
corr_radius_list=None,
prop_radius_list=None,
num_reg_refine=1,
):
model.eval()
results = {}
val_transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
]
val_transform = transforms.Compose(val_transform_list)
val_dataset = ETH3DStereo(transform=val_transform,
)
num_samples = len(val_dataset)
print('=> %d samples found in the validation set' % num_samples)
val_epe = 0
val_d1 = 0
val_thres1 = 0
valid_samples = 0
for i, sample in enumerate(val_dataset):
if i % 100 == 0:
print('=> Validating %d/%d' % (i, num_samples))
left = sample['left'].to(device).unsqueeze(0) # [1, 3, H, W]
right = sample['right'].to(device).unsqueeze(0) # [1, 3, H, W]
gt_disp = sample['disp'].to(device) # [H, W]
if inference_size is None:
padder = InputPadder(left.shape, padding_factor=padding_factor)
left, right = padder.pad(left, right)
else:
ori_size = left.shape[-2:]
left = F.interpolate(left, size=inference_size, mode='bilinear',
align_corners=True)
right = F.interpolate(right, size=inference_size, mode='bilinear',
align_corners=True)
mask = gt_disp > 0
if not mask.any():
continue
valid_samples += 1
with torch.no_grad():
pred_disp = model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)['flow_preds'][-1] # [1, H, W]
# remove padding
if inference_size is None:
pred_disp = padder.unpad(pred_disp)[0] # [H, W]
else:
# resize back
pred_disp = F.interpolate(pred_disp.unsqueeze(1), size=ori_size, mode='bilinear',
align_corners=True).squeeze(1)[0] # [H, W]
pred_disp = pred_disp * ori_size[-1] / float(inference_size[-1])
epe = F.l1_loss(gt_disp[mask], pred_disp[mask], reduction='mean')
d1 = d1_metric(pred_disp, gt_disp, mask)
thres1 = thres_metric(pred_disp, gt_disp, mask, 1.0)
val_epe += epe.item()
val_d1 += d1.item()
val_thres1 += thres1.item()
mean_epe = val_epe / valid_samples
mean_thres1 = val_thres1 / valid_samples
print('Validation ETH3D EPE: %.3f, 1px: %.4f' % (
mean_epe, mean_thres1))
results['eth3d_epe'] = mean_epe
results['eth3d_1px'] = mean_thres1
return results
@torch.no_grad()
def validate_middlebury(model,
padding_factor=16,
inference_size=None,
attn_type=None,
attn_splits_list=None,
corr_radius_list=None,
prop_radius_list=None,
num_reg_refine=1,
resolution='H',
):
model.eval()
results = {}
val_transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
]
val_transform = transforms.Compose(val_transform_list)
val_dataset = MiddleburyEval3(transform=val_transform,
resolution=resolution,
)
num_samples = len(val_dataset)
print('=> %d samples found in the validation set' % num_samples)
val_epe = 0
val_d1 = 0
val_thres2 = 0
valid_samples = 0
for i, sample in enumerate(val_dataset):
if i % 100 == 0:
print('=> Validating %d/%d' % (i, num_samples))
left = sample['left'].to(device).unsqueeze(0) # [1, 3, H, W]
right = sample['right'].to(device).unsqueeze(0) # [1, 3, H, W]
gt_disp = sample['disp'].to(device) # [H, W]
if inference_size is None:
padder = InputPadder(left.shape, padding_factor=padding_factor)
left, right = padder.pad(left, right)
else:
ori_size = left.shape[-2:]
left = F.interpolate(left, size=inference_size,
mode='bilinear',
align_corners=True)
right = F.interpolate(right, size=inference_size,
mode='bilinear',
align_corners=True)
mask = gt_disp > 0
if not mask.any():
continue
valid_samples += 1
with torch.no_grad():
pred_disp = model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)['flow_preds'][-1] # [1, H, W]
# remove padding
if inference_size is None:
pred_disp = padder.unpad(pred_disp)[0] # [H, W]
else:
# resize back
pred_disp = F.interpolate(pred_disp.unsqueeze(1), size=ori_size,
mode='bilinear',
align_corners=True).squeeze(1)[0] # [H, W]
pred_disp = pred_disp * ori_size[-1] / float(inference_size[-1])
epe = F.l1_loss(gt_disp[mask], pred_disp[mask], reduction='mean')
d1 = d1_metric(pred_disp, gt_disp, mask)
thres2 = thres_metric(pred_disp, gt_disp, mask, 2.0)
val_epe += epe.item()
val_d1 += d1.item()
val_thres2 += thres2.item()
mean_epe = val_epe / valid_samples
mean_thres2 = val_thres2 / valid_samples
print('Validation Middlebury EPE: %.3f, 2px: %.4f' % (
mean_epe, mean_thres2))
results['middlebury_epe'] = mean_epe
results['middlebury_2px'] = mean_thres2
return results
@torch.no_grad()
def inference_stereo(model,
inference_dir=None,
inference_dir_left=None,
inference_dir_right=None,
output_path='output',
padding_factor=16,
inference_size=None,
attn_type=None,
attn_splits_list=None,
corr_radius_list=None,
prop_radius_list=None,
num_reg_refine=1,
pred_bidir_disp=False,
pred_right_disp=False,
save_pfm_disp=False,
):
model.eval()
val_transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
]
val_transform = transforms.Compose(val_transform_list)
if not os.path.exists(output_path):
os.makedirs(output_path)
assert inference_dir or (inference_dir_left and inference_dir_right)
if inference_dir is not None:
filenames = sorted(glob(inference_dir + '/*.png') + glob(inference_dir + '/*.jpg'))
left_filenames = filenames[::2]
right_filenames = filenames[1::2]
else:
left_filenames = sorted(glob(inference_dir_left + '/*.png') + glob(inference_dir_left + '/*.jpg'))
right_filenames = sorted(glob(inference_dir_right + '/*.png') + glob(inference_dir_right + '/*.jpg'))
assert len(left_filenames) == len(right_filenames)
num_samples = len(left_filenames)
print('%d test samples found' % num_samples)
fixed_inference_size = inference_size
for i in range(num_samples):
if (i + 1) % 50 == 0:
print('predicting %d/%d' % (i + 1, num_samples))
left_name = left_filenames[i]
right_name = right_filenames[i]
left = np.array(Image.open(left_name).convert('RGB')).astype(np.float32)
right = np.array(Image.open(right_name).convert('RGB')).astype(np.float32)
sample = {'left': left, 'right': right}
sample = val_transform(sample)
left = sample['left'].to(device).unsqueeze(0) # [1, 3, H, W]
right = sample['right'].to(device).unsqueeze(0) # [1, 3, H, W]
nearest_size = [int(np.ceil(left.size(-2) / padding_factor)) * padding_factor,
int(np.ceil(left.size(-1) / padding_factor)) * padding_factor]
# resize to nearest size or specified size
inference_size = nearest_size if fixed_inference_size is None else fixed_inference_size
ori_size = left.shape[-2:]
if inference_size[0] != ori_size[0] or inference_size[1] != ori_size[1]:
left = F.interpolate(left, size=inference_size,
mode='bilinear',
align_corners=True)
right = F.interpolate(right, size=inference_size,
mode='bilinear',
align_corners=True)
with torch.no_grad():
if pred_bidir_disp:
new_left, new_right = hflip(right), hflip(left)
left = torch.cat((left, new_left), dim=0)
right = torch.cat((right, new_right), dim=0)
if pred_right_disp:
left, right = hflip(right), hflip(left)
pred_disp = model(left, right,
attn_type=attn_type,
attn_splits_list=attn_splits_list,
corr_radius_list=corr_radius_list,
prop_radius_list=prop_radius_list,
num_reg_refine=num_reg_refine,
task='stereo',
)['flow_preds'][-1] # [1, H, W]
if inference_size[0] != ori_size[0] or inference_size[1] != ori_size[1]:
# resize back
pred_disp = F.interpolate(pred_disp.unsqueeze(1), size=ori_size,
mode='bilinear',
align_corners=True).squeeze(1) # [1, H, W]
pred_disp = pred_disp * ori_size[-1] / float(inference_size[-1])
save_name = os.path.join(output_path, os.path.basename(left_name)[:-4] + '_disp.png')
if pred_right_disp:
pred_disp = hflip(pred_disp)
disp = pred_disp[0].cpu().numpy()
if save_pfm_disp:
save_name_pfm = save_name[:-4] + '.pfm'
write_pfm(save_name_pfm, disp)
disp = vis_disparity(disp)
cv2.imwrite(save_name, disp)
if pred_bidir_disp:
assert pred_disp.size(0) == 2 # [2, H, W]
save_name = os.path.join(output_path, os.path.basename(left_name)[:-4] + '_disp_right.png')
# flip back
disp = hflip(pred_disp[1]).cpu().numpy()
if save_pfm_disp:
save_name_pfm = save_name[:-4] + '.pfm'
write_pfm(save_name_pfm, disp)
disp = vis_disparity(disp)
cv2.imwrite(save_name, disp)
print('Done!')