forked from samim23/DeepDreamAnim
/
dreamer.py
458 lines (397 loc) · 14.5 KB
/
dreamer.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
#!/usr/bin/python
__author__ = "Samim.io"
# Imports
import argparse
import time
import os
import errno
import subprocess
# import natsort
from cStringIO import StringIO
import numpy as np
import scipy.ndimage as nd
import PIL.Image
from google.protobuf import text_format
import caffe
# a couple of utility functions for converting to and from Caffe's input image layout
def preprocess(net, img):
return np.float32(np.rollaxis(img, 2)[::-1]) - net.transformer.mean["data"]
def deprocess(net, img):
return np.dstack((img + net.transformer.mean["data"])[::-1])
def objective_L2(dst):
dst.diff[:] = dst.data
# First we implement a basic gradient ascent step function, applying the first
# two tricks // 32:
def make_step(
net,
step_size=1.5,
end="inception_4c/output",
jitter=32,
clip=True,
objective=objective_L2,
):
"""Basic gradient ascent step."""
src = net.blobs["data"] # input image is stored in Net's 'data' blob
dst = net.blobs[end]
ox, oy = np.random.randint(-jitter, jitter + 1, 2)
src.data[0] = np.roll(np.roll(src.data[0], ox, -1), oy, -2) # apply jitter shift
net.forward(end=end)
objective(dst) # specify the optimization objective
net.backward(start=end)
g = src.diff[0]
# apply normalized ascent step to the input image
src.data[:] += step_size / np.abs(g).mean() * g
src.data[0] = np.roll(np.roll(src.data[0], -ox, -1), -oy, -2) # unshift image
if clip:
bias = net.transformer.mean["data"]
src.data[:] = np.clip(src.data, -bias, 255 - bias)
def deepdream(
net,
base_img,
iter_n=10,
octave_n=4,
step_size=1.5,
octave_scale=1.4,
jitter=32,
end="inception_4c/output",
clip=True,
**step_params
):
# prepare base images for all octaves
octaves = [preprocess(net, base_img)]
for i in range(octave_n - 1):
octaves.append(
nd.zoom(octaves[-1], (1, 1.0 / octave_scale, 1.0 / octave_scale), order=1)
)
src = net.blobs["data"]
detail = np.zeros_like(octaves[-1]) # allocate image for network-produced details
for octave, octave_base in enumerate(octaves[::-1]):
h, w = octave_base.shape[-2:]
if octave > 0:
# upscale details from the previous octave
h1, w1 = detail.shape[-2:]
detail = nd.zoom(detail, (1, 1.0 * h / h1, 1.0 * w / w1), order=1)
src.reshape(1, 3, h, w) # resize the network's input image size
src.data[0] = octave_base + detail
for i in xrange(iter_n):
make_step(
net, end=end, step_size=step_size, jitter=jitter, clip=clip, **step_params
)
# visualization
vis = deprocess(net, src.data[0])
if not clip: # adjust image contrast if clipping is disabled
vis = vis * (255.0 / np.percentile(vis, 99.98))
print(octave, i, end, vis.shape)
# extract details produced on the current octave
detail = src.data[0] - octave_base
# returning the resulting image
return deprocess(net, src.data[0])
# Animaton functions
def resizePicture(image, width):
img = PIL.Image.open(image)
basewidth = width
wpercent = basewidth / float(img.size[0])
hsize = int((float(img.size[1]) * float(wpercent)))
return img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
def morphPicture(filename1, filename2, blend, width):
img1 = PIL.Image.open(filename1)
img2 = PIL.Image.open(filename2)
if width is not 0:
img2 = resizePicture(filename2, width)
return PIL.Image.blend(img1, img2, blend)
def make_sure_path_exists(path):
# make sure input and output directory exist, if not create them. If another error
# (permission denied) throw an error.
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
def main(
inputdir,
outputdir,
preview,
octaves,
octave_scale,
iterations,
jitter,
zoom,
stepsize,
blend,
layers,
guide,
gpu,
flow,
):
# input var setup
make_sure_path_exists(inputdir)
make_sure_path_exists(outputdir)
if preview is None:
preview = 0
if octaves is None:
octaves = 4
if octave_scale is None:
octave_scale = 1.5
if iterations is None:
iterations = 10
if jitter is None:
jitter = 32
if jitter is None:
jitter = 32
if zoom is None:
zoom = 1
if stepsize is None:
stepsize = 1.5
if blend is None:
blend = 0.5
if layers is None:
layers = ["inception_4c/output"]
if gpu is None:
gpu = 1
if flow is None:
flow = 0
# net.blobs.keys()
# Loading DNN model
model_name = "bvlc_googlenet"
model_path = "../../caffe/models/" + model_name + "/"
net_fn = model_path + "deploy.prototxt"
param_fn = model_path + "bvlc_googlenet.caffemodel"
# Patching model to be able to compute gradients.
# Note that you can also manually add "force_backward: true" line to "deploy.prototxt"
model = caffe.io.caffe_pb2.NetParameter()
text_format.Merge(open(net_fn).read(), model)
model.force_backward = True
open("tmp.prototxt", "w").write(str(model))
net = caffe.Classifier(
"tmp.prototxt",
param_fn,
mean=np.float32([104.0, 116.0, 122.0]), # ImageNet mean, training set dependent
channel_swap=(2, 1, 0), # the reference model has channels in BGR order
)
if gpu is 1:
caffe.set_mode_gpu()
caffe.set_device(0)
# load images & sort them
vidinput = sorted(os.listdir(inputdir))
vids = []
var_counter = 1
# create list
for frame in vidinput:
if not ".png" in frame:
continue
vids.append(frame)
img = PIL.Image.open(inputdir + "/" + vids[0])
if preview is not 0:
img = resizePicture(inputdir + "/" + vids[0], preview)
frame = np.float32(img)
# guide
if guide is not None:
guideimg = PIL.Image.open(inputdir + "/" + guide)
guideimgresized = guideimg.resize((224, 224), PIL.Image.ANTIALIAS)
guide = np.float32(guideimgresized)
end = layers[0] # 'inception_3b/output'
h, w = guide.shape[:2]
src, dst = net.blobs["data"], net.blobs[end]
src.reshape(1, 3, h, w)
src.data[0] = preprocess(net, guide)
net.forward(end=end)
guide_features = dst.data[0].copy()
def objective_guide(dst):
x = dst.data[0].copy()
y = guide_features
ch = x.shape[0]
x = x.reshape(ch, -1)
y = y.reshape(ch, -1)
A = x.T.dot(y) # compute the matrix of dot-products with guide features
dst.diff[0].reshape(ch, -1)[:] = y[:, A.argmax(1)] # select ones that match best
def getFrame(net, frame, endparam):
# dream frame
if guide is None:
result = deepdream(
net,
frame,
iter_n=iterations,
step_size=stepsize,
octave_n=octaves,
octave_scale=octave_scale,
jitter=jitter,
end=endparam,
)
else:
result = deepdream(
net,
frame,
iter_n=iterations,
step_size=stepsize,
octave_n=octaves,
octave_scale=octave_scale,
jitter=jitter,
end=endparam,
objective=objective_guide,
)
def getStats(saveframe, var_counter, vids, difference):
# Stats
print("***************************************")
print("Saving Image As: {}".format(saveframe))
print("Frame {} of {}".format(var_counter, len(vids)))
print("Frame Time: {}s".format(difference))
timeleft = difference * (len(vids) - var_counter)
m, s = divmod(timeleft, 60)
h, m = divmod(m, 60)
print(
"Estimated Total Time Remaining: {}s ({:d}:{:02d}:{:02d})".format(
timeleft, h, m, s
)
)
print("***************************************")
if flow is 1:
import cv2
# optical flow
img = np.float32(PIL.Image.open(inputdir + "/" + vids[0]))
h, w, c = img.shape
hallu = getFrame(net, img, layers[0])
np.clip(hallu, 0, 255, out=hallu)
PIL.Image.fromarray(np.uint8(hallu)).save(outputdir + "/" + "frame_000000.png")
grayImg = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
for v in range(len(vids)):
if var_counter < len(vids):
previousImg = img
previousGrayImg = grayImg
newframe = inputdir + "/" + vids[v + 1]
print "Processing: {}".format(newframe)
endparam = layers[var_counter % len(layers)]
img = np.float32(PIL.Image.open(newframe))
grayImg = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
flow = cv2.calcOpticalFlowFarneback(
previousGrayImg,
grayImg,
pyr_scale=0.5,
levels=3,
winsize=15,
iterations=3,
poly_n=5,
poly_sigma=1.2,
flags=0,
flow=None,
)
flow = -flow
flow[:, :, 0] += np.arange(w)
flow[:, :, 1] += np.arange(h)[:, np.newaxis]
halludiff = hallu - previousImg
halludiff = cv2.remap(halludiff, flow, None, cv2.INTER_LINEAR)
hallu = img + halludiff
now = time.time()
hallu = getFrame(net, hallu, endparam)
later = time.time()
difference = int(later - now)
saveframe = outputdir + "/" + "frame_%06d.png" % (var_counter)
getStats(saveframe, var_counter, vids, difference)
np.clip(hallu, 0, 255, out=hallu)
PIL.Image.fromarray(np.uint8(hallu)).save(saveframe)
var_counter += 1
else:
print("Finished processing all frames")
else:
# process anim frames
for v in range(len(vids)):
if var_counter < len(vids):
vid = vids[v]
h, w = frame.shape[:2]
s = 0.05 # scale coefficient
print("Processing: {}/{}".format(inputdir, vid))
# setup
now = time.time()
endparam = layers[var_counter % len(layers)]
frame = getFrame(net, frame, endparam)
later = time.time()
difference = int(later - now)
saveframe = outputdir + "/" + "frame_%06d.png" % (var_counter)
getStats(saveframe, var_counter, vids, difference)
# save image
PIL.Image.fromarray(np.uint8(frame)).save(saveframe)
# setup next image
newframe = inputdir + "/" + vids[v + 1]
# blend
if blend == 0:
newimg = PIL.Image.open(newframe)
if preview is not 0:
newimg = resizePicture(newframe, preview)
frame = newimg
else:
frame = morphPicture(saveframe, newframe, blend, preview)
# setup next frame
frame = np.float32(frame)
var_counter += 1
else:
print("Finished processing all frames")
def extractVideo(inputdir, outputdir):
# fmt: off
cmds = [
"ffmpeg", "-i", inputdir, "-f", "image2", os.path.join(outputdir, "image-%06d.png")
]
print(subprocess.Popen(args=cmds, stdout=subprocess.PIPE).stdout.read())
# fmt: on
def createVideo(inputdir, outputdir, framerate):
# fmt: off
cmds = [ # noqa
"ffmpeg", "-r", str(framerate), "-f", "image2", "-i",
os.path.join(inputdir, "frame_%6d.png"), "-c:v", "libx264", "-crf", "18",
"-pix_fmt", "yuv420p", "-tune", "fastdecode", "-tune", "zerolatency",
"-profile:v", "baseline", outputdir
]
print(subprocess.Popen(args=cmds, stdout=subprocess.PIPE).stdout.read())
# fmt: on
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="DeepDreamAnim")
parser.add_argument("-i", "--input", help="Input directory", required=True)
parser.add_argument("-o", "--output", help="Output directory", required=True)
parser.add_argument(
"-p", "--preview", help="Preview image width. Default: 0", type=int
)
parser.add_argument("-oct", "--octaves", help="Octaves. Default: 4", type=int)
parser.add_argument(
"-octs", "--octavescale", help="Octave Scale. Default: 1.4", type=float
)
parser.add_argument("-itr", "--iterations", help="Iterations. Default: 10", type=int)
parser.add_argument("-j", "--jitter", help="Jitter. Default: 32", type=int)
parser.add_argument("-z", "--zoom", help="Zoom in Amount. Default: 1", type=int)
parser.add_argument("-s", "--stepsize", help="Step Size. Default: 1.5", type=float)
parser.add_argument("-b", "--blend", help="Blend Amount. Default: 0.5", type=float)
parser.add_argument(
"-l",
"--layers",
help="Layers Loop. Default: inception_4c/output",
nargs="+",
type=str,
)
parser.add_argument("-e", "--extract", help="Extract Frames From Video.", type=int)
parser.add_argument("-c", "--create", help="Create Video From Frames.", type=int)
parser.add_argument("-g", "--guide", help="Guided dream image input.", type=str)
parser.add_argument("-flow", "--flow", help="Optical Flow.", type=int)
parser.add_argument("-gpu", "--gpu", help="Use GPU or CPU.", type=int)
parser.add_argument("-f", "--framerate", help="Video creation Framerate.", type=int)
args = parser.parse_args()
if args.extract is 1:
extractVideo(args.input, args.output)
elif args.create is 1:
framerate = 25
if args.framerate is not None:
framerate = args.framerate
createVideo(args.input, args.output, framerate)
else:
main(
args.input,
args.output,
args.preview,
args.octaves,
args.octavescale,
args.iterations,
args.jitter,
args.zoom,
args.stepsize,
args.blend,
args.layers,
args.guide,
args.gpu,
args.flow,
)