-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
91 lines (77 loc) · 2.96 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
"""
Some codes from https://github.com/Newmu/dcgan_code
"""
from __future__ import division
import scipy.misc
import numpy as np
from random import random
get_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x.get_shape()[-1])
def get_image(image_path, input_height, input_width,
resize_height=64, resize_width=64,
is_crop=False, is_grayscale=False):
if random() < .5:
return np.fliplr(transform(imread(image_path, is_grayscale), input_height, input_width, resize_height, resize_width, is_crop))
else:
return transform(imread(image_path, is_grayscale), input_height, input_width, resize_height, resize_width, is_crop)
def save_images(images, size, image_path, is_grayscale=False):
return imsave(inverse_transform(images), size, image_path, is_grayscale)
def imread(path, is_grayscale=False):
if (is_grayscale):
return scipy.misc.imread(path, flatten = True).astype(np.float)
else:
return scipy.misc.imread(path).astype(np.float)
def merge(images, size):
h, w = images.shape[1], images.shape[2]
img = np.zeros((h * size[0], w * size[1], 3))
for idx, image in enumerate(images):
i = idx % size[1]
j = idx // size[1]
img[j*h:j*h+h, i*w:i*w+w, :] = image
return img
def merge_gray(images, size):
h, w = images.shape[1], images.shape[2]
img = np.zeros((h * size[0], w * size[1]))
for idx, image in enumerate(images):
i = idx % size[1]
j = idx // size[1]
img[j*h:j*h+h, i*w:i*w+w] = image
return img
def imsave(images, size, path, is_grayscale=False):
if (is_grayscale):
return scipy.misc.imsave(path, merge_gray(images, size))
else:
return scipy.misc.imsave(path, merge(images, size))
def center_crop(x, crop_h, crop_w,
resize_h=64, resize_w=64):
if crop_w is None:
crop_w = crop_h
h, w = x.shape[:2]
j = int(round((h - crop_h)/2.))
i = int(round((w - crop_w)/2.))
return scipy.misc.imresize(
x[j:j+crop_h, i:i+crop_w], [resize_h, resize_w])
def transform(image, input_height, input_width,
resize_height=64, resize_width=64, is_crop=True):
if is_crop:
cropped_image = center_crop(
image, input_height, input_width,
resize_height, resize_width)
else:
cropped_image = scipy.misc.imresize(image, [resize_height, resize_width])
return np.array(cropped_image)/127.5 - 1.
# return cropped_image
def inverse_transform(images):
return (images+1.)/2.
def make_gif(images, fname, duration=2, true_image=False):
import moviepy.editor as mpy
def make_frame(t):
try:
x = images[int(len(images)/duration*t)]
except:
x = images[-1]
if true_image:
return x.astype(np.uint8)
else:
return ((x+1)/2*255).astype(np.uint8)
clip = mpy.VideoClip(make_frame, duration=duration)
clip.write_gif(fname, fps = len(images) / duration)