-
Notifications
You must be signed in to change notification settings - Fork 157
/
evaluate.py
215 lines (170 loc) · 9.3 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
import argparse
import os
import sys
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
from tqdm import tqdm
import model_io
from dataloader import DepthDataLoader
from models import UnetAdaptiveBins
from utils import RunningAverageDict
def compute_errors(gt, pred):
thresh = np.maximum((gt / pred), (pred / gt))
a1 = (thresh < 1.25).mean()
a2 = (thresh < 1.25 ** 2).mean()
a3 = (thresh < 1.25 ** 3).mean()
abs_rel = np.mean(np.abs(gt - pred) / gt)
sq_rel = np.mean(((gt - pred) ** 2) / gt)
rmse = (gt - pred) ** 2
rmse = np.sqrt(rmse.mean())
rmse_log = (np.log(gt) - np.log(pred)) ** 2
rmse_log = np.sqrt(rmse_log.mean())
err = np.log(pred) - np.log(gt)
silog = np.sqrt(np.mean(err ** 2) - np.mean(err) ** 2) * 100
log_10 = (np.abs(np.log10(gt) - np.log10(pred))).mean()
return dict(a1=a1, a2=a2, a3=a3, abs_rel=abs_rel, rmse=rmse, log_10=log_10, rmse_log=rmse_log,
silog=silog, sq_rel=sq_rel)
# def denormalize(x, device='cpu'):
# mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(device)
# std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(device)
# return x * std + mean
#
def predict_tta(model, image, args):
pred = model(image)[-1]
# pred = utils.depth_norm(pred)
# pred = nn.functional.interpolate(pred, depth.shape[-2:], mode='bilinear', align_corners=True)
# pred = np.clip(pred.cpu().numpy(), 10, 1000)/100.
pred = np.clip(pred.cpu().numpy(), args.min_depth, args.max_depth)
image = torch.Tensor(np.array(image.cpu().numpy())[..., ::-1].copy()).to(device)
pred_lr = model(image)[-1]
# pred_lr = utils.depth_norm(pred_lr)
# pred_lr = nn.functional.interpolate(pred_lr, depth.shape[-2:], mode='bilinear', align_corners=True)
# pred_lr = np.clip(pred_lr.cpu().numpy()[...,::-1], 10, 1000)/100.
pred_lr = np.clip(pred_lr.cpu().numpy()[..., ::-1], args.min_depth, args.max_depth)
final = 0.5 * (pred + pred_lr)
final = nn.functional.interpolate(torch.Tensor(final), image.shape[-2:], mode='bilinear', align_corners=True)
return torch.Tensor(final)
def eval(model, test_loader, args, gpus=None, ):
if gpus is None:
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
else:
device = gpus[0]
if args.save_dir is not None:
os.makedirs(args.save_dir)
metrics = RunningAverageDict()
# crop_size = (471 - 45, 601 - 41)
# bins = utils.get_bins(100)
total_invalid = 0
with torch.no_grad():
model.eval()
sequential = test_loader
for batch in tqdm(sequential):
image = batch['image'].to(device)
gt = batch['depth'].to(device)
final = predict_tta(model, image, args)
final = final.squeeze().cpu().numpy()
# final[final < args.min_depth] = args.min_depth
# final[final > args.max_depth] = args.max_depth
final[np.isinf(final)] = args.max_depth
final[np.isnan(final)] = args.min_depth
if args.save_dir is not None:
if args.dataset == 'nyu':
impath = f"{batch['image_path'][0].replace('/', '__').replace('.jpg', '')}"
factor = 1000
else:
dpath = batch['image_path'][0].split('/')
impath = dpath[1] + "_" + dpath[-1]
impath = impath.split('.')[0]
factor = 256
# rgb_path = os.path.join(rgb_dir, f"{impath}.png")
# tf.ToPILImage()(denormalize(image.squeeze().unsqueeze(0).cpu()).squeeze()).save(rgb_path)
pred_path = os.path.join(args.save_dir, f"{impath}.png")
pred = (final * factor).astype('uint16')
Image.fromarray(pred).save(pred_path)
if 'has_valid_depth' in batch:
if not batch['has_valid_depth']:
# print("Invalid ground truth")
total_invalid += 1
continue
gt = gt.squeeze().cpu().numpy()
valid_mask = np.logical_and(gt > args.min_depth, gt < args.max_depth)
if args.garg_crop or args.eigen_crop:
gt_height, gt_width = gt.shape
eval_mask = np.zeros(valid_mask.shape)
if args.garg_crop:
eval_mask[int(0.40810811 * gt_height):int(0.99189189 * gt_height),
int(0.03594771 * gt_width):int(0.96405229 * gt_width)] = 1
elif args.eigen_crop:
if args.dataset == 'kitti':
eval_mask[int(0.3324324 * gt_height):int(0.91351351 * gt_height),
int(0.0359477 * gt_width):int(0.96405229 * gt_width)] = 1
else:
eval_mask[45:471, 41:601] = 1
valid_mask = np.logical_and(valid_mask, eval_mask)
# gt = gt[valid_mask]
# final = final[valid_mask]
metrics.update(compute_errors(gt[valid_mask], final[valid_mask]))
print(f"Total invalid: {total_invalid}")
metrics = {k: round(v, 3) for k, v in metrics.get_value().items()}
print(f"Metrics: {metrics}")
def convert_arg_line_to_args(arg_line):
for arg in arg_line.split():
if not arg.strip():
continue
yield str(arg)
if __name__ == '__main__':
# Arguments
parser = argparse.ArgumentParser(description='Model evaluator', fromfile_prefix_chars='@',
conflict_handler='resolve')
parser.convert_arg_line_to_args = convert_arg_line_to_args
parser.add_argument('--n-bins', '--n_bins', default=256, type=int,
help='number of bins/buckets to divide depth range into')
parser.add_argument('--gpu', default=None, type=int, help='Which gpu to use')
parser.add_argument('--save-dir', '--save_dir', default=None, type=str, help='Store predictions in folder')
parser.add_argument("--root", default=".", type=str,
help="Root folder to save data in")
parser.add_argument("--dataset", default='nyu', type=str, help="Dataset to train on")
parser.add_argument("--data_path", default='../dataset/nyu/sync/', type=str,
help="path to dataset")
parser.add_argument("--gt_path", default='../dataset/nyu/sync/', type=str,
help="path to dataset gt")
parser.add_argument('--filenames_file',
default="./train_test_inputs/nyudepthv2_train_files_with_gt.txt",
type=str, help='path to the filenames text file')
parser.add_argument('--input_height', type=int, help='input height', default=416)
parser.add_argument('--input_width', type=int, help='input width', default=544)
parser.add_argument('--max_depth', type=float, help='maximum depth in estimation', default=10)
parser.add_argument('--min_depth', type=float, help='minimum depth in estimation', default=1e-3)
parser.add_argument('--do_kb_crop', help='if set, crop input images as kitti benchmark images', action='store_true')
parser.add_argument('--data_path_eval',
default="../dataset/nyu/official_splits/test/",
type=str, help='path to the data for online evaluation')
parser.add_argument('--gt_path_eval', default="../dataset/nyu/official_splits/test/",
type=str, help='path to the groundtruth data for online evaluation')
parser.add_argument('--filenames_file_eval',
default="./train_test_inputs/nyudepthv2_test_files_with_gt.txt",
type=str, help='path to the filenames text file for online evaluation')
parser.add_argument('--checkpoint_path', '--checkpoint-path', type=str, required=True,
help="checkpoint file to use for prediction")
parser.add_argument('--min_depth_eval', type=float, help='minimum depth for evaluation', default=1e-3)
parser.add_argument('--max_depth_eval', type=float, help='maximum depth for evaluation', default=10)
parser.add_argument('--eigen_crop', help='if set, crops according to Eigen NIPS14', action='store_true')
parser.add_argument('--garg_crop', help='if set, crops according to Garg ECCV16', action='store_true')
parser.add_argument('--do_kb_crop', help='Use kitti benchmark cropping', action='store_true')
if sys.argv.__len__() == 2:
arg_filename_with_prefix = '@' + sys.argv[1]
args = parser.parse_args([arg_filename_with_prefix])
else:
args = parser.parse_args()
# args = parser.parse_args()
args.gpu = int(args.gpu) if args.gpu is not None else 0
args.distributed = False
device = torch.device('cuda:{}'.format(args.gpu))
test = DepthDataLoader(args, 'online_eval').data
model = UnetAdaptiveBins.build(n_bins=args.n_bins, min_val=args.min_depth, max_val=args.max_depth,
norm='linear').to(device)
model = model_io.load_checkpoint(args.checkpoint_path, model)[0]
model = model.eval()
eval(model, test, args, gpus=[device])