-
Notifications
You must be signed in to change notification settings - Fork 5
/
evaluate_stereo.py
264 lines (204 loc) · 10.9 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
import sys
sys.path.append('core')
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
import argparse
import time
import logging
import numpy as np
import torch
from tqdm import tqdm
from igev_stereo import IGEVStereo, autocast
import stereo_datasets as datasets
from utils.utils import InputPadder
from PIL import Image
import torch.utils.data as data
from pathlib import Path
from matplotlib import pyplot as plt
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
@torch.no_grad()
def validate_eth3d(model, iters=32, mixed_prec=False):
""" Peform validation using the ETH3D (train) split """
model.eval()
aug_params = {}
val_dataset = datasets.ETH3D(aug_params)
out_list, epe_list = [], []
for val_id in range(len(val_dataset)):
(imageL_file, imageR_file, GT_file), image1, image2, flow_gt, valid_gt = val_dataset[val_id]
image1 = image1[None].cuda()
image2 = image2[None].cuda()
padder = InputPadder(image1.shape, divis_by=32)
image1, image2 = padder.pad(image1, image2)
with autocast(enabled=mixed_prec):
flow_pr = model(image1, image2, iters=iters, test_mode=True)
flow_pr = padder.unpad(flow_pr.float()).cpu().squeeze(0)
assert flow_pr.shape == flow_gt.shape, (flow_pr.shape, flow_gt.shape)
epe = torch.sum((flow_pr - flow_gt)**2, dim=0).sqrt()
epe_flattened = epe.flatten()
occ_mask = Image.open(GT_file.replace('disp0GT.pfm', 'mask0nocc.png'))
occ_mask = np.ascontiguousarray(occ_mask).flatten()
val = (valid_gt.flatten() >= 0.5) & (occ_mask == 255)
# val = (valid_gt.flatten() >= 0.5)
out = (epe_flattened > 1.0)
image_out = out[val].float().mean().item()
image_epe = epe_flattened[val].mean().item()
logging.info(f"ETH3D {val_id+1} out of {len(val_dataset)}. EPE {round(image_epe,4)} D1 {round(image_out,4)}")
epe_list.append(image_epe)
out_list.append(image_out)
epe_list = np.array(epe_list)
out_list = np.array(out_list)
epe = np.mean(epe_list)
d1 = 100 * np.mean(out_list)
print("Validation ETH3D: EPE %f, D1 %f" % (epe, d1))
return {'eth3d-epe': epe, 'eth3d-d1': d1}
@torch.no_grad()
def validate_kitti(model, iters=32, mixed_prec=False):
""" Peform validation using the KITTI-2015 (train) split """
model.eval()
aug_params = {}
val_dataset = datasets.KITTI(aug_params, image_set='training')
torch.backends.cudnn.benchmark = True
out_list, epe_list, elapsed_list = [], [], []
for val_id in range(len(val_dataset)):
_, image1, image2, flow_gt, valid_gt = val_dataset[val_id]
image1 = image1[None].cuda()
image2 = image2[None].cuda()
padder = InputPadder(image1.shape, divis_by=32)
image1, image2 = padder.pad(image1, image2)
with autocast(enabled=mixed_prec):
start = time.time()
flow_pr = model(image1, image2, iters=iters, test_mode=True)
end = time.time()
if val_id > 50:
elapsed_list.append(end-start)
flow_pr = padder.unpad(flow_pr).cpu().squeeze(0)
assert flow_pr.shape == flow_gt.shape, (flow_pr.shape, flow_gt.shape)
epe = torch.sum((flow_pr - flow_gt)**2, dim=0).sqrt()
epe_flattened = epe.flatten()
val = (valid_gt.flatten() >= 0.5) & (flow_gt.abs().flatten() < 192)
# val = valid_gt.flatten() >= 0.5
out = (epe_flattened > 3.0)
image_out = out[val].float().mean().item()
image_epe = epe_flattened[val].mean().item()
if val_id < 9 or (val_id+1)%10 == 0:
logging.info(f"KITTI Iter {val_id+1} out of {len(val_dataset)}. EPE {round(image_epe,4)} D1 {round(image_out,4)}. Runtime: {format(end-start, '.3f')}s ({format(1/(end-start), '.2f')}-FPS)")
epe_list.append(epe_flattened[val].mean().item())
out_list.append(out[val].cpu().numpy())
epe_list = np.array(epe_list)
out_list = np.concatenate(out_list)
epe = np.mean(epe_list)
d1 = 100 * np.mean(out_list)
avg_runtime = np.mean(elapsed_list)
print(f"Validation KITTI: EPE {epe}, D1 {d1}, {format(1/avg_runtime, '.2f')}-FPS ({format(avg_runtime, '.3f')}s)")
return {'kitti-epe': epe, 'kitti-d1': d1}
@torch.no_grad()
def validate_sceneflow(model, iters=32, mixed_prec=False):
""" Peform validation using the Scene Flow (TEST) split """
model.eval()
val_dataset = datasets.SceneFlowDatasets(dstype='frames_finalpass', things_test=True)
val_loader = data.DataLoader(val_dataset, batch_size=8,
pin_memory=True, shuffle=False, num_workers=8)
out_list, epe_list = [], []
for i_batch, (_, *data_blob) in enumerate(tqdm(val_loader)):
image1, image2, disp_gt, valid_gt = [x for x in data_blob]
image1 = image1.cuda()
image2 = image2.cuda()
padder = InputPadder(image1.shape, divis_by=32)
image1, image2 = padder.pad(image1, image2)
with autocast(enabled=mixed_prec):
disp_pr = model(image1, image2, iters=iters, test_mode=True)
disp_pr = padder.unpad(disp_pr).cpu()
assert disp_pr.shape == disp_gt.shape, (disp_pr.shape, disp_gt.shape)
epe = torch.abs(disp_pr - disp_gt)
epe = epe.flatten()
val = (disp_gt.abs().flatten() < 768)
if(np.isnan(epe[val].mean().item())):
continue
out = (epe > 3.0)
epe_list.append(epe[val].mean().item())
out_list.append(out[val].cpu().numpy())
epe_list = np.array(epe_list)
out_list = np.concatenate(out_list)
epe = np.mean(epe_list)
d1 = 100 * np.mean(out_list)
f = open('test_sceneflow.txt', 'a')
f.write("Validation Scene Flow: %f, %f\n" % (epe, d1))
print("Validation Scene Flow: %f, %f" % (epe, d1))
return {'scene-disp-epe': epe, 'scene-disp-d1': d1}
@torch.no_grad()
def validate_middlebury(model, iters=32, split='MiddEval3', resolution='F', mixed_prec=False):
""" Peform validation using the Middlebury-V3 dataset """
model.eval()
aug_params = {}
val_dataset = datasets.Middlebury(aug_params, split=split, resolution=resolution)
out_list, epe_list = [], []
for val_id in range(len(val_dataset)):
(imageL_file, _, _), image1, image2, flow_gt, valid_gt = val_dataset[val_id]
image1 = image1[None].cuda()
image2 = image2[None].cuda()
padder = InputPadder(image1.shape, divis_by=32)
image1, image2 = padder.pad(image1, image2)
with autocast(enabled=mixed_prec):
flow_pr = model(image1, image2, iters=iters, test_mode=True)
flow_pr = padder.unpad(flow_pr).cpu().squeeze(0)
assert flow_pr.shape == flow_gt.shape, (flow_pr.shape, flow_gt.shape)
epe = torch.sum((flow_pr - flow_gt)**2, dim=0).sqrt()
epe_flattened = epe.flatten()
occ_mask = Image.open(imageL_file.replace('im0.png', 'mask0nocc.png')).convert('L')
occ_mask = np.ascontiguousarray(occ_mask, dtype=np.float32).flatten()
val = (valid_gt.reshape(-1) >= 0.5) & (occ_mask==255)
out = (epe_flattened > 2.0)
image_out = out[val].float().mean().item()
image_epe = epe_flattened[val].mean().item()
logging.info(f"Middlebury Iter {val_id+1} out of {len(val_dataset)}. EPE {round(image_epe,4)} D1 {round(image_out,4)}")
epe_list.append(image_epe)
out_list.append(image_out)
epe_list = np.array(epe_list)
out_list = np.array(out_list)
epe = np.mean(epe_list)
d1 = 100 * np.mean(out_list)
f = open('test_middlebury.txt', 'a')
f.write("Validation Middlebury: %f, %f\n" % (epe, d1))
print(f"Validation Middlebury{split}: EPE {epe}, D1 {d1}")
return {f'middlebury{split}-epe': epe, f'middlebury{split}-d1': d1}
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--restore_ckpt', help="restore checkpoint", default='./pretrained_models/igev_plusplus/sceneflow.pth')
parser.add_argument('--dataset', help="dataset for evaluation", default='middlebury_H', choices=["eth3d", "kitti", "sceneflow"] + [f"middlebury_{s}" for s in 'FHQ'])
parser.add_argument('--mixed_precision', default=False, action='store_true', help='use mixed precision')
parser.add_argument('--valid_iters', type=int, default=32, help='number of flow-field updates during forward pass')
# Architecure choices
parser.add_argument('--hidden_dims', nargs='+', type=int, default=[128]*3, help="hidden state and context dimensions")
parser.add_argument('--corr_levels', type=int, default=2, help="number of levels in the correlation pyramid")
parser.add_argument('--corr_radius', type=int, default=4, help="width of the correlation pyramid")
parser.add_argument('--n_downsample', type=int, default=2, help="resolution of the disparity field (1/2^K)")
parser.add_argument('--n_gru_layers', type=int, default=3, help="number of hidden GRU levels")
parser.add_argument('--max_disp', type=int, default=768, help="max disp range")
parser.add_argument('--s_disp_range', type=int, default=48, help="max disp of small disparity-range geometry encoding volume")
parser.add_argument('--m_disp_range', type=int, default=96, help="max disp of medium disparity-range geometry encoding volume")
parser.add_argument('--l_disp_range', type=int, default=192, help="max disp of large disparity-range geometry encoding volume")
parser.add_argument('--s_disp_interval', type=int, default=1, help="disp interval of small disparity-range geometry encoding volume")
parser.add_argument('--m_disp_interval', type=int, default=2, help="disp interval of medium disparity-range geometry encoding volume")
parser.add_argument('--l_disp_interval', type=int, default=4, help="disp interval of large disparity-range geometry encoding volume")
args = parser.parse_args()
model = torch.nn.DataParallel(IGEVStereo(args), device_ids=[0])
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s')
if args.restore_ckpt is not None:
assert args.restore_ckpt.endswith(".pth")
logging.info("Loading checkpoint...")
checkpoint = torch.load(args.restore_ckpt)
model.load_state_dict(checkpoint, strict=True)
logging.info(f"Done loading checkpoint")
model.cuda()
model.eval()
print(f"The model has {format(count_parameters(model)/1e6, '.2f')}M learnable parameters.")
if args.dataset == 'eth3d':
validate_eth3d(model, iters=args.valid_iters, mixed_prec=args.mixed_precision)
elif args.dataset == 'kitti':
validate_kitti(model, iters=args.valid_iters, mixed_prec=args.mixed_precision)
elif args.dataset in [f"middlebury_{s}" for s in 'FHQ']:
validate_middlebury(model, iters=args.valid_iters, resolution=args.dataset[-1], mixed_prec=args.mixed_precision)
elif args.dataset == 'sceneflow':
validate_sceneflow(model, iters=args.valid_iters, mixed_prec=args.mixed_precision)