-
Notifications
You must be signed in to change notification settings - Fork 18
/
evaluate.py
283 lines (210 loc) · 10.2 KB
/
evaluate.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
import sys
sys.path.append('core')
import argparse
import copy
import os
import time
import datasets
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from utils import frame_utils
from utils.utils import InputPadder, forward_interpolate
MAX_FLOW = 400
@torch.no_grad()
def create_sintel_submission(model, warm_start=False, fixed_point_reuse=False, output_path='sintel_submission', **kwargs):
""" Create submission for the Sintel leaderboard """
model.eval()
for dstype in ['clean', 'final']:
test_dataset = datasets.MpiSintel(split='test', aug_params=None, dstype=dstype)
sequence_prev, flow_prev, fixed_point = None, None, None
for test_id in range(len(test_dataset)):
image1, image2, (sequence, frame) = test_dataset[test_id]
if sequence != sequence_prev:
flow_prev = None
fixed_point = None
padder = InputPadder(image1.shape)
image1, image2 = padder.pad(image1[None].cuda(), image2[None].cuda())
flow_low, flow_pr, info = model(image1, image2, flow_init=flow_prev, cached_result=fixed_point, **kwargs)
flow = padder.unpad(flow_pr[0]).permute(1, 2, 0).cpu().numpy()
# You may choose to use some hacks here,
# for example, warm start, i.e., reusing the f* part with a borderline check (forward_interpolate),
# which was orignally taken by RAFT.
# This trick usually (only) improves the optical flow estimation on the ``ambush_1'' sequence,
# in terms of clearer background estimation.
if warm_start:
flow_prev = forward_interpolate(flow_low[0])[None].cuda()
# Note that the fixed point reuse usually does not improve performance.
# It facilitates the convergence.
# To improve performance, the borderline check like ``forward_interpolate'' is necessary.
if fixed_point_reuse:
net, flow_pred_low = info['cached_result']
flow_pred_low = forward_interpolate(flow_pred_low[0])[None].cuda()
fixed_point = (net, flow_pred_low)
output_dir = os.path.join(output_path, dstype, sequence)
output_file = os.path.join(output_dir, 'frame%04d.flo' % (frame+1))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
frame_utils.writeFlow(output_file, flow)
sequence_prev = sequence
@torch.no_grad()
def create_kitti_submission(model, output_path='kitti_submission'):
""" Create submission for the KITTI leaderboard """
model.eval()
test_dataset = datasets.KITTI(split='testing', aug_params=None)
if not os.path.exists(output_path):
os.makedirs(output_path)
for test_id in range(len(test_dataset)):
image1, image2, (frame_id, ) = test_dataset[test_id]
padder = InputPadder(image1.shape, mode='kitti')
image1, image2 = padder.pad(image1[None].cuda(), image2[None].cuda())
_, flow_pr, _ = model(image1, image2)
flow = padder.unpad(flow_pr[0]).permute(1, 2, 0).cpu().numpy()
output_filename = os.path.join(output_path, frame_id)
frame_utils.writeFlowKITTI(output_filename, flow)
@torch.no_grad()
def validate_chairs(model, **kwargs):
""" Perform evaluation on the FlyingChairs (test) split """
model.eval()
epe_list = []
rho_list = []
best = kwargs.get("best", {"epe":1e8})
val_dataset = datasets.FlyingChairs(split='validation')
for val_id in range(len(val_dataset)):
image1, image2, flow_gt, _ = val_dataset[val_id]
image1 = image1[None].cuda()
image2 = image2[None].cuda()
_, flow_pr, info = model(image1, image2, **kwargs)
epe = torch.sum((flow_pr[0].cpu() - flow_gt)**2, dim=0).sqrt()
epe_list.append(epe.view(-1).numpy())
rho_list.append(info['sradius'].mean().item())
epe = np.mean(np.concatenate(epe_list))
best['epe'] = min(epe, best['epe'])
print(f"Validation Chairs EPE: {epe:.3f} ({best['epe']:.3f})")
if np.mean(rho_list) != 0:
print("Spectral radius: %.2f" % np.mean(rho_list))
return {'chairs': epe}
@torch.no_grad()
def validate_things(model, **kwargs):
""" Peform validation using the FlyingThings3D (test) split """
model.eval()
results = {}
for dstype in ['frames_cleanpass', 'frames_finalpass']:
val_dataset = datasets.FlyingThings3D(split='test', dstype=dstype)
epe_list = []
epe_w_mask_list = []
rho_list = []
print(f'{dstype} length', len(val_dataset))
for val_id in range(len(val_dataset)):
image1, image2, flow_gt, valid = val_dataset[val_id]
image1 = image1[None].cuda()
image2 = image2[None].cuda()
padder = InputPadder(image1.shape)
image1, image2 = padder.pad(image1, image2)
flow_low, flow_pr, info = model(image1, image2, **kwargs)
flow = padder.unpad(flow_pr[0]).cpu()
# exlude invalid pixels and extremely large diplacements
mag = torch.sum(flow_gt**2, dim=0).sqrt()
valid = (valid >= 0.5) & (mag < MAX_FLOW)
loss = (flow - flow_gt)**2
if torch.any(torch.isnan(loss)):
print(f'Bad prediction, {val_id}')
loss_w_mask = valid[None, :] * loss
if torch.any(torch.isnan(loss_w_mask)):
print(f'Bad prediction after mask, {val_id}')
print('Bad pixels num', torch.isnan(loss).sum())
print('Bad pixels num after mask', torch.isnan(loss_w_mask).sum())
continue
epe = torch.sum(loss, dim=0).sqrt()
epe_w_mask = torch.sum(loss_w_mask, dim=0).sqrt()
epe_list.append(epe.view(-1).numpy())
epe_w_mask_list.append(epe_w_mask.view(-1).numpy())
rho_list.append(info['sradius'].mean().item())
if (val_id + 1) % 100 == 0:
print('EPE', np.mean(epe_list), 'EPE w/ mask', np.mean(epe_w_mask_list))
epe_all = np.concatenate(epe_list)
epe = np.mean(epe_all)
px1 = np.mean(epe_all<1) * 100
px3 = np.mean(epe_all<3) * 100
px5 = np.mean(epe_all<5) * 100
epe_all_w_mask = np.concatenate(epe_w_mask_list)
epe_w_mask = np.mean(epe_all_w_mask)
px1_w_mask = np.mean(epe_all_w_mask<1) * 100
px3_w_mask = np.mean(epe_all_w_mask<3) * 100
px5_w_mask = np.mean(epe_all_w_mask<5) * 100
print("Validation (%s) EPE: %.3f, 1px: %.2f, 3px: %.2f, 5px: %.2f" % (dstype, epe, px1, px3, px5))
print("Validation w/ mask (%s) EPE: %.3f, 1px: %.2f, 3px: %.2f, 5px: %.2f" % (dstype, epe_w_mask, px1_w_mask, px3_w_mask, px5_w_mask))
results[dstype] = np.mean(epe_list)
results[dstype+'_w_mask'] = np.mean(epe_w_mask_list)
if np.mean(rho_list) != 0:
print("Spectral radius (%s): %f" % (dstype, np.mean(rho_list)))
return results
@torch.no_grad()
def validate_sintel(model, **kwargs):
""" Peform validation using the Sintel (train) split """
model.eval()
best = kwargs.get("best", {"clean-epe":1e8, "final-epe":1e8})
results = {}
for dstype in ['clean', 'final']:
val_dataset = datasets.MpiSintel(split='training', dstype=dstype)
epe_list = []
rho_list = []
info = {"sradius": None, "cached_result": None}
for val_id in range(len(val_dataset)):
image1, image2, flow_gt, _ = val_dataset[val_id]
image1 = image1[None].cuda()
image2 = image2[None].cuda()
padder = InputPadder(image1.shape)
image1, image2 = padder.pad(image1, image2)
flow_low, flow_pr, info = model(image1, image2, **kwargs)
flow = padder.unpad(flow_pr[0]).cpu()
epe = torch.sum((flow - flow_gt)**2, dim=0).sqrt()
epe_list.append(epe.view(-1).numpy())
rho_list.append(info['sradius'].mean().item())
epe_all = np.concatenate(epe_list)
epe = np.mean(epe_all)
px1 = np.mean(epe_all<1) * 100
px3 = np.mean(epe_all<3) * 100
px5 = np.mean(epe_all<5) * 100
best[dstype+'-epe'] = min(epe, best[dstype+'-epe'])
print(f"Validation ({dstype}) EPE: {epe:.3f} ({best[dstype+'-epe']:.3f}), 1px: {px1:.2f}, 3px: {px3:.2f}, 5px: {px5:.2f}")
results[dstype] = np.mean(epe_list)
if np.mean(rho_list) != 0:
print("Spectral radius (%s): %.2f" % (dstype, np.mean(rho_list)))
return results
@torch.no_grad()
def validate_kitti(model, **kwargs):
""" Peform validation using the KITTI-2015 (train) split """
model.eval()
best = kwargs.get("best", {"epe":1e8, "f1":1e8})
val_dataset = datasets.KITTI(split='training')
out_list, epe_list, rho_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, mode='kitti')
image1, image2 = padder.pad(image1, image2)
flow_low, flow_pr, info = model(image1, image2, **kwargs)
flow = padder.unpad(flow_pr[0]).cpu()
epe = torch.sum((flow - flow_gt)**2, dim=0).sqrt()
mag = torch.sum(flow_gt**2, dim=0).sqrt()
epe = epe.view(-1)
mag = mag.view(-1)
val = valid_gt.view(-1) >= 0.5
out = ((epe > 3.0) & ((epe/mag) > 0.05)).float()
epe_list.append(epe[val].mean().item())
out_list.append(out[val].cpu().numpy())
rho_list.append(info['sradius'].mean().item())
epe_list = np.array(epe_list)
out_list = np.concatenate(out_list)
epe = np.mean(epe_list)
f1 = np.mean(out_list) * 100
best['epe'] = min(epe, best['epe'])
best['f1'] = min(f1, best['f1'])
print(f"Validation KITTI: EPE: {epe:.3f} ({best['epe']:.3f}), F1: {f1:.2f} ({best['f1']:.2f})")
if np.mean(rho_list) != 0:
print("Spectral radius %.2f" % np.mean(rho_list))
return {'kitti-epe': epe, 'kitti-f1': f1}