Created
July 4, 2018 22:38
-
-
Save llSourcell/8f981c4e3d8e6cc300fd148c70e42c68 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from keras.applications import vgg19 | |
| from keras import backend as K | |
| from scipy.optimize import fmin_l_bfgs_b | |
| # Define the base image and style image | |
| base_image_path = base_image_path | |
| style_reference_image_path = style_reference_image_path | |
| # these are the weights of the different loss components | |
| total_variation_weight = 1.0 | |
| style_weight = 1.0 | |
| content_weight = 0.025 | |
| # get tensor representations of our images | |
| base_image = K.variable(preprocess_image(base_image_path)) | |
| style_reference_image = K.variable(preprocess_image(style_reference_image_path)) | |
| # this will contain our generated image | |
| combination_image = K.placeholder((1, 3, img_nrows, img_ncols)) | |
| # combine the 3 images into a single Keras tensor | |
| input_tensor = K.concatenate([base_image, | |
| style_reference_image, | |
| combination_image], axis=0) | |
| # build the VGG16 network with our 3 images as input | |
| # the model will be loaded with pre-trained ImageNet weights | |
| model = vgg19.VGG19(input_tensor=input_tensor, | |
| weights='imagenet', include_top=False) | |
| # get the symbolic outputs of each "key" layer (we gave them unique names). | |
| outputs_dict = dict([(layer.name, layer.output) for layer in model.layers]) | |
| # compute the neural style loss | |
| # first we need to define 4 util functions | |
| # the gram matrix of an image tensor (feature-wise outer product) | |
| def gram_matrix(x): | |
| assert K.ndim(x) == 3 | |
| if K.image_data_format() == 'channels_first': | |
| features = K.batch_flatten(x) | |
| else: | |
| features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1))) | |
| gram = K.dot(features, K.transpose(features)) | |
| return gram | |
| # the "style loss" is designed to maintain | |
| # the style of the reference image in the generated image. | |
| # It is based on the gram matrices (which capture style) of | |
| # feature maps from the style reference image | |
| # and from the generated image | |
| def style_loss(style, combination): | |
| assert K.ndim(style) == 3 | |
| assert K.ndim(combination) == 3 | |
| S = gram_matrix(style) | |
| C = gram_matrix(combination) | |
| channels = 3 | |
| size = img_nrows * img_ncols | |
| return K.sum(K.square(S - C)) / (4. * (channels ** 2) * (size ** 2)) | |
| # an auxiliary loss function | |
| # designed to maintain the "content" of the | |
| # base image in the generated image | |
| def content_loss(base, combination): | |
| return K.sum(K.square(combination - base)) | |
| # the 3rd loss function, total variation loss, | |
| # designed to keep the generated image locally coherent | |
| def total_variation_loss(x): | |
| assert K.ndim(x) == 4 | |
| if K.image_data_format() == 'channels_first': | |
| a = K.square(x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, 1:, :img_ncols - 1]) | |
| b = K.square(x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, :img_nrows - 1, 1:]) | |
| else: | |
| a = K.square(x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, 1:, :img_ncols - 1, :]) | |
| b = K.square(x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, :img_nrows - 1, 1:, :]) | |
| return K.sum(K.pow(a + b, 1.25)) | |
| # combine these loss functions into a single scalar | |
| loss = K.variable(0.) | |
| layer_features = outputs_dict['block5_conv2'] | |
| base_image_features = layer_features[0, :, :, :] | |
| combination_features = layer_features[2, :, :, :] | |
| loss += content_weight * content_loss(base_image_features, | |
| combination_features) | |
| # get the gradients of the generated image wrt the loss | |
| grads = K.gradients(loss, combination_image) | |
| # this Evaluator class makes it possible | |
| # to compute loss and gradients in one pass | |
| # while retrieving them via two separate functions, | |
| # "loss" and "grads". This is done because scipy.optimize | |
| # requires separate functions for loss and gradients, | |
| # but computing them separately would be inefficient. | |
| class Evaluator(object): | |
| def __init__(self): | |
| self.loss_value = None | |
| self.grads_values = None | |
| def loss(self, x): | |
| assert self.loss_value is None | |
| loss_value, grad_values = eval_loss_and_grads(x) | |
| self.loss_value = loss_value | |
| self.grad_values = grad_values | |
| return self.loss_value | |
| def grads(self, x): | |
| assert self.loss_value is not None | |
| grad_values = np.copy(self.grad_values) | |
| self.loss_value = None | |
| self.grad_values = None | |
| return grad_values | |
| evaluator = Evaluator() | |
| # run scipy-based optimization (L-BFGS) over the pixels of the generated image | |
| # so as to minimize the neural style loss | |
| x = preprocess_image(base_image_path) | |
| for i in range(iterations): | |
| print('Start of iteration', i) | |
| start_time = time.time() | |
| x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(), | |
| fprime=evaluator.grads, maxfun=20) | |
| print('Current loss value:', min_val) | |
| # save current generated image | |
| img = deprocess_image(x.copy()) | |
| fname = result_prefix + '_at_iteration_%d.png' % i | |
| save_img(fname, img) | |
| end_time = time.time() | |
| print('Image saved as', fname) | |
| print('Iteration %d completed in %ds' % (i, end_time - start_time)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment