-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
243 lines (191 loc) · 7.1 KB
/
util.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
from __future__ import print_function
import numpy as np
from PIL import Image
import inspect, re
import os
from collections import OrderedDict
import random
import torch
from torch.autograd import Variable
import torch
from torch import nn
from torchvision import models, transforms
import torch.utils.model_zoo as model_zoo
def tensor2im(image_tensor, imtype=np.uint8):
image_numpy = image_tensor[0].cpu().float().numpy()
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0
return image_numpy.astype(imtype)
def get_current_visuals(input, output, input_rec, output_gt):
IN = tensor2im(input.data)
OUT = tensor2im(output.data)
IN_REC = tensor2im(input_rec.data)
OUT_GT = tensor2im(output_gt.data)
return OrderedDict([
('IN', IN),
('OUT', OUT),
('IN_REC', IN_REC),
('OUT_GT', OUT_GT),
])
def get_current_visuals1(H, R):
HR = tensor2im(H.data)
LRSR = tensor2im(R.data)
return OrderedDict([
('HR', HR),
('REC', LRSR),
])
def get_current_visuals2(L):
LR = tensor2im(L.data)
return OrderedDict([
('LR', LR),
])
##?????
def get_feamap_visuals(feamap,width, depth):
Dict = []
ncol = 8
nrow = depth/ncol
canvas=np.zeros((width*nrow, width*ncol))
name = 'name'
feamap = feamap.data[0]
# print(feamap[0:8].cpu().float().numpy().shape)
for i in range(0,nrow):
l = np.concatenate(feamap[ncol*i:ncol*i + ncol].cpu().float().numpy(),1)
canvas[i*width:(i+1)*width,:] = l
Dict.append((name, canvas))
return OrderedDict(Dict)
def get_feamap_visuals_vgg(feamap, width, depth):
Dict = []
ncol = 8
nrow = depth / ncol
canvas = np.zeros((width * nrow, width * ncol))
name = 'name'
feamap = feamap.data[0]
# print(feamap[0:8].cpu().float().numpy().shape)
for i in range(0, nrow):
l = np.concatenate(feamap[ncol * i:ncol * i + ncol].cpu().float().numpy(), 1)
canvas[i * width:(i + 1) * width, :] = l
Dict.append((name, canvas))
return OrderedDict(Dict)
# save image to the disk
def save_image(image_numpy, image_path):
image_pil = Image.fromarray(image_numpy)
image_pil.save(image_path, 'png')
class ImagePool():
def __init__(self, pool_size):
self.pool_size = pool_size
if self.pool_size > 0:
self.num_imgs = 0
self.images = []
def query(self, images):
if self.pool_size == 0:
return Variable(images)
return_images = []
for image in images:
image = torch.unsqueeze(image, 0)
if self.num_imgs < self.pool_size:
self.num_imgs = self.num_imgs + 1
self.images.append(image)
return_images.append(image)
else:
p = random.uniform(0, 1)
if p > 0.5:
random_id = random.randint(0, self.pool_size - 1)
tmp = self.images[random_id].clone()
self.images[random_id] = image
return_images.append(tmp)
else:
return_images.append(image)
return_images = Variable(torch.cat(return_images, 0))
return return_images
def save_network(self, network, network_label, epoch_label, gpu_ids):
save_filename = '%s_net_%s.pth' % (epoch_label, network_label)
save_path = os.path.join(self.save_dir, save_filename)
torch.save(network.cpu().state_dict(), save_path)
if len(gpu_ids) and torch.cuda.is_available():
network.cuda(device_id=gpu_ids[0])
class PerceptualLoss(nn.Module):
def __init__(self):
super(PerceptualLoss, self).__init__()
vgg = models.vgg16()
vgg16 = 'https://download.pytorch.org/models/vgg16-397923af.pth'
vgg.load_state_dict(model_zoo.load_url(vgg16))
# vgg.load_state_dict(torch.load(vgg_path))
self.vgg = nn.Sequential(*(list(vgg.features.children())[:36])).eval()
self.vgg = nn.DataParallel(self.vgg, device_ids=[0])
self.mse = nn.MSELoss()
for param in self.vgg.parameters():
param.requires_grad = False
def forward(self, input, target):
return self.mse(self.vgg(input), self.vgg(target).detach())
class AvgMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
class LRTransformTest(object):
def __init__(self, shrink_factor):
self.to_pil = transforms.ToPILImage()
self.to_tensor = transforms.ToTensor()
self.shrink_factor = shrink_factor
def __call__(self, hr_tensor):
hr_img = self.to_pil(hr_tensor)
w, h = hr_img.size
lr_scale = transforms.Scale(int(min(w, h) / self.shrink_factor), interpolation=3)
hr_scale = transforms.Scale(min(w, h), interpolation=3)
lr_img = lr_scale(hr_img)
hr_restore_img = hr_scale(lr_img)
return self.to_tensor(lr_img), self.to_tensor(hr_restore_img)
class TotalVariation(nn.Module):
def __init__(self):
super(TotalVariation, self).__init__()
def forward(self, x):
return (((x[:, :, :-1, :] - x[:, :, 1:, :]) ** 2 + (x[:, :, :, :-1] - x[:, :, :, 1:]) ** 2) ** 1.25).mean()
def diagnose_network(net, name='network'):
mean = 0.0
count = 0
for param in net.parameters():
if param.grad is not None:
mean += torch.mean(torch.abs(param.grad.data))
count += 1
if count > 0:
mean = mean / count
print(name)
print(mean)
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [e for e in dir(object) if isinstance(getattr(object, e), collections.Callable)]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print( "\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList]) )
def varname(p):
for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
if m:
return m.group(1)
def print_numpy(x, val=True, shp=False):
x = x.astype(np.float64)
if shp:
print('shape,', x.shape)
if val:
x = x.flatten()
print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % (
np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))
def mkdirs(paths):
if isinstance(paths, list) and not isinstance(paths, str):
for path in paths:
mkdir(path)
else:
mkdir(paths)
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)