-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutility.py
More file actions
192 lines (143 loc) · 4.58 KB
/
Copy pathutility.py
File metadata and controls
192 lines (143 loc) · 4.58 KB
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
import math
import time
import random
import numpy as np
import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lrs
import cv2
from skimage.measure import compare_ssim
import os
import matplotlib.pyplot as plt
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.device_count() == 1:
torch.cuda.manual_seed(seed)
else:
torch.cuda.manual_seed_all(seed)
class timer():
def __init__(self):
self.acc = 0
self.tic()
def tic(self):
self.t0 = time.time()
def toc(self):
return time.time() - self.t0
def hold(self):
self.acc += self.toc()
def release(self):
ret = self.acc
self.acc = 0
return ret
def reset(self):
self.acc = 0
def quantize(img, rgb_range):
pixel_range = 255 / rgb_range
return img.mul(pixel_range).clamp(0, 255).round().div(pixel_range)
def calc_psnr(sr, hr, scale, rgb_range, benchmark=False):
if sr.size(-2) > hr.size(-2) or sr.size(-1) > hr.size(-1):
print("the dimention of sr image is not equal to hr's! ")
sr = sr[:,:,:hr.size(-2),:hr.size(-1)]
diff = (sr - hr).data.div(rgb_range)
if benchmark:
shave = scale
if diff.size(1) > 1:
convert = diff.new(1, 3, 1, 1)
convert[0, 0, 0, 0] = 65.738
convert[0, 1, 0, 0] = 129.057
convert[0, 2, 0, 0] = 25.064
diff.mul_(convert).div_(256)
diff = diff.sum(dim=1, keepdim=True)
else:
shave = scale + 6
valid = diff[:, :, shave:-shave, shave:-shave]
mse = valid.pow(2).mean()
return -10 * math.log10(mse)
def SSIM(original, compressed):
# Convert the images to grayscale
grayA = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(compressed, cv2.COLOR_BGR2GRAY)
# Compute the Structural Similarity Index (SSIM) between the two
# images, ensuring that the difference image is returned
(score, diff) = compare_ssim(grayA, grayB, full=True)
diff = (diff * 255).astype("uint8")
# 6. You can print only the score if you want
# print(f"SSIM value is {score}")
return score
def make_optimizer(opt, my_model):
trainable = filter(lambda x: x.requires_grad, my_model.parameters())
optimizer_function = optim.Adam
kwargs = {
'betas': (opt.beta1, opt.beta2),
'eps': opt.epsilon
}
kwargs['lr'] = opt.lr
kwargs['weight_decay'] = opt.weight_decay
return optimizer_function(trainable, **kwargs)
def make_dual_optimizer(opt, dual_models):
dual_optimizers = []
for dual_model in dual_models:
temp_dual_optim = torch.optim.Adam(
params=dual_model.parameters(),
lr = opt.lr,
betas = (opt.beta1, opt.beta2),
eps = opt.epsilon,
weight_decay=opt.weight_decay)
dual_optimizers.append(temp_dual_optim)
return dual_optimizers
def make_scheduler(opt, my_optimizer):
scheduler = lrs.CosineAnnealingLR(
my_optimizer,
float(opt.epochs),
eta_min=opt.eta_min
)
return scheduler
def make_dual_scheduler(opt, dual_optimizers):
dual_scheduler = []
for i in range(len(dual_optimizers)):
scheduler = lrs.CosineAnnealingLR(
dual_optimizers[i],
float(opt.epochs),
eta_min=opt.eta_min
)
dual_scheduler.append(scheduler)
return dual_scheduler
def init_model(args):
# Set the templates here
if args.model.find('DRN-S') >= 0:
if args.scale == 4:
args.n_blocks = 30
args.n_feats = 16
elif args.scale == 8:
args.n_blocks = 30
args.n_feats = 8
else:
print('Use defaults n_blocks and n_feats.')
args.dual = True
if args.model.find('DRN-L') >= 0:
if args.scale == 4:
args.n_blocks = 40
args.n_feats = 20
elif args.scale == 8:
args.n_blocks = 36
args.n_feats = 10
else:
print('Use defaults n_blocks and n_feats.')
args.dual = True
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 17:59:00 2020
@author: user
"""
def graph(X, savefolder, typeof='GRAD', Xlab='iteration'):
plt.figure()
plt.title('graph')
coloring = 'red'
plt.xlabel(Xlab)
plt.ylabel(typeof)
plt.plot(X, label='previous '+typeof, color=coloring, linestyle='dashed', marker='o',
markersize =3, markerfacecolor=coloring)
plt.savefig(savefolder+typeof+'.jpg')
plt.close()