Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132939 views
License: OTHER
1
""" Utils needed for the implementation of the paper "A Neural Algorithm of Artistic Style"
2
by Gatys et al. in TensorFlow.
3
4
Author: Chip Huyen ([email protected])
5
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
6
For more details, please read the assignment handout:
7
http://web.stanford.edu/class/cs20si/assignments/a2.pdf
8
"""
9
from __future__ import print_function
10
11
import os
12
13
from PIL import Image, ImageOps
14
import numpy as np
15
import scipy.misc
16
from six.moves import urllib
17
18
def download(download_link, file_name, expected_bytes):
19
""" Download the pretrained VGG-19 model if it's not already downloaded """
20
if os.path.exists(file_name):
21
print("VGG-19 pre-trained model ready")
22
return
23
print("Downloading the VGG pre-trained model. This might take a while ...")
24
file_name, _ = urllib.request.urlretrieve(download_link, file_name)
25
file_stat = os.stat(file_name)
26
if file_stat.st_size == expected_bytes:
27
print('Successfully downloaded VGG-19 pre-trained model', file_name)
28
else:
29
raise Exception('File ' + file_name +
30
' might be corrupted. You should try downloading it with a browser.')
31
32
def get_resized_image(img_path, height, width, save=True):
33
image = Image.open(img_path)
34
# it's because PIL is column major so you have to change place of width and height
35
# this is stupid, i know
36
image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
37
if save:
38
image_dirs = img_path.split('/')
39
image_dirs[-1] = 'resized_' + image_dirs[-1]
40
out_path = '/'.join(image_dirs)
41
if not os.path.exists(out_path):
42
image.save(out_path)
43
image = np.asarray(image, np.float32)
44
return np.expand_dims(image, 0)
45
46
def generate_noise_image(content_image, height, width, noise_ratio=0.6):
47
noise_image = np.random.uniform(-20, 20,
48
(1, height, width, 3)).astype(np.float32)
49
return noise_image * noise_ratio + content_image * (1 - noise_ratio)
50
51
def save_image(path, image):
52
# Output should add back the mean pixels we subtracted at the beginning
53
image = image[0] # the image
54
image = np.clip(image, 0, 255).astype('uint8')
55
scipy.misc.imsave(path, image)
56
57
def make_dir(path):
58
""" Create a directory if there isn't one already. """
59
try:
60
os.mkdir(path)
61
except OSError:
62
pass
63