-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtester.py
143 lines (116 loc) · 5.65 KB
/
tester.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
import os
import cv2
import logging
import tqdm
import numpy as np
import time
import torch
import torch.nn.functional as F
import torch.nn.utils as nn_utils
import torch.backends.cudnn as cudnn
import torch.optim.lr_scheduler as lr_scheduler
import utils
from utils import CONFIG
import networks
from utils import comput_sad_loss, compute_connectivity_error, \
compute_gradient_loss, compute_mse_loss
class Tester(object):
def __init__(self, test_dataloader):
# cudnn.benchmark = True
self.test_dataloader = test_dataloader
self.logger = logging.getLogger("Logger")
self.model_config = CONFIG.model
self.test_config = CONFIG.test
self.log_config = CONFIG.log
self.data_config = CONFIG.data
self.build_model()
self.resume_step = None
utils.print_network(self.G, CONFIG.version)
if self.test_config.checkpoint:
self.logger.info('Resume checkpoint: {}'.format(self.test_config.checkpoint))
self.restore_model(self.test_config.checkpoint)
def build_model(self):
self.G = networks.get_generator(encoder=self.model_config.arch.encoder, decoder=self.model_config.arch.decoder)
if not self.test_config.cpu:
self.G.cuda()
if self.test_config.fp16:
self.G = self.G.half()
def restore_model(self, resume_checkpoint):
"""
Restore the trained generator and discriminator.
:param resume_checkpoint: File name of checkpoint
:return:
"""
pth_path = os.path.join(self.log_config.checkpoint_path, '{}.pth'.format(resume_checkpoint))
checkpoint = torch.load(pth_path)
# self.resume_step = checkpoint['iter']
# self.logger.info('Loading the trained models from step {}...'.format(self.resume_step))
self.G.load_state_dict(utils.remove_prefix_state_dict(checkpoint['state_dict']), strict=True)
def test(self):
self.G = self.G.eval()
mse_loss = 0
sad_loss = 0
conn_loss = 0
grad_loss = 0
test_num = 0
all_time = 0
with torch.no_grad():
for image_dict in self.test_dataloader:
image, alpha, trimap = image_dict['image'], image_dict['alpha'], image_dict['trimap']
alpha_shape, name = image_dict['alpha_shape'], image_dict['image_name']
if not self.test_config.cpu:
image = image.cuda()
alpha = alpha.cuda()
trimap = trimap.cuda()
if self.test_config.fp16:
image = image.half()
alpha = alpha.half()
trimap = trimap.half()
t1 = time.time()
if not CONFIG.test.TTA:
alpha_pred, _ = self.G(image, trimap)
else:
alpha_pred = torch.zeros_like(image[:, :1, :, :])
for rot in range(4):
alpha_tmp, _ = self.G(image.rot90(rot, [2, 3]), trimap.rot90(rot, [2, 3]))
alpha_pred += alpha_tmp.rot90(rot, [3, 2])
alpha_tmp, _ = self.G(image.flip(3).rot90(rot, [2, 3]), trimap.flip(3).rot90(rot, [2, 3]))
alpha_pred += alpha_tmp.rot90(rot, [3, 2]).flip(3)
alpha_pred = alpha_pred / 8
torch.cuda.synchronize()
all_time += time.time() - t1
# if self.data_config.extreme_aug:
# trimap_reverse = trimap[:,[2,1,0],...]
# alpha_reverse, _ = self.G(image, trimap_reverse)
# alpha_pred = (alpha_pred + 1 - alpha_reverse) / 2
if self.model_config.trimap_channel == 3:
trimap = trimap.argmax(dim=1, keepdim=True)
alpha_pred[trimap == 2] = 1
alpha_pred[trimap == 0] = 0
trimap[trimap==2] = 255
trimap[trimap==1] = 128
for cnt in range(image.shape[0]):
h, w = alpha_shape
test_alpha = alpha[cnt, 0, ...].data.cpu().numpy() * 255
test_pred = alpha_pred[cnt, 0, ...].data.cpu().numpy() * 255
test_pred = test_pred.astype(np.uint8)
test_trimap = trimap[cnt, 0, ...].data.cpu().numpy()
test_pred = test_pred[:h, :w]
test_trimap = test_trimap[:h, :w]
if self.test_config.alpha_path is not None:
cv2.imwrite(os.path.join(self.test_config.alpha_path, os.path.splitext(name[cnt])[0] + ".png"),
test_pred)
mse_loss += compute_mse_loss(test_pred, test_alpha, test_trimap)
self.logger.info("{} {}".format(name, comput_sad_loss(test_pred, test_alpha, test_trimap)[0]))
sad_loss += comput_sad_loss(test_pred, test_alpha, test_trimap)[0]
if not self.test_config.fast_eval:
# conn_loss += compute_connectivity_error(test_pred, test_alpha, test_trimap, 0.1)
grad_loss += compute_gradient_loss(test_pred, test_alpha, test_trimap)
test_num += 1
self.logger.info("TEST NUM: \t\t {}".format(test_num))
self.logger.info("MSE: \t\t {}".format(mse_loss / test_num))
self.logger.info("SAD: \t\t {}".format(sad_loss / test_num))
if not self.test_config.fast_eval:
self.logger.info("GRAD: \t\t {}".format(grad_loss / test_num))
# self.logger.info("CONN: \t\t {}".format(conn_loss / test_num))
self.logger.info("TIME: {}".format(all_time))