-
Notifications
You must be signed in to change notification settings - Fork 2
/
test.py
294 lines (227 loc) · 13.2 KB
/
test.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
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import utils
import numpy as np
import argparse
from model import FNAC
from datasets import get_test_dataset, inverse_normalize, get_test_dataset_2
import cv2
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--model_dir', type=str, default='./checkpoints', help='path to save trained model weights')
parser.add_argument('--experiment_name', type=str, default='ezvsl_vggss', help='experiment name (experiment folder set to "args.model_dir/args.experiment_name)"')
parser.add_argument('--save_visualizations', action='store_true', help='Set to store all VSL visualizations (saved in viz directory within experiment folder)')
# Dataset
parser.add_argument('--testset', default='flickr', type=str, help='testset (flickr or vggss)')
parser.add_argument('--test_data_path', default='', type=str, help='Root directory path of data')
parser.add_argument('--test_gt_path', default='', type=str)
parser.add_argument('--batch_size', default=1, type=int, help='Batch Size')
# Model
parser.add_argument('--tau', default=0.03, type=float, help='tau')
parser.add_argument('--out_dim', default=512, type=int)
parser.add_argument('--alpha', default=0.4, type=float, help='alpha')
parser.add_argument("--dropout_img", type=float, default=0, help="dropout for image")
parser.add_argument("--dropout_aud", type=float, default=0, help="dropout for audio")
# Distributed params
parser.add_argument('--workers', type=int, default=8)
parser.add_argument('--gpu', type=int, default=None)
parser.add_argument('--world_size', type=int, default=1)
parser.add_argument('--rank', type=int, default=0)
parser.add_argument('--node', type=str, default='localhost')
parser.add_argument('--port', type=int, default=12345)
parser.add_argument('--dist_url', type=str, default='tcp://localhost:12345')
parser.add_argument('--multiprocessing_distributed', default=False)
return parser.parse_args()
def main(args):
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# Model dir
model_dir = os.path.join(args.model_dir, args.experiment_name)
viz_dir = os.path.join(model_dir, 'viz')
os.makedirs(viz_dir, exist_ok=True)
# Models
audio_visual_model = FNAC(args.tau, args.out_dim, args.dropout_img, args.dropout_aud)
from torchvision.models import resnet18
object_saliency_model = resnet18(pretrained=True)
object_saliency_model.avgpool = nn.Identity()
object_saliency_model.fc = nn.Sequential(
nn.Unflatten(1, (512, 7, 7)),
NormReducer(dim=1),
Unsqueeze(1)
)
if not torch.cuda.is_available():
print('using CPU, this will be slow')
elif args.multiprocessing_distributed:
if args.gpu is not None:
torch.cuda.set_device(args.gpu)
audio_visual_model.cuda(args.gpu)
object_saliency_model.cuda(args.gpu)
audio_visual_model = torch.nn.parallel.DistributedDataParallel(audio_visual_model, device_ids=[args.gpu])
object_saliency_model = torch.nn.parallel.DistributedDataParallel(object_saliency_model, device_ids=[args.gpu])
audio_visual_model.cuda(args.gpu)
object_saliency_model.cuda(args.gpu)
# Load weights
ckp_fn = os.path.join(model_dir, 'best.pth')
if os.path.exists(ckp_fn):
ckp = torch.load(ckp_fn, map_location='cpu')
audio_visual_model.load_state_dict({k.replace('module.', ''): ckp['model'][k] for k in ckp['model']})
print(f'loaded from {os.path.join(model_dir, "best.pth")}')
else:
print(f"Checkpoint not found: {ckp_fn}")
# Dataloader
if args.testset == 'flickr':
testdataset = get_test_dataset(args)
else:
testdataset = get_test_dataset_2(args)
testdataloader = DataLoader(testdataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers)
print("Loaded dataloader.")
# cIoU, auc = validate2(testdataloader, audio_visual_model, args)
# print(f'cIoU (epoch ): {cIoU}')
# print(f'AUC (epoch ): {auc}')
validate(testdataloader, audio_visual_model, object_saliency_model, viz_dir, args)
validate2(testdataloader, audio_visual_model, object_saliency_model, viz_dir, args)
@torch.no_grad()
def validate(testdataloader, audio_visual_model, object_saliency_model, viz_dir, args):
audio_visual_model.train(False)
object_saliency_model.train(False)
evaluator_av = utils.Evaluator()
evaluator_obj = utils.Evaluator()
evaluator_av_obj = utils.Evaluator()
for step, (image, spec, bboxes, name) in enumerate(testdataloader):
if args.gpu is not None:
spec = spec.cuda(args.gpu, non_blocking=True)
image = image.cuda(args.gpu, non_blocking=True)
# print( image.get_device(), spec.get_device())
# Compute S_AVL
heatmap_av = audio_visual_model(image.float(), spec.float())[1].unsqueeze(1)
heatmap_av = F.interpolate(heatmap_av, size=(224, 224), mode='bilinear', align_corners=True)
heatmap_av = heatmap_av.data.cpu().numpy()
# Compute S_OBJ
img_feat = object_saliency_model(image)
heatmap_obj = F.interpolate(img_feat, size=(224, 224), mode='bilinear', align_corners=True)
heatmap_obj = heatmap_obj.data.cpu().numpy()
# Compute eval metrics and save visualizations
for i in range(spec.shape[0]):
pred_av = utils.normalize_img(heatmap_av[i, 0])
pred_obj = utils.normalize_img(heatmap_obj[i, 0])
pred_av_obj = utils.normalize_img(pred_av * args.alpha + pred_obj * (1 - args.alpha))
gt_map = bboxes['gt_map'].data.cpu().numpy()
thr_av = np.sort(pred_av.flatten())[int(pred_av.shape[0] * pred_av.shape[1] * 0.5)]
evaluator_av.cal_CIOU(pred_av, gt_map, thr_av)
thr_obj = np.sort(pred_obj.flatten())[int(pred_obj.shape[0] * pred_obj.shape[1] * 0.5)]
evaluator_obj.cal_CIOU(pred_obj, gt_map, thr_obj)
thr_av_obj = np.sort(pred_av_obj.flatten())[int(pred_av_obj.shape[0] * pred_av_obj.shape[1] * 0.5)]
evaluator_av_obj.cal_CIOU(pred_av_obj, gt_map, thr_av_obj)
if args.save_visualizations:
denorm_image = inverse_normalize(image).squeeze(0).permute(1, 2, 0).cpu().numpy()[:, :, ::-1]
denorm_image = (denorm_image*255).astype(np.uint8)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_image.jpg'), denorm_image)
# visualize bboxes on raw images
gt_boxes_img = utils.visualize(denorm_image, bboxes['bboxes'], test_set=args.testset)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_gt_boxes.jpg'), gt_boxes_img)
# visualize heatmaps
heatmap_img = np.uint8(pred_av*255)
heatmap_img = cv2.applyColorMap(heatmap_img[:, :, np.newaxis], cv2.COLORMAP_JET)
fin = cv2.addWeighted(heatmap_img, 0.8, np.uint8(denorm_image), 0.2, 0)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_pred_av.jpg'), fin)
heatmap_img = np.uint8(pred_obj*255)
heatmap_img = cv2.applyColorMap(heatmap_img[:, :, np.newaxis], cv2.COLORMAP_JET)
fin = cv2.addWeighted(heatmap_img, 0.8, np.uint8(denorm_image), 0.2, 0)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_pred_obj.jpg'), fin)
heatmap_img = np.uint8(pred_av_obj*255)
heatmap_img = cv2.applyColorMap(heatmap_img[:, :, np.newaxis], cv2.COLORMAP_JET)
fin = cv2.addWeighted(heatmap_img, 0.8, np.uint8(denorm_image), 0.2, 0)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_pred_av_obj.jpg'), fin)
# print(f'{step+1}/{len(testdataloader)}: map_av={evaluator_av.finalize_AP50():.2f} map_obj={evaluator_obj.finalize_AP50():.2f} map_av_obj={evaluator_av_obj.finalize_AP50():.2f}')
def compute_stats(eval):
mAP = eval.finalize_AP50()
ciou = eval.finalize_cIoU()
auc = eval.finalize_AUC()
return mAP, ciou, auc
print('AV: AP50(cIoU)={}, Avg-cIoU={}, AUC={}'.format(*compute_stats(evaluator_av)))
print('Obj: AP50(cIoU)={}, Avg-cIoU={}, AUC={}'.format(*compute_stats(evaluator_obj)))
print('AV_Obj: AP50(cIoU)={}, Avg-cIoU={}, AUC={}'.format(*compute_stats(evaluator_av_obj)))
utils.save_iou(evaluator_av.ciou, 'av', viz_dir)
utils.save_iou(evaluator_obj.ciou, 'obj', viz_dir)
utils.save_iou(evaluator_av_obj.ciou, 'av_obj', viz_dir)
# we test different interpolation settings
@torch.no_grad()
def validate2(testdataloader, audio_visual_model, object_saliency_model, viz_dir, args):
audio_visual_model.train(False)
object_saliency_model.train(False)
evaluator_av = utils.Evaluator()
evaluator_obj = utils.Evaluator()
evaluator_av_obj = utils.Evaluator()
for step, (image, spec, bboxes, name) in enumerate(testdataloader):
if args.gpu is not None:
spec = spec.cuda(args.gpu, non_blocking=True)
image = image.cuda(args.gpu, non_blocking=True)
# print( image.get_device(), spec.get_device())
# Compute S_AVL
heatmap_av = audio_visual_model(image.float(), spec.float())[1].unsqueeze(1)
heatmap_av = F.interpolate(heatmap_av, size=(224, 224), mode='bicubic', align_corners=False)
heatmap_av = heatmap_av.data.cpu().numpy()
# Compute S_OBJ
img_feat = object_saliency_model(image)
heatmap_obj = F.interpolate(img_feat, size=(224, 224), mode='bilinear', align_corners=True)
heatmap_obj = heatmap_obj.data.cpu().numpy()
# Compute eval metrics and save visualizations
for i in range(spec.shape[0]):
pred_av = utils.normalize_img(heatmap_av[i, 0])
pred_obj = utils.normalize_img(heatmap_obj[i, 0])
pred_av_obj = utils.normalize_img(pred_av * args.alpha + pred_obj * (1 - args.alpha))
gt_map = bboxes['gt_map'].data.cpu().numpy()
thr_av = np.sort(pred_av.flatten())[int(pred_av.shape[0] * pred_av.shape[1] * 0.5)]
evaluator_av.cal_CIOU(pred_av, gt_map, thr_av)
thr_obj = np.sort(pred_obj.flatten())[int(pred_obj.shape[0] * pred_obj.shape[1] * 0.5)]
evaluator_obj.cal_CIOU(pred_obj, gt_map, thr_obj)
thr_av_obj = np.sort(pred_av_obj.flatten())[int(pred_av_obj.shape[0] * pred_av_obj.shape[1] * 0.5)]
evaluator_av_obj.cal_CIOU(pred_av_obj, gt_map, thr_av_obj)
if args.save_visualizations:
denorm_image = inverse_normalize(image).squeeze(0).permute(1, 2, 0).cpu().numpy()[:, :, ::-1]
denorm_image = (denorm_image*255).astype(np.uint8)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_image.jpg'), denorm_image)
# visualize bboxes on raw images
gt_boxes_img = utils.visualize(denorm_image, bboxes['bboxes'], test_set=args.testset)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_gt_boxes.jpg'), gt_boxes_img)
# visualize heatmaps
heatmap_img = np.uint8(pred_av*255)
heatmap_img = cv2.applyColorMap(heatmap_img[:, :, np.newaxis], cv2.COLORMAP_JET)
fin = cv2.addWeighted(heatmap_img, 0.8, np.uint8(denorm_image), 0.2, 0)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_pred_av.jpg'), fin)
heatmap_img = np.uint8(pred_obj*255)
heatmap_img = cv2.applyColorMap(heatmap_img[:, :, np.newaxis], cv2.COLORMAP_JET)
fin = cv2.addWeighted(heatmap_img, 0.8, np.uint8(denorm_image), 0.2, 0)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_pred_obj.jpg'), fin)
heatmap_img = np.uint8(pred_av_obj*255)
heatmap_img = cv2.applyColorMap(heatmap_img[:, :, np.newaxis], cv2.COLORMAP_JET)
fin = cv2.addWeighted(heatmap_img, 0.8, np.uint8(denorm_image), 0.2, 0)
cv2.imwrite(os.path.join(viz_dir, f'{name[i]}_pred_av_obj.jpg'), fin)
# print(f'{step+1}/{len(testdataloader)}: map_av={evaluator_av.finalize_AP50():.2f} map_obj={evaluator_obj.finalize_AP50():.2f} map_av_obj={evaluator_av_obj.finalize_AP50():.2f}')
def compute_stats(eval):
mAP = eval.finalize_AP50()
ciou = eval.finalize_cIoU()
auc = eval.finalize_AUC()
return mAP, ciou, auc
print('AV: AP50(cIoU)={}, Avg-cIoU={}, AUC={}'.format(*compute_stats(evaluator_av)))
print('Obj: AP50(cIoU)={}, Avg-cIoU={}, AUC={}'.format(*compute_stats(evaluator_obj)))
print('AV_Obj: AP50(cIoU)={}, Avg-cIoU={}, AUC={}'.format(*compute_stats(evaluator_av_obj)))
utils.save_iou(evaluator_av.ciou, 'av', viz_dir)
utils.save_iou(evaluator_obj.ciou, 'obj', viz_dir)
utils.save_iou(evaluator_av_obj.ciou, 'av_obj', viz_dir)
class NormReducer(nn.Module):
def __init__(self, dim):
super(NormReducer, self).__init__()
self.dim = dim
def forward(self, x):
return x.abs().mean(self.dim)
class Unsqueeze(nn.Module):
def __init__(self, dim):
super(Unsqueeze, self).__init__()
self.dim = dim
def forward(self, x):
return x.unsqueeze(self.dim)
if __name__ == "__main__":
main(get_arguments())