-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
108 lines (92 loc) · 2.85 KB
/
utils.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
import os
import shutil
import numpy as np
import pylab
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def warpgrid(bs, HO, WO, warp=True):
# meshgrid
x = np.linspace(-1, 1, WO)
y = np.linspace(-1, 1, HO)
xv, yv = np.meshgrid(x, y)
grid = np.zeros((bs, HO, WO, 2))
grid_x = xv
if warp:
grid_y = (np.power(21, (yv+1)/2) - 11) / 10
else:
grid_y = np.log(yv * 10 + 11) / np.log(21) * 2 - 1
grid[:, :, :, 0] = grid_x
grid[:, :, :, 1] = grid_y
grid = grid.astype(np.float32)
return grid
def makedirs(path, remove=False):
if os.path.isdir(path):
if remove:
shutil.rmtree(path)
print('removed existing directory...')
else:
return
os.makedirs(path, exist_ok=True)
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.initialized = False
self.val = None
self.avg = None
self.sum = None
self.count = None
def initialize(self, val, weight):
self.val = val
self.avg = val
self.sum = val*weight
self.count = weight
self.initialized = True
def update(self, val, weight=1):
val = np.asarray(val)
if not self.initialized:
self.initialize(val, weight)
else:
self.add(val, weight)
def add(self, val, weight):
self.val = val
self.sum += val * weight
self.count += weight
self.avg = self.sum / self.count
def value(self):
if self.val is None:
return 0.
else:
return self.val.tolist()
def average(self):
if self.avg is None:
return 0.
else:
return self.avg.tolist()
def recover_rgb(img):
for t, m, s in zip(img,
[0.485, 0.456, 0.406],
[0.229, 0.224, 0.225]):
t.mul_(s).add_(m)
img = (img.cpu().numpy().transpose((1, 2, 0)) * 255).astype(np.uint8)
return img
def apply_cmap(im, cmap = pylab.cm.jet, lo = None, hi = None):
return cmap(clip_rescale(im, lo, hi).flatten()).reshape(im.shape[:2] + (-1,))[:, :, :3]
def cmap_im(cmap, im, lo = None, hi = None):
return np.uint8(255*apply_cmap(im, cmap, lo, hi))
def clip_rescale(x, lo = None, hi = None):
if lo is None:
lo = np.min(x)
if hi is None:
hi = np.max(x)
return np.clip((x - lo)/(hi - lo), 0., 1.)
def plot_onlyFinalerr_metrics(path, history):
# plot total loss
fig = plt.figure()
plt.plot(history['train']['epoch'], history['train']['err'],
color='b', label='training')
plt.plot(history['val']['epoch'], history['val']['err'],
color='c', label='validation')
plt.legend()
fig.savefig(os.path.join(path, 'loss.png'), dpi=200)
plt.close('all')