-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrainer.py
306 lines (260 loc) · 12.5 KB
/
trainer.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
294
295
296
297
298
299
300
301
302
303
304
305
306
import Vgg19
import os
import numpy as np
from imageio import imread, imsave
from PIL import Image
import math
import cv2
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.utils as utils
def calc_psnr(img1, img2):
### args:
# img1: [h, w, c], range [0, 255]
# img2: [h, w, c], range [0, 255]
diff = (img1 - img2) / 255.0
diff[:,:,0] = diff[:,:,0] * 65.738 / 256.0
diff[:,:,1] = diff[:,:,1] * 129.057 / 256.0
diff[:,:,2] = diff[:,:,2] * 25.064 / 256.0
diff = np.sum(diff, axis=2)
mse = np.mean(np.power(diff, 2))
return -10 * math.log10(mse)
def calc_ssim(img1, img2):
def ssim(img1, img2):
C1 = (0.01 * 255)**2
C2 = (0.03 * 255)**2
img1 = img1.astype(np.float64)
img2 = img2.astype(np.float64)
kernel = cv2.getGaussianKernel(11, 1.5)
window = np.outer(kernel, kernel.transpose())
mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid
mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
mu1_sq = mu1**2
mu2_sq = mu2**2
mu1_mu2 = mu1 * mu2
sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq
sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq
sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *
(sigma1_sq + sigma2_sq + C2))
return ssim_map.mean()
### args:
# img1: [h, w, c], range [0, 255]
# img2: [h, w, c], range [0, 255]
# the same outputs as MATLAB's
border = 0
img1_y = np.dot(img1, [65.738,129.057,25.064])/256.0+16.0
img2_y = np.dot(img2, [65.738,129.057,25.064])/256.0+16.0
if not img1.shape == img2.shape:
raise ValueError('Input images must have the same dimensions.')
h, w = img1.shape[:2]
img1_y = img1_y[border:h-border, border:w-border]
img2_y = img2_y[border:h-border, border:w-border]
if img1_y.ndim == 2:
return ssim(img1_y, img2_y)
elif img1.ndim == 3:
if img1.shape[2] == 3:
ssims = []
for i in range(3):
ssims.append(ssim(img1, img2))
return np.array(ssims).mean()
elif img1.shape[2] == 1:
return ssim(np.squeeze(img1), np.squeeze(img2))
else:
raise ValueError('Wrong input image dimensions.')
def calc_psnr_and_ssim(sr, hr):
### args:
# sr: pytorch tensor, range [-1, 1]
# hr: pytorch tensor, range [-1, 1]
### prepare data
sr = (sr+1.) * 127.5
hr = (hr+1.) * 127.5
if (sr.size() != hr.size()):
h_min = min(sr.size(2), hr.size(2))
w_min = min(sr.size(3), hr.size(3))
sr = sr[:, :, :h_min, :w_min]
hr = hr[:, :, :h_min, :w_min]
img1 = np.transpose(sr.squeeze().round().cpu().numpy(), (1,2,0))
img2 = np.transpose(hr.squeeze().round().cpu().numpy(), (1,2,0))
psnr = calc_psnr(img1, img2)
ssim = calc_ssim(img1, img2)
return psnr, ssim
class Trainer():
def __init__(self, args, dataloader, model, loss_all):
self.args = args
self.dataloader = dataloader
self.model = model
self.loss_all = loss_all
self.device = torch.device('cpu') if args.cpu else torch.device('cuda')
self.vgg19 = Vgg19.Vgg19(requires_grad=False).to(self.device)
if ((not self.args.cpu) and (self.args.num_gpu > 1)):
self.vgg19 = nn.DataParallel(self.vgg19, list(range(self.args.num_gpu)))
self.params = [
{"params": filter(lambda p: p.requires_grad, self.model.MainNet.parameters() if
args.num_gpu==1 else self.model.module.MainNet.parameters()),
"lr": args.lr_rate
},
{"params": filter(lambda p: p.requires_grad, self.model.LTE.parameters() if
args.num_gpu==1 else self.model.module.LTE.parameters()),
"lr": args.lr_rate_lte
}
]
self.optimizer = optim.Adam(self.params, betas=(args.beta1, args.beta2), eps=args.eps)
self.scheduler = optim.lr_scheduler.StepLR(
self.optimizer, step_size=self.args.decay, gamma=self.args.gamma)
self.max_psnr = 0.
self.max_psnr_epoch = 0
self.max_ssim = 0.
self.max_ssim_epoch = 0
self.SSS=0
def load(self, model_path=None):
if (model_path):
print('load_model_path: ' + model_path)
#model_state_dict_save = {k.replace('module.',''):v for k,v in torch.load(model_path).items()}
model_state_dict_save = {k:v for k,v in torch.load(model_path).items()}
model_state_dict = self.model.state_dict()
model_state_dict.update(model_state_dict_save)
self.model.load_state_dict(model_state_dict)
def prepare(self, sample_batched):
for key in sample_batched.keys():
sample_batched[key] = sample_batched[key].to(self.device)
return sample_batched
def train(self, current_epoch=0, is_init=False):
self.model.train()
if (not is_init):
self.scheduler.step()
print('Current epoch learning rate: %e' %(self.optimizer.param_groups[0]['lr']))
start = time.clock()
for i_batch, sample_batched in enumerate(self.dataloader['train']):
self.optimizer.zero_grad()
sample_batched = self.prepare(sample_batched)
lr = sample_batched['LR']
lr_sr = sample_batched['LR_sr']
hr = sample_batched['HR']
ref = sample_batched['Ref']
ref_sr = sample_batched['Ref_sr']
sr, S, T_lv3, T_lv2, T_lv1 = self.model(lr=lr, lrsr=lr_sr, ref=ref, refsr=ref_sr)
self.SSS=S
### calc loss
is_print = ((i_batch + 1) % self.args.print_every == 0) ### flag of print
rec_loss = self.args.rec_w * self.loss_all['rec_loss'](sr, hr) #重建误差,用l1
loss = rec_loss
if (is_print):
print( ('init ' if is_init else '') + 'epoch: ' + str(current_epoch) +
'\t batch: ' + str(i_batch+1) )
print( 'rec_loss: %.10f' %(rec_loss.item()) )
if (not is_init):
if ('per_loss' in self.loss_all):
#print('1111',sr)
#print('2222',(sr + 1.) / 2)
sr_relu5_1 = self.vgg19((sr + 1.) / 2.)
with torch.no_grad():
hr_relu5_1 = self.vgg19((hr.detach() + 1.) / 2.)
per_loss = self.args.per_w * self.loss_all['per_loss'](sr_relu5_1, hr_relu5_1)
loss += per_loss
if (is_print):
print( 'per_loss: %.10f' %(per_loss.item()) )
if ('tpl_loss' in self.loss_all):
sr_lv1, sr_lv2, sr_lv3 = self.model(sr=sr)
tpl_loss = self.args.tpl_w * self.loss_all['tpl_loss'](sr_lv3, sr_lv2, sr_lv1,
S, T_lv3, T_lv2, T_lv1)
loss += tpl_loss
if (is_print):
print( 'tpl_loss: %.10f' %(tpl_loss.item()) )
if ('adv_loss' in self.loss_all):
adv_loss = self.args.adv_w * self.loss_all['adv_loss'](sr, hr)
loss += adv_loss
if (is_print):
print( 'adv_loss: %.10f' %(adv_loss.item()) )
loss.backward()
self.optimizer.step()
if (is_print):
print("Time used:",(time.clock() - start),"s")
if ((not is_init) and current_epoch % self.args.save_every == 0):
print('saving the model...')
tmp = self.model.state_dict()
model_state_dict = {key.replace('module.',''): tmp[key] for key in tmp if
(('SearchNet' not in key) and ('_copy' not in key))}
model_name = 'model_save/'+'model_'+str(current_epoch).zfill(5)+'.pt'
torch.save(model_state_dict, model_name)
def evaluate(self, current_epoch=0):
print('Epoch ' + str(current_epoch) + ' evaluation process...')
if (self.args.dataset == 'CUFED'):
self.model.eval()
with torch.no_grad():
psnr, ssim, cnt = 0., 0., 0
for i_batch, sample_batched in enumerate(self.dataloader['test']['1']):
cnt += 1
sample_batched = self.prepare(sample_batched)
lr = sample_batched['LR']
lr_sr = sample_batched['LR_sr']
hr = sample_batched['HR']
ref = sample_batched['Ref']
ref_sr = sample_batched['Ref_sr']
sr, _, _, _, _ = self.model(lr=lr, lrsr=lr_sr, ref=ref, refsr=ref_sr)
if (self.args.eval_save_results):
sr_save = (sr+1.) * 127.5
sr_save = np.transpose(sr_save.squeeze().round().cpu().numpy(), (1, 2, 0)).astype(np.uint8)
imsave(os.path.join(self.args.save_dir, 'save_results', str(i_batch).zfill(5)+'.png'), sr_save)
### calculate psnr and ssim
_psnr, _ssim = calc_psnr_and_ssim(sr.detach(), hr.detach())
psnr += _psnr
ssim += _ssim
psnr_ave = psnr / cnt
ssim_ave = ssim / cnt
print('Ref PSNR (now): %.3f \t SSIM (now): %.4f' %(psnr_ave, ssim_ave))
if (psnr_ave > self.max_psnr):
self.max_psnr = psnr_ave
self.max_psnr_epoch = current_epoch
if (ssim_ave > self.max_ssim):
self.max_ssim = ssim_ave
self.max_ssim_epoch = current_epoch
print('Ref PSNR (max): %.3f (%d) \t SSIM (max): %.4f (%d)'
%(self.max_psnr, self.max_psnr_epoch, self.max_ssim, self.max_ssim_epoch))
print('Evaluation over.')
def test(self):
print('Test process...')
print('lr path: %s' %(self.args.lr_path))
print('ref path: %s' %(self.args.ref_path))
### LR and LR_sr
img = Image.open(self.args.lr_path).convert("RGB")
img.save(self.args.lr_path)
LR = imread(self.args.lr_path)
h1, w1 = LR.shape[:2]
LR_sr = np.array(Image.fromarray(LR).resize((w1*4, h1*4), Image.BICUBIC))
### Ref and Ref_sr
img = Image.open(self.args.ref_path).convert("RGB")
img.save(self.args.ref_path)
Ref = imread(self.args.ref_path)
h2, w2 = Ref.shape[:2]
h2, w2 = h2//4*4, w2//4*4
Ref = Ref[:h2, :w2, :]
Ref_sr = np.array(Image.fromarray(Ref).resize((w2//4, h2//4), Image.BICUBIC))
Ref_sr = np.array(Image.fromarray(Ref_sr).resize((w2, h2), Image.BICUBIC))
### change type
LR = LR.astype(np.float32)
LR_sr = LR_sr.astype(np.float32)
Ref = Ref.astype(np.float32)
Ref_sr = Ref_sr.astype(np.float32)
### rgb range to [-1, 1]
LR = LR / 127.5 - 1.
LR_sr = LR_sr / 127.5 - 1.
Ref = Ref / 127.5 - 1.
Ref_sr = Ref_sr / 127.5 - 1.
### to tensor
LR_t = torch.from_numpy(LR.transpose((2,0,1))).unsqueeze(0).float().to(self.device)
LR_sr_t = torch.from_numpy(LR_sr.transpose((2,0,1))).unsqueeze(0).float().to(self.device)
Ref_t = torch.from_numpy(Ref.transpose((2,0,1))).unsqueeze(0).float().to(self.device)
Ref_sr_t = torch.from_numpy(Ref_sr.transpose((2,0,1))).unsqueeze(0).float().to(self.device)
self.model.eval()
with torch.no_grad():
sr, _, _, _, _ = self.model(lr=LR_t, lrsr=LR_sr_t, ref=Ref_t, refsr=Ref_sr_t)
sr_save = (sr+1.) * 127.5
sr_save = np.transpose(sr_save.squeeze().round().cpu().numpy(), (1, 2, 0)).astype(np.uint8)
save_path = os.path.join(self.args.save_dir, 'save_result', os.path.basename(self.args.lr_path))
imsave(save_path, sr_save)
print('output path: %s' %(save_path))
print('Test over.')