📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Utils needed for the implementation in TensorFlow1of the paper A Neural Algorithm of Artistic Style (Gatys et al., 2016)23Created by Chip Huyen ([email protected])4CS20: "TensorFlow for Deep Learning Research"5cs20.stanford.edu67For more details, please read the assignment handout:8https://docs.google.com/document/d/1FpueD-3mScnD0SJQDtwmOb1FrSwo1NGowkXzMwPoLH4/edit?usp=sharing910"""1112import os1314from PIL import Image, ImageOps15import numpy as np16import scipy.misc17from six.moves import urllib1819def download(download_link, file_name, expected_bytes):20""" Download the pretrained VGG-19 model if it's not already downloaded """21if os.path.exists(file_name):22print("VGG-19 pre-trained model is ready")23return24print("Downloading the VGG pre-trained model. This might take a while ...")25file_name, _ = urllib.request.urlretrieve(download_link, file_name)26file_stat = os.stat(file_name)27if file_stat.st_size == expected_bytes:28print('Successfully downloaded VGG-19 pre-trained model', file_name)29else:30raise Exception('File ' + file_name +31' might be corrupted. You should try downloading it with a browser.')3233def get_resized_image(img_path, width, height, save=True):34image = Image.open(img_path)35# PIL is column major so you have to swap the places of width and height36image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)37if save:38image_dirs = img_path.split('/')39image_dirs[-1] = 'resized_' + image_dirs[-1]40out_path = '/'.join(image_dirs)41if not os.path.exists(out_path):42image.save(out_path)43image = np.asarray(image, np.float32)44return np.expand_dims(image, 0)4546def generate_noise_image(content_image, width, height, noise_ratio=0.6):47noise_image = np.random.uniform(-20, 20, (1, height, width, 3)).astype(np.float32)48return noise_image * noise_ratio + content_image * (1 - noise_ratio)4950def save_image(path, image):51image = image[0]52image = np.clip(image, 0, 255).astype('uint8')53scipy.misc.imsave(path, image)5455def safe_mkdir(path):56""" Create a directory if there isn't one already. """57try:58os.mkdir(path)59except OSError:60pass6162