forked from yxgeee/FD-GAN
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.py
150 lines (134 loc) · 6.11 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
import os, sys
import os.path as osp
import time
import numpy as np
import types
import torch
from torch.utils.data import DataLoader
from torch.nn import functional as F
from torch.autograd import Variable
from reid import datasets
from reid.utils.data.preprocessor import Preprocessor
from reid.utils.data.sampler import RandomPairSampler
from reid.utils.data import transforms as T
from reid.evaluators import CascadeEvaluator
from fdgan.options import Options
from fdgan.utils.visualizer import Visualizer
from fdgan.model import FDGANModel
import scipy
def get_data(name, data_dir, height, width, batch_size, workers, pose_aug):
root = osp.join(data_dir, name)
dataset = datasets.create(name, root)
# use combined trainval set for training as default
preprocessor = Preprocessor(dataset.trainval, root=dataset.images_dir, with_pose=True, pose_root=dataset.poses_dir, pid_imgs=dataset.trainval_query, height=height, width=width, pose_aug=pose_aug)
train_loader = DataLoader(
preprocessor,
sampler=RandomPairSampler(dataset.trainval, neg_pos_ratio=3),
batch_size=batch_size, num_workers=workers, pin_memory=False)
test_transformer = T.Compose([
T.RectScale(height, width),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
test_loader = DataLoader(
Preprocessor(list(set(dataset.query) | set(dataset.gallery)),
root=dataset.images_dir, transform=test_transformer),
batch_size=batch_size, num_workers=workers,
shuffle=False, pin_memory=False)
return dataset, train_loader, test_loader
######################################################################
# recover image
# -----------------
def recover(inp):
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = inp * 255.0
inp = np.clip(inp, 0, 255)
return inp
def main():
opt = Options().parse()
dataset, train_loader, test_loader = get_data(opt.dataset, opt.dataroot, opt.height, opt.width, opt.batch_size, opt.workers, opt.pose_aug)
dataset_size = len(dataset.trainval)*4
print('#training images = %d' % dataset_size)
model = FDGANModel(opt)
#visualizer = Visualizer(opt)
'''
evaluator = CascadeEvaluator(
torch.nn.DataParallel(model.net_E.module.base_model).cuda(),
model.net_E.module.embed_model,
embed_dist_fn=lambda x: F.softmax(Variable(x), dim=1).data[:, 0])
if opt.stage!=1:
print('Test with baseline model:')
top1, mAP = evaluator.evaluate(test_loader, dataset.query, dataset.gallery, rerank_topk=100, dataset=opt.dataset)
message = '\n Test with baseline model: mAP: {:5.1%} top1: {:5.1%}\n'.format(mAP, top1)
visualizer.print_reid_results(message)
'''
total_steps = 0
best_mAP = 0
for epoch in range(1, opt.niter + opt.niter_decay + 1):
epoch_start_time = time.time()
epoch_iter = 0
model.reset_model_status()
if epoch == 2:
break
target_path = '/home/zzd/FD-GAN/test'
for i, data in enumerate(train_loader):
iter_start_time = time.time()
#visualizer.reset()
total_steps += opt.batch_size
epoch_iter += opt.batch_size
model.set_input(data)
fake_img = model.forward()
#print (fake_img.shape)
#model.optimize_parameters()
fake_img = fake_img.cpu()
print (i)
for j in range(opt.batch_size):
save_img = np.zeros(fake_img.shape[1:])
save_img = fake_img[j,:,:,:]
save_img = recover(save_img)
#save_img = np.reshape(save_img, (fake_img.shape[1:]))
save_name = data[0]['origin_name'][j] + 'to' + data[0]['target_name'][j] + '.jpg'
#save_name = data[0]['target_name'][j] + '.jpg' # save one target.
img_path = os.path.join(target_path, save_name)
scipy.misc.imsave(img_path, save_img)
'''
if total_steps % opt.display_freq == 0:
save_result = total_steps % opt.update_html_freq == 0
visualizer.display_current_results(model.get_current_visuals(), epoch, save_result)
if total_steps % opt.print_freq == 0:
errors = model.get_current_errors()
t = (time.time() - iter_start_time) / opt.batch_size
visualizer.print_current_errors(epoch, epoch_iter, errors, t)
if opt.display_id > 0:
visualizer.plot_current_errors(epoch, float(epoch_iter)/dataset_size, opt, errors)
if epoch % opt.save_step == 0:
print('saving the model at the end of epoch %d, iters %d' % (epoch, total_steps))
model.save(epoch)
if epoch % opt.eval_step == 0 and opt.stage!=1:
mAP = evaluator.evaluate(val_loader, dataset.val, dataset.val, top1=False)
is_best = mAP > best_mAP
best_mAP = max(mAP, best_mAP)
if is_best:
model.save('best')
message = '\n * Finished epoch {:3d} mAP: {:5.1%} best: {:5.1%}{}\n'.format(epoch, mAP, best_mAP, ' *' if is_best else '')
visualizer.print_reid_results(message)
print('End of epoch %d / %d \t Time Taken: %d sec' %
(epoch, opt.niter + opt.niter_decay, time.time() - epoch_start_time))
model.update_learning_rate()
'''
# Final test
'''
if opt.stage!=1:
print('Test with best model:')
checkpoint = load_checkpoint(osp.join(opt.checkpoints, opt.name, '%s_net_%s.pth' % ('best', 'E')))
model.net_E.load_state_dict(checkpoint)
top1, mAP = evaluator.evaluate(test_loader, dataset.query, dataset.gallery, rerank_topk=100, dataset=opt.dataset)
message = '\n Test with best model: mAP: {:5.1%} top1: {:5.1%}\n'.format(mAP, top1)
visualizer.print_reid_results(message)
'''
if __name__ == '__main__':
main()