Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
""" Utils needed for the implementation in TensorFlow
2
of the paper A Neural Algorithm of Artistic Style (Gatys et al., 2016)
3
4
Created by Chip Huyen ([email protected])
5
CS20: "TensorFlow for Deep Learning Research"
6
cs20.stanford.edu
7
8
For more details, please read the assignment handout:
9
https://docs.google.com/document/d/1FpueD-3mScnD0SJQDtwmOb1FrSwo1NGowkXzMwPoLH4/edit?usp=sharing
10
11
"""
12
13
import os
14
15
from PIL import Image, ImageOps
16
import numpy as np
17
import scipy.misc
18
from six.moves import urllib
19
20
def download(download_link, file_name, expected_bytes):
21
""" Download the pretrained VGG-19 model if it's not already downloaded """
22
if os.path.exists(file_name):
23
print("VGG-19 pre-trained model is ready")
24
return
25
print("Downloading the VGG pre-trained model. This might take a while ...")
26
file_name, _ = urllib.request.urlretrieve(download_link, file_name)
27
file_stat = os.stat(file_name)
28
if file_stat.st_size == expected_bytes:
29
print('Successfully downloaded VGG-19 pre-trained model', file_name)
30
else:
31
raise Exception('File ' + file_name +
32
' might be corrupted. You should try downloading it with a browser.')
33
34
def get_resized_image(img_path, width, height, save=True):
35
image = Image.open(img_path)
36
# PIL is column major so you have to swap the places of width and height
37
image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
38
if save:
39
image_dirs = img_path.split('/')
40
image_dirs[-1] = 'resized_' + image_dirs[-1]
41
out_path = '/'.join(image_dirs)
42
if not os.path.exists(out_path):
43
image.save(out_path)
44
image = np.asarray(image, np.float32)
45
return np.expand_dims(image, 0)
46
47
def generate_noise_image(content_image, width, height, noise_ratio=0.6):
48
noise_image = np.random.uniform(-20, 20, (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
image = image[0]
53
image = np.clip(image, 0, 255).astype('uint8')
54
scipy.misc.imsave(path, image)
55
56
def safe_mkdir(path):
57
""" Create a directory if there isn't one already. """
58
try:
59
os.mkdir(path)
60
except OSError:
61
pass
62