-
Notifications
You must be signed in to change notification settings - Fork 23
/
test.py
208 lines (160 loc) · 6.45 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
from libs.dataset.data import ROOT, build_dataset, multibatch_collate_fn
from libs.dataset.transform import TrainTransform, TestTransform
from libs.utils.logger import Logger, AverageMeter
from libs.utils.loss import *
from libs.utils.utility import parse_args, write_mask, save_checkpoint, adjust_learning_rate, mask_iou
from libs.models.models import STAN
from libs.config import getCfg
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import libs.utils.logger as logger
import numpy as np
import os
import os.path as osp
import shutil
import time
import pickle
import cv2
import argparse
from progress.bar import Bar
from collections import OrderedDict
# from options import OPTION as opt
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
MAX_FLT = 1e6
# parse args
opt, _ = parse_args()
# Use CUDA
device = 'cuda:{}'.format(opt.gpu_id)
use_gpu = torch.cuda.is_available() and int(opt.gpu_id) >= 0
logger.setup(filename='test_out.log', resume=False)
log = logger.getLogger(__name__)
def main():
# Data
log.info('Preparing dataset %s' % opt.valset)
input_dim = opt.input_size
test_transformer = TestTransform(size=input_dim)
testset = build_dataset(
name=opt.valset,
train=False,
transform=test_transformer,
samples_per_video=1
)
testloader = data.DataLoader(testset, batch_size=1, shuffle=False, num_workers=opt.workers,
collate_fn=multibatch_collate_fn)
# Model
log.info("Creating model")
net = STAN(opt)
log.info('Total params: %.2fM' % (sum(p.numel() for p in net.parameters())/1000000.0))
# set eval to freeze batchnorm update
net.eval()
if use_gpu:
net.to(device)
# set training parameters
for p in net.parameters():
p.requires_grad = False
# Resume
title = 'STAN'
if opt.initial:
# Load checkpoint.
log.info('Loading weights from checkpoint {}'.format(opt.initial))
assert os.path.isfile(opt.initial), 'Error: no checkpoint directory found!'
checkpoint = torch.load(opt.initial, map_location=device)
try:
net.load_param(checkpoint['state_dict'])
except:
net.load_param(checkpoint)
# Train and val
log.info('Runing model on dataset {}, totally {:d} videos'.format(opt.valset, len(testloader)))
test(testloader,
model=net,
use_cuda=use_gpu,
opt=opt)
log.info('Results are saved at: {}'.format(os.path.join(ROOT, opt.output_dir, opt.valset)))
def test(testloader, model, use_cuda, opt):
data_time = AverageMeter()
criterion = lambda pred, target, obj: cross_entropy_loss(pred, target, obj) + mask_iou_loss(pred, target, obj)
# with torch.no_grad():
for p in model.parameters():
p.requires_grad = False
for batch_idx, data in enumerate(testloader):
frames, masks, objs, infos = data
if use_cuda:
frames = frames.to(device)
masks = masks.to(device)
frames = frames[0]
masks = masks[0]
num_objects = objs[0]
info = infos[0]
max_obj = masks.shape[1]-1
T, _, H, W = frames.shape
prev = frames.new_zeros((1, 3, H, W))
prev_mask = frames.new_zeros((1, num_objects+1, H, W))
bar = Bar('video {}: {}'.format(batch_idx+1, info['name']), max=T-1)
log.info('Runing video {}, objects {:d}'.format(info['name'], num_objects))
# compute output
pred = [masks[0:1]]
keys = []
vals = []
ref_mask = None
for t in range(1, T):
with torch.no_grad():
if t-1 == 0:
tmp_mask = masks[0:1]
ref_mask = tmp_mask
ref_index = 0
elif 'frame' in info and t-1 < len(info['frame']['imgs']) and info['frame']['imgs'][t-1] in info['frame']['masks']:
# start frame
mask_stamp = info['frame']['imgs'][t-1]
mask_id = info['frame']['masks'].index(mask_stamp)
tmp_mask = masks[mask_id:mask_id+1]
num_objects = max(num_objects, tmp_mask.max())
ref_mask = tmp_mask
ref_index = t-1
# pred[-1] = tmp_mask
else:
tmp_mask = out
# tmp_mask = masks[t-1:t]
t1 = time.time()
# memorize
key, val, _ = model(frame=frames[t-1:t], mask=tmp_mask, num_objects=num_objects)
# segment
tmp_key = torch.cat(keys+[key], dim=1)
tmp_val = torch.cat(vals+[val], dim=1)
logits, ps = model(frame=frames[t:t+1], keys=tmp_key, values=tmp_val,
num_objects=num_objects, max_obj=max_obj)
out = torch.softmax(logits, dim=1)
if (t-1) % opt.save_freq == 0:
keys.append(key)
vals.append(val)
pred.append(out)
if t % opt.save_freq == 0:
# internal loop
for m in range(opt.loop):
tmp_mask = out.detach().clone()
tmp_mask.requires_grad = True
key, val, _ = model(frame=frames[t:t+1], mask=tmp_mask, num_objects=num_objects)
flogits, _ = model(frame=frames[ref_index:ref_index+1], keys=key, values=val,
num_objects=num_objects, max_obj=max_obj)
fout = torch.softmax(flogits, 1)
loss = criterion(fout, ref_mask, num_objects)
loss.backward()
out = out - opt.correction_rate * tmp_mask.grad
toc = time.time() - t1
data_time.update(toc, 1)
# plot progress
bar.suffix = '({batch}/{size}) Time: {data:.3f}s'.format(
batch=t,
size=T-1,
data=data_time.sum
)
bar.next()
bar.finish()
pred = torch.cat(pred, dim=0)
pred = pred.detach().cpu().numpy()
write_mask(pred, info, opt, directory=opt.output_dir)
return
if __name__ == '__main__':
main()