-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvisualize.py
46 lines (39 loc) · 1.2 KB
/
visualize.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
# ------------------------------------------------------------------------------
# Util functions to visualize images.
# ------------------------------------------------------------------------------
import numpy as np
from PIL import Image
def split(x):
assert type(x) == int
t = int(np.floor(np.sqrt(x)))
for a in range(t, 0, -1):
if x % a == 0:
return a, x / a
def grid_transform(x):
n, c, h, w = x.shape
a, b = split(n)
x = np.transpose(x, [0, 2, 3, 1])
x = np.reshape(x, [a, b, h, w, c])
x = np.transpose(x, [0, 2, 1, 3, 4])
x = np.reshape(x, [a * h, b * w, c])
if x.shape[2] == 1:
x = np.squeeze(x, axis=2)
return x
def seq_transform(x):
n, c, h, w = x.shape
x = np.transpose(x, [2, 0, 3, 1])
x = np.reshape(x, [h, n * w, c])
return x
# Converts image pixels from range [-1, 1] to [0, 255].
def data2img(data):
rescaled = np.divide(data + 1.0, 2.0) * 255.
rescaled = np.clip(rescaled, 0, 255)
return np.rint(rescaled).astype('uint8')
def interleave(a, b):
res = np.empty([a.shape[0] + b.shape[0]] + list(a.shape[1:]), dtype=a.dtype)
res[0::2] = a
res[1::2] = b
return res
def save_image(filepath, img):
pilimg = Image.fromarray(img)
pilimg.save(filepath)