📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Utils needed for the implementation of the paper "A Neural Algorithm of Artistic Style"1by Gatys et al. in TensorFlow.23Author: Chip Huyen ([email protected])4Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"5For more details, please read the assignment handout:6http://web.stanford.edu/class/cs20si/assignments/a2.pdf7"""8from __future__ import print_function910import os1112from PIL import Image, ImageOps13import numpy as np14import scipy.misc15from six.moves import urllib1617def download(download_link, file_name, expected_bytes):18""" Download the pretrained VGG-19 model if it's not already downloaded """19if os.path.exists(file_name):20print("VGG-19 pre-trained model ready")21return22print("Downloading the VGG pre-trained model. This might take a while ...")23file_name, _ = urllib.request.urlretrieve(download_link, file_name)24file_stat = os.stat(file_name)25if file_stat.st_size == expected_bytes:26print('Successfully downloaded VGG-19 pre-trained model', file_name)27else:28raise Exception('File ' + file_name +29' might be corrupted. You should try downloading it with a browser.')3031def get_resized_image(img_path, height, width, save=True):32image = Image.open(img_path)33# it's because PIL is column major so you have to change place of width and height34# this is stupid, i know35image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)36if save:37image_dirs = img_path.split('/')38image_dirs[-1] = 'resized_' + image_dirs[-1]39out_path = '/'.join(image_dirs)40if not os.path.exists(out_path):41image.save(out_path)42image = np.asarray(image, np.float32)43return np.expand_dims(image, 0)4445def generate_noise_image(content_image, height, width, noise_ratio=0.6):46noise_image = np.random.uniform(-20, 20,47(1, height, width, 3)).astype(np.float32)48return noise_image * noise_ratio + content_image * (1 - noise_ratio)4950def save_image(path, image):51# Output should add back the mean pixels we subtracted at the beginning52image = image[0] # the image53image = np.clip(image, 0, 255).astype('uint8')54scipy.misc.imsave(path, image)5556def make_dir(path):57""" Create a directory if there isn't one already. """58try:59os.mkdir(path)60except OSError:61pass6263