forked from alexjc/neural-doodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoodle.py
298 lines (230 loc) · 14.3 KB
/
doodle.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#
# Copyright (c) 2016, Alex J. Champandard.
#
import os
import sys
import bz2
import pickle
import argparse
import numpy as np
import scipy.optimize
import skimage.transform
parser = argparse.ArgumentParser(description='Generate a new image by applying style onto a content image.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--content', default=None, type=str, help='Content image path as optimization target.')
parser.add_argument('--content-weight', default=10.0, type=float, help='Weight of content relative to style.')
parser.add_argument('--content-layers', default='4_2', type=str, help='The layer with which to match content.')
parser.add_argument('--style', required=True, type=str, help='Style image path to extract patches.')
parser.add_argument('--style-weight', default=50.0, type=float, help='Weight of style relative to content.')
parser.add_argument('--style-layers', default='3_1,4_1', type=str, help='The layers to match style patches.')
parser.add_argument('--semantic-ext', default='_sem.png', type=str, help='File extension for the semantic maps.')
parser.add_argument('--semantic-weight', default=1.0, type=float, help='Global weight of semantics vs. features.')
parser.add_argument('--output', default='output.png', type=str, help='Output image path to save once done.')
parser.add_argument('--resolutions', default=3, type=int, help='Number of image scales to process.')
parser.add_argument('--smoothness', default=1E+0, type=float, help='Weight of image smoothing scheme.')
parser.add_argument('--seed', default='noise', type=str, help='Seed image path, "noise" or "content".')
parser.add_argument('--iterations', default=100, type=int, help='Number of iterations to run each resolution.')
parser.add_argument('--device', default='cpu', type=str, help='Index of the GPU number to use, for theano.')
parser.add_argument('--print-every', default=10, type=int, help='How often to log statistics to stdout.')
parser.add_argument('--save-every', default=0, type=int, help='How frequently to save PNG into `frames`.')
args = parser.parse_args()
os.environ.setdefault('THEANO_FLAGS', 'device=%s,floatX=float32,allow_gc=True,print_active_device=False' % (args.device))
import theano
import theano.tensor as T
import theano.tensor.nnet.neighbours
import lasagne
from lasagne.layers import Conv2DLayer as ConvLayer, Pool2DLayer as PoolLayer
from lasagne.layers import InputLayer, ConcatLayer
class ansi:
BOLD = '\033[1;97m'
WHITE = '\033[0;97m'
YELLOW = '\033[0;33m'
RED = '\033[0;31m'
GREEN = '\033[0;32m'
BLUE_BOLD = '\033[1;94m'
BLUE = '\033[0;94m'
ENDC = '\033[0m'
class Model(object):
def __init__(self):
self.pixel_mean = np.array([103.939, 116.779, 123.680], dtype=np.float32).reshape((3,1,1))
self.setup_model()
self.load_data()
def setup_model(self):
net = {}
# First network for the main image.
net['img'] = InputLayer((1, 3, None, None))
net['conv1_1'] = ConvLayer(net['img'], 64, 3, pad=1)
net['conv1_2'] = ConvLayer(net['conv1_1'], 64, 3, pad=1)
net['pool1'] = PoolLayer(net['conv1_2'], 2, mode='average_exc_pad')
net['conv2_1'] = ConvLayer(net['pool1'], 128, 3, pad=1)
net['conv2_2'] = ConvLayer(net['conv2_1'], 128, 3, pad=1)
net['pool2'] = PoolLayer(net['conv2_2'], 2, mode='average_exc_pad')
net['conv3_1'] = ConvLayer(net['pool2'], 256, 3, pad=1)
net['conv3_2'] = ConvLayer(net['conv3_1'], 256, 3, pad=1)
net['conv3_3'] = ConvLayer(net['conv3_2'], 256, 3, pad=1)
net['conv3_4'] = ConvLayer(net['conv3_3'], 256, 3, pad=1)
net['pool3'] = PoolLayer(net['conv3_4'], 2, mode='average_exc_pad')
net['conv4_1'] = ConvLayer(net['pool3'], 512, 3, pad=1)
net['conv4_2'] = ConvLayer(net['conv4_1'], 512, 3, pad=1)
net['main'] = net['conv4_2']
# Second network for the semantic map.
net['map'] = InputLayer((1, 3, None, None))
net['map_2'] = PoolLayer(net['map'], 2, mode='average_exc_pad')
net['map_3'] = PoolLayer(net['map'], 4, mode='average_exc_pad')
net['map_4'] = PoolLayer(net['map'], 8, mode='average_exc_pad')
net['sem2_1'] = ConcatLayer([net['conv3_1'], net['map_2']])
net['sem3_1'] = ConcatLayer([net['conv3_1'], net['map_3']])
net['sem4_1'] = ConcatLayer([net['conv4_1'], net['map_4']])
# Third network for the nearest neighbors (default size for now).
net['nn3_1'] = ConvLayer(net['sem3_1'], 1, 3, b=None, pad=0)
net['nn4_1'] = ConvLayer(net['sem4_1'], 1, 3, b=None, pad=0)
self.network = net
def load_data(self):
if not os.path.exists('vgg19_conv.pkl.bz2'):
print("""{}ERROR: Model file with pre-trained convolution layers not found. Download here:\nhttps://github.com/alexjc/neural-doodle/releases/download/v0.0/vgg19_conv.pkl.bz2{}\n""".format(ansi.RED, ansi.ENDC))
sys.exit(-1)
data = pickle.load(bz2.open('vgg19_conv.pkl.bz2', 'rb'))
params = lasagne.layers.get_all_param_values(self.network['main'])
lasagne.layers.set_all_param_values(self.network['main'], data[:len(params)])
def prepare(self, layers):
self.tensor_img = T.tensor4()
self.tensor_map = T.tensor4()
self.tensor_inputs = {self.network['img']: self.tensor_img, self.network['map']: self.tensor_map}
outputs = lasagne.layers.get_output([self.network[l] for l in layers], self.tensor_inputs)
self.tensor_outputs = {k: v for k, v in zip(layers, outputs)}
class NeuralGenerator(object):
def __init__(self):
self.model = Model()
if args.output is not None and os.path.isfile(args.output):
os.remove(args.output)
filename_image = args.content or args.output
filename_map = os.path.splitext(filename_image)[0]+args.semantic_ext
if os.path.exists(filename_image):
self.content_image_original = scipy.ndimage.imread(filename_image, mode='RGB')
else:
self.content_image_original = None
args.content_weight = 0.0
if os.path.exists(filename_map):
self.content_map_original = scipy.ndimage.imread(filename_map, mode='RGB')
if self.content_image_original is None:
self.content_image_original = np.zeros(self.content_map_original.shape[:2]+(3,))
else:
self.content_map_original = np.zeros(self.content_image_original.shape[:2]+(1,))
args.semantic_weight = 0.0
self.style_image_original = scipy.ndimage.imread(args.style, mode='RGB')
self.style_map_original = scipy.ndimage.imread(os.path.splitext(args.style)[0]+args.semantic_ext, mode='RGB')
def prepare_content(self, scale=1.0):
content_image = skimage.transform.rescale(self.content_image_original, scale) * 255.0
self.content_image = self.prepare_image(content_image)
content_map = skimage.transform.rescale(self.content_map_original * args.semantic_weight, scale) * 255.0
self.content_map = content_map.transpose((2, 0, 1))[np.newaxis].astype(np.float32)
def prepare_style(self, scale=1.0):
style_image = skimage.transform.rescale(self.style_image_original, scale) * 255.0
self.style_image = self.prepare_image(style_image)
style_map = skimage.transform.rescale(self.style_map_original * args.semantic_weight, scale) * 255.0
self.style_map = style_map.transpose((2, 0, 1))[np.newaxis].astype(np.float32)
for layer in args.style_layers.split(','):
extractor = theano.function([self.model.tensor_img, self.model.tensor_map],
self.extract_patches(self.model.tensor_outputs['sem'+layer]))
patches, norm = extractor(self.style_image, self.style_map)
l = self.model.network['nn'+layer]
l.N = theano.shared(norm)
l.W.set_value(patches)
l.num_filters = patches.shape[0]
print(' - Style layer sem{}: {} patches in {:,}kb.'.format(layer, patches.shape[0], patches.size//1000))
def extract_patches(self, f, size=3, stride=1):
patches = theano.tensor.nnet.neighbours.images2neibs(f, (size, size), (stride, stride), mode='valid')
patches = patches.reshape((-1, patches.shape[0] // f.shape[1], size, size)).dimshuffle((1, 0, 2, 3))
norm = T.sqrt(T.sum(patches ** 2.0, axis=(1,2,3), keepdims=True))
return patches[:,:,::-1,::-1], norm
def prepare_optimization(self):
self.content_loss = []
if args.content_weight > 0.0:
for layer in args.content_layers.split(','):
content_features = self.model.tensor_outputs['conv'+layer].eval({self.model.tensor_img: self.content_image})
content_loss = T.mean((self.model.tensor_outputs['conv'+layer] - content_features) ** 2.0)
self.content_loss.append(('content', layer, args.content_weight * content_loss))
print(' - Content layer conv{}: {} features in {:,}kb.'.format(layer, content_features.shape[0], content_features.size//1000))
def style_loss(l):
layer = self.model.network['nn'+l]
dist = self.model.tensor_outputs['nn'+l]
patches, norm = self.extract_patches(self.model.tensor_outputs['sem'+l])
dist = dist.reshape((dist.shape[1], -1)) / norm.reshape((1,-1)) / layer.N.reshape((-1,1))
best = dist.argmax(axis=0)
return T.mean((patches[:,:-3] - layer.W[best,:-3]) ** 2.0)
self.style_loss = [('style', l, args.style_weight * style_loss(l)) for l in args.style_layers.split(',')]
variation_loss = [('smooth', 'img', args.smoothness * self.variation_loss(self.model.tensor_img))]
self.losses = self.content_loss + self.style_loss + variation_loss
grad = T.grad(sum([l[-1] for l in self.losses]), self.model.tensor_img)
self.compute_grad_and_losses = theano.function([self.model.tensor_img, self.model.tensor_map],
[grad] + [l[-1] for l in self.losses], on_unused_input='ignore')
def variation_loss(self, x):
return (((x[:,:,:-1,:-1] - x[:,:,1:,:-1])**2 + (x[:,:,:-1,:-1] - x[:,:,:-1,1:])**2)**1.25).mean()
def evaluate(self, Xn):
current_img = Xn.reshape(self.content_image.shape).astype(np.float32) - self.model.pixel_mean
grads, *losses = self.compute_grad_and_losses(current_img, self.content_map)
loss = sum(losses)
if args.save_every and self.frame % args.save_every == 0:
scipy.misc.toimage(self.finalize_image(Xn), cmin=0, cmax=255).save('frames/%04d.png'%self.frame)
# Use gradients as an estimate for overall quality.
self.error = self.error * 0.9 + 0.1 * np.abs(grads).max()
if args.print_every and self.frame % args.print_every == 0:
print('{:>3} {}error{} {:8.2e} '.format(self.frame, ansi.BOLD, ansi.ENDC, loss / 1000.0), end='')
category = ''
for v, l in zip(losses, self.losses):
if l[0] == 'smooth':
continue
if l[0] != category:
print(' {}{}{}'.format(ansi.BOLD, l[0], ansi.ENDC), end='')
category = l[0]
print(' {}{}{} {:8.2e} '.format(ansi.BOLD, l[1], ansi.ENDC, v / 1000.0), end='')
quality = 100.0 - 100.0 * np.sqrt(self.error / 255.0)
print(' {}quality{} {:3.1f}% '.format(ansi.BOLD, ansi.ENDC, quality, flush=True))
self.frame += 1
return loss, np.array(grads).flatten().astype(np.float64)
def run(self):
self.frame = 0
for i in range(args.resolutions):
self.error = 255.0
scale = 1.0 / 2.0 ** (args.resolutions - 1 - i)
shape = self.content_image_original.shape
print('\n{}Phase #{}: resolution {}x{} scale {}{}'.format(ansi.BLUE_BOLD, i,
int(shape[1]*scale), int(shape[0]*scale), scale, ansi.BLUE))
self.model.prepare(layers=['sem3_1', 'sem4_1', 'conv4_2'])
self.prepare_content(scale)
self.prepare_style(scale)
shape = self.content_image.shape[2:]
self.model.prepare(layers=['sem3_1', 'sem4_1', 'conv4_2', 'nn3_1', 'nn4_1'])
self.prepare_optimization()
print('{}'.format(ansi.ENDC))
if args.seed == 'content':
Xn = self.content_image[0] + self.model.pixel_mean
if args.seed == 'noise':
Xn = np.random.uniform(32, 224, shape + (3,)).astype(np.float32)
if args.seed == 'previous':
Xn = scipy.misc.imresize(Xn[0], shape)
Xn = Xn.transpose((2, 0, 1))[np.newaxis]
data_bounds = np.zeros((np.product(Xn.shape), 2), dtype=np.float64)
data_bounds[:] = (0.0, 255.0)
Xn, Vn, info = scipy.optimize.fmin_l_bfgs_b(
self.evaluate,
Xn.astype(np.float64).flatten(),
bounds=data_bounds,
factr=0.0, pgtol=0.0, # Disable automatic termination by setting low threshold.
m=4, # Maximum correlations kept in memory by algorithm.
maxfun=args.iterations-1, # Limit number of calls to evaluate().
iprint=-1) # Handle our own logging of information.
args.seed = 'previous'
Xn = Xn.reshape(self.content_image.shape)
scipy.misc.toimage(self.finalize_image(Xn), cmin=0, cmax=255).save(args.output)
def prepare_image(self, image):
image = np.swapaxes(np.swapaxes(image, 1, 2), 0, 1)[::-1, :, :]
image = image.astype(np.float32) - self.model.pixel_mean
return image[np.newaxis]
def finalize_image(self, x):
x = x.reshape(self.content_image.shape[1:])[::-1]
x = np.swapaxes(np.swapaxes(x, 0, 1), 1, 2)
return np.clip(x, 0, 255).astype('uint8')
if __name__ == "__main__":
generator = NeuralGenerator()
generator.run()