-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtest_STM.py
159 lines (121 loc) · 4.64 KB
/
test_STM.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
from dataloaders.data import ROOT, DATA_CONTAINER, multibatch_collate_fn
from dataloaders.transform import TrainTransform, TestTransform
from utils.logger import Logger, AverageMeter
from utils.loss import *
from utils.utility import write_mask, save_checkpoint, adjust_learning_rate, mask_iou
from models_STM.models_ASPP import STM
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import numpy as np
import os
import os.path as osp
import shutil
import time
import pickle
from progress.bar import Bar
from collections import OrderedDict
from options import OPTION as opt
MAX_FLT = 1e6
# Use CUDA
device = 'cuda:{}'.format(opt.gpu_id)
use_gpu = torch.cuda.is_available() and int(opt.gpu_id) >= 0
def main():
# Data
print('==> Preparing dataset %s' % opt.valset)
input_dim = opt.input_size
test_transformer = TestTransform(size=input_dim)
testset = DATA_CONTAINER[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
print("==> creating model")
net = STM(opt.keydim, opt.valdim)
print(' 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 = 'STM'
if opt.resume:
# Load checkpoint.
print('==> Resuming from checkpoint {}'.format(opt.resume))
assert os.path.isfile(opt.resume), 'Error: no checkpoint directory found!'
checkpoint = torch.load(opt.resume, map_location=device)
state = checkpoint['state_dict']
net.load_param(state)
# Train and val
print('==> Runing model on dataset {}, totally {:d} videos'.format(opt.valset, len(testloader)))
test(testloader,
model=net,
use_cuda=use_gpu,
opt=opt)
print('==> Results are saved at: {}'.format(os.path.join(ROOT, opt.output_dir, opt.valset)))
def test(testloader, model, use_cuda, opt):
data_time = AverageMeter()
with torch.no_grad():
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
bar = Bar(info['name'], max=T-1)
print('==>Runing video {}, objects {:d}'.format(info['name'], num_objects))
# compute output
pred = [masks[0:1]]
keys = []
vals = []
for t in range(1, T):
if t-1 == 0:
tmp_mask = masks[0:1]
elif 'frame' in info and t-1 in info['frame']:
# start frame
mask_id = info['frame'].index(t-1)
tmp_mask = masks[mask_id:mask_id+1]
num_objects = max(num_objects, tmp_mask.max())
else:
tmp_mask = out
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)
pred.append(out)
if (t-1) % opt.save_freq == 0 and t<100:
keys.append(key)
vals.append(val)
# _, idx = torch.max(out, dim=1)
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()