Fast neural style in tensorflow based on http://arxiv.org/abs/1603.08155
We consider image transformation problems, where an input image is transformed into an output image. Recent methods for such problems typically train feed-forward convolutional neural networks using a per-pixel loss between the output and ground-truth images. Parallel work has shown that high-quality images can be generated by defining and optimizing perceptual loss functions based on high-level features extracted from pretrained networks. We combine the benefits of both approaches, and propose the use of perceptual loss functions for training feed-forward networks for image transformation tasks. We show results on image style transfer, where a feed-forward network is trained to solve the optimization problem proposed by Gatys et al in real-time. Compared to the optimization-based method, our network gives similar qualitative results but is three orders of magnitude faster. We also experiment with single-image super-resolution, where replacing a per-pixel loss with a perceptual loss gives visually pleasing results.READ FULL TEXT VIEW PDF
Fast neural style in tensorflow based on http://arxiv.org/abs/1603.08155
Implementation of original style transfer paper (Gatys et al)
A Deep Learning toolkit based on iOS Metal
Art to Image Style Transfer using Keras and Tensorflow.
TensorFlow implementation of CNN fast neural style transfer ⚡️ ? ?
Many classic problems can be framed as image transformation
tasks, where a system receives some input image and transforms it into an output image. Examples from image processing include denoising, super-resolution, and colorization, where the input is a degraded image (noisy, low-resolution, or grayscale) and the output is a high-quality color image. Examples from computer vision include semantic segmentation and depth estimation, where the input is a color image and the output image encodes semantic or geometric information about the scene.
One approach for solving image transformation tasks is to train a feed-forward convolutional neural network in a supervised manner, using a per-pixel loss function to measure the difference between output and ground-truth images. This approach has been used for example by Donget al for super-resolution , by Cheng et al for colorization , by Long et al for segmentation , and by Eigen et al for depth and surface normal prediction [4, 5]. Such approaches are efficient at test-time, requiring only a forward pass through the trained network.
However, the per-pixel losses used by these methods do not capture perceptual differences between output and ground-truth images. For example, consider two identical images offset from each other by one pixel; despite their perceptual similarity they would be very different as measured by per-pixel losses.
In parallel, recent work has shown that high-quality images can be generated using perceptual loss functions based not on differences between pixels but instead on differences between high-level image feature representations extracted from pretrained convolutional neural networks. Images are generated by minimizing a loss function. This strategy has been applied to feature inversion  by Mahendran et al, to feature visualization by Simonyan et al  and Yosinski et al , and to texture synthesis and style transfer by Gatys et al [9, 10]. These approaches produce high-quality images, but are slow since inference requires solving an optimization problem.
In this paper we combine the benefits of these two approaches. We train feed-forward transformation networks for image transformation tasks, but rather than using per-pixel loss functions depending only on low-level pixel information, we train our networks using perceptual loss functions that depend on high-level features from a pretrained loss network
. During training, perceptual losses measure image similarities more robustly than per-pixel losses, and at test-time the transformation networks run in real-time.
We experiment on two tasks: style transfer and single-image super-resolution. Both are inherently ill-posed; for style transfer there is no single correct output, and for super-resolution there are many high-resolution images that could have generated the same low-resolution input. Success in either task requires semantic reasoning about the input image. For style transfer the output must be semantically similar to the input despite drastic changes in color and texture; for super-resolution fine details must be inferred from visually ambiguous low-resolution inputs. In principle a high-capacity neural network trained for either task could implicitly learn to reason about the relevant semantics; however in practice we need not learn from scratch: the use of perceptual loss functions allows the transfer of semantic knowledge from the loss network to the transformation network.
For style transfer our feed-forward networks are trained to solve the optimization problem from ; our results are similar to  both qualitatively and as measured by objective function value, but are three orders of magnitude faster to generate. For super-resolution we show that replacing the per-pixel loss with a perceptual loss gives visually pleasing results for and super-resolution.
Feed-forward image transformation. In recent years, a wide variety of feed-forward image transformation tasks have been solved by training deep convolutional neural networks with per-pixel loss functions.
Semantic segmentation methods [3, 5, 12, 13, 14, 15] produce dense scene labels by running a network in a fully-convolutional manner over an input image, training with a per-pixel classification loss.  moves beyond per-pixel losses by framing CRF inference as a recurrent layer trained jointly with the rest of the network. The architecture of our transformation networks are inspired by  and , which use in-network downsampling to reduce the spatial extent of feature maps followed by in-network upsampling to produce the final output image.
Recent methods for depth [5, 4, 16] and surface normal estimation [5, 17] are similar in that they transform a color input image into a geometrically meaningful output image using a feed-forward convolutional network trained with per-pixel regression [4, 5] or classification  losses. Some methods move beyond per-pixel losses by penalizing image gradients  or using a CRF loss layer  to enforce local consistency in the output image. In  a feed-forward model is trained using a per-pixel loss to transform grayscale images to color.
Perceptual optimization. A number of recent papers have used optimization to generate images where the objective is perceptual, depending on high-level features extracted from a convolutional network. Images can be generated to maximize class prediction scores [7, 8] or individual features  in order to understand the functions encoded in trained networks. Similar optimization techniques can also be used to generate high-confidence fooling images [18, 19].
Mahendran and Vedaldi 
invert features from convolutional networks by minimizing a feature reconstruction loss in order to understand the image information retained by different network layers; similar methods had previously been used to invert local binary descriptors and HOG features .
The work of Dosovitskiy and Brox 
is particularly relevant to ours, as they train a feed-forward neural network to invert convolutional features, quickly approximating a solution to the optimization problem posed by. However, their feed-forward network is trained with a per-pixel reconstruction loss, while our networks directly optimize the feature reconstruction loss of .
Style Transfer. Gatys et al  perform artistic style transfer, combining the content of one image with the style of another by jointly minimizing the feature reconstruction loss of  and a style reconstruction loss also based on features extracted from a pretrained convolutional network; a similar method had previously been used for texture synthesis . Their method produces high-quality results, but is computationally expensive since each step of the optimization problem requires a forward and backward pass through the pretrained network. To overcome this computational burden, we train a feed-forward network to quickly approximate solutions to their optimization problem.
Image super-resolution. Image super-resolution is a classic problem for which a wide variety of techniques have been developed. Yang et al  provide an exhaustive evaluation of the prevailing techniques prior to the widespread adoption of convolutional neural networks. They group super-resolution techniques into prediction-based methods (bilinear, bicubic, Lanczos, ), edge-based methods [25, 26], statistical methods [27, 28, 29], patch-based methods [25, 30, 31, 32, 33, 34, 35, 36], and sparse dictionary methods [37, 38]. Recently  achieved excellent performance on single-image super-resolution using a three-layer convolutional neural network trained with a per-pixel Euclidean loss. Other recent state-of-the-art methods include [39, 40, 41].
As shown in Figure 2, our system consists of two components: an image transformation network and a loss network that is used to define several loss functions . The image transformation network is a deep residual convolutional neural network parameterized by weights ; it transforms input images into output images via the mapping . Each loss function computes a scalar value measuring the difference between the output image and a target image
. The image transformation network is trained using stochastic gradient descent to minimize a weighted combination of loss functions:
To address the shortcomings of per-pixel losses and allow our loss functions to better measure perceptual and semantic differences between images, we draw inspiration from recent work that generates images via optimization [6, 7, 8, 9, 10]. The key insight of these methods is that convolutional neural networks pretrained for image classification have already learned to encode the perceptual and semantic information we would like to measure in our loss functions. We therefore make use of a network which as been pretrained for image classification as a fixed loss network in order to define our loss functions. Our deep convolutional transformation network is then trained using loss functions that are also deep convolutional networks.
The loss network is used to define a feature reconstruction loss and a style reconstruction loss that measure differences in content and style between images. For each input image we have a content target and a style target . For style transfer, the content target is the input image and the output image should combine the content of with the style of ; we train one network per style target. For single-image super-resolution, the input image is a low-resolution input, the content target is the ground-truth high-resolution image, and the style reconstruction loss is not used; we train one network per super-resolution factor.
Our image transformation networks roughly follow the architectural guidelines set forth by Radford et al 43] using the architecture of 
. All non-residual convolutional layers are followed by spatial batch normalization
and ReLU nonlinearities with the exception of the output layer, which instead uses a scaledto ensure that the output image has pixels in the range . Other than the first and last layers which use kernels, all convolutional layers use kernels. The exact architectures of all our networks can be found in the supplementary material.
Inputs and Outputs. For style transfer the input and output are both color images of shape . For super-resolution with an upsampling factor of , the output is a high-resolution image patch of shape and the input is a low-resolution patch of shape . Since the image transformation networks are fully-convolutional, at test-time they can be applied to images of any resolution.
Downsampling and Upsampling. For super-resolution with an upsampling factor of , we use several residual blocks followed by convolutional layers with stride 1/2. This is different from 
who use bicubic interpolation to upsample the low-resolution input before passing it to the network. Rather than relying on a fixed upsampling function, fractionally-strided convolution allows the upsampling function to be learned jointly with the rest of the network.
For style transfer our networks use two stride-2 convolutions to downsample the input followed by several residual blocks and then two convolutional layers with stride 1/2 to upsample. Although the input and output have the same size, there are several benefits to networks that downsample and then upsample.
The first is computational. With a naive implementation, a convolution with filters on an input of size requires multiply-adds, which is the same cost as a convolution with filters on an input of shape . After downsampling, we can therefore use a larger network for the same computational cost.
The second benefit has to do with effective receptive field sizes. High-quality style transfer requires changing large parts of the image in a coherent way; therefore it is advantageous for each pixel in the output to have a large effective receptive field in the input. Without downsampling, each additional convolutional layer increases the effective receptive field size by 2. After downsampling by a factor of , each convolution instead increases effective receptive field size by , giving larger effective receptive fields with the same number of layers.
Residual Connections. He et al  use residual connections
to train very deep networks for image classification. They argue that residual connections make it easy for the network to learn the identify function; this is an appealing property for image transformation networks, since in most cases the output image should share structure with the input image. The body of our network thus consists of several residual blocks, each of which contains twoconvolutional layers. We use the residual block design of , shown in the supplementary material.
We define two perceptual loss functions that measure high-level perceptual and semantic differences between images. They make use of a loss network pretrained for image classification, meaning that these perceptual loss functions are themselves deep convolutional neural networks. In all our experiments is the 16-layer VGG network 
pretrained on the ImageNet dataset.
Feature Reconstruction Loss. Rather than encouraging the pixels of the output image to exactly match the pixels of the target image , we instead encourage them to have similar feature representations as computed by the loss network . Let be the activations of the th layer of the network when processing the image ; if is a convolutional layer then will be a feature map of shape . The feature reconstruction loss is the (squared, normalized) Euclidean distance between feature representations:
As demonstrated in  and reproduced in Figure 3, finding an image that minimizes the feature reconstruction loss for early layers tends to produce images that are visually indistinguishable from . As we reconstruct from higher layers, image content and overall spatial structure are preserved but color, texture, and exact shape are not. Using a feature reconstruction loss for training our image transformation networks encourages the output image to be perceptually similar to the target image , but does not force them to match exactly.
Style Reconstruction Loss. The feature reconstruction loss penalizes the output image when it deviates in content from the target . We also wish to penalize differences in style: colors, textures, common patterns, etc. To achieve this effect, Gatys et al [9, 10] propose the following style reconstruction loss.
As above, let be the activations at the th layer of the network for the input , which is a feature map of shape . Define the Gram matrix to be the matrix whose elements are given by
If we interpret as giving -dimensional features for each point on a grid, then is proportional to the uncentered covariance of the -dimensional features, treating each grid location as an independent sample. It thus captures information about which features tend to activate together. The Gram matrix can be computed efficiently by reshaping into a matrix of shape ; then .
The style reconstruction loss is then the squared Frobenius norm of the difference between the Gram matrices of the output and target images:
The style reconstruction loss is well-defined even when and have different sizes, since their Gram matrices will both have the same shape.
As demonstrated in  and reproduced in Figure 5, generating an image that minimizes the style reconstruction loss preserves stylistic features from the target image, but does not preserve its spatial structure. Reconstructing from higher layers transfers larger-scale structure from the target image.
To perform style reconstruction from a set of layers rather than a single layer , we define to be the sum of losses for each layer .
In addition to the perceptual losses defined above, we also define two simple loss functions that depend only on low-level pixel information.
Pixel Loss. The pixel loss is the (normalized) Euclidean distance between the output image and the target . If both have shape , then the pixel loss is defined as . This can only be used when when we have a ground-truth target that the network is expected to match.
We perform experiments on two image transformation tasks: style transfer and single-image super-resolution. Prior work on style transfer has used optimization to generate images; our feed-forward networks give similar qualitative results but are up to three orders of magnitude faster. Prior work on single-image super-resolution with convolutional neural networks has used a per-pixel loss; we show encouraging qualitative results by using a perceptual loss instead.
The goal of style transfer is to generate an image that combines the content of a target content image with the the style of a target style image . We train one image transformation network per style target for several hand-picked style targets and compare our results with the baseline approach of Gatys et al .
Baseline. As a baseline, we reimplement the method of Gatys et al . Given style and content targets and and layers and at which to perform feature and style reconstruction, an image is generated by solving the problem
where , and are scalars,
is initialized with white noise, and optimization is performed using L-BFGS. We find that unconstrained optimization of Equation5 typically results in images whose pixels fall outside the range . For a more fair comparison with our method whose output is constrained to this range, for the baseline we minimize Equation 5 using projected L-BFGS by clipping the image to the range at each iteration. In most cases optimization converges to satisfactory results within 500 iterations. This method is slow because each L-BFGS iteration requires a forward and backward pass through the VGG-16 loss network .
Training Details. Our style transfer networks are trained on the Microsoft COCO dataset . We resize each of the 80k training images to
and train our networks with a batch size of 4 for 40,000 iterations, giving roughly two epochs over the training data. We use Adam with a learning rate of . The output images are regularized with total variation regularization with a strength of between and , chosen via cross-validation per style target. We do not use weight decay or dropout, as the model does not overfit within two epochs. For all style transfer experiments we compute feature reconstruction loss at layer
relu2_2and style reconstruction loss at layers
relu4_3of the VGG-16 loss network
. Our implementation uses Torch and cuDNN ; training takes roughly 4 hours on a single GTX Titan X GPU.
Qualitative Results. In Figure 6
we show qualitative examples comparing our results with those of the baseline method for a variety of style and content images. In all cases the hyperparameters, , and are exactly the same between the two methods; all content images are taken from the MS-COCO 2014 validation set. Overall our results are qualitatively similar to the baseline.
Although our models are trained with images, they can be applied in a fully-convolutional manner to images of any size at test-time. In Figure 7 we show examples of style transfer using our models on images.
In these results it is clear that the trained style transfer network is aware of the semantic content of images. For example in the beach image in Figure 7 the people are clearly recognizable in the transformed image but the background is warped beyond recognition; similarly in the cat image, the cat’s face is clear in the transformed image, but its body is not. One explanation is that the VGG-16 loss network has features which are selective for people and animals since these objects are present in the classification dataset on which it was trained. Our style transfer networks are trained to preserve VGG-16 features, and in doing so they learn to preserve people and animals more than background objects.
Quantitative Results. The baseline and our method both minimize Equation 5. The baseline performs explicit optimization over the output image, while our method is trained to find a solution for any content image in a single forward pass. We may therefore quantitatively compare the two methods by measuring the degree to which they successfully minimize Equation 5.
We run our method and the baseline on 50 images from the MS-COCO validation set, using The Muse by Pablo Picasso as a style image. For the baseline we record the value of the objective function at each iteration of optimization, and for our method we record the value of Equation 5 for each image; we also compute the value of Equation 5 when is equal to the content image . Results are shown in Figure 5. We see that the content image achieves a very high loss, and that our method achieves a loss comparable to between 50 and 100 iterations of explicit optimization.
Although our networks are trained to minimize Equation 5 for images, they are also successful at minimizing the objective when applied to larger images. We repeat the same quantitative evaluation for 50 images at and ; results are shown in Figure 5. We see that even at higher resolutions our model achieves a loss comparable to 50 to 100 iterations of the baseline method.
|Gatys et al ||Speedup|
Speed. In Table 1 we compare the runtime of our method and the baseline for several image sizes; for the baseline we report times for varying numbers of optimization iterations. Across all image sizes, we see that the runtime of our method is approximately twice the speed of a single iteration of the baseline method. Compared to 500 iterations of the baseline method, our method is three orders of magnitude faster. Our method processes images of size at 20 FPS, making it feasible to run style transfer in real-time or on video.
In single-image super-resolution, the task is to generate a high-resolution output image from a low-resolution input. This is an inherently ill-posed problem, since for each low-resolution image there exist multiple high-resolution images that could have generated it. The ambiguity becomes more extreme as the super-resolution factor grows; for large factors (, ), fine details of the high-resolution image may have little or no evidence in its low-resolution version.
To overcome this problem, we train super-resolution networks not with the per-pixel loss typically used  but instead with a feature reconstruction loss (see Section 3) to allow transfer of semantic knowledge from the pretrained loss network to the super-resolution network. We focus on and super-resolution since larger factors require more semantic reasoning about the input.
The traditional metrics used to evaluate super-resolution are PSNR and SSIM , both of which have been found to correlate poorly with human assessment of visual quality [55, 56, 57, 58, 59]. PSNR and SSIM rely only on low-level differences between pixels and operate under the assumption of additive Gaussian noise, which may be invalid for super-resolution. In addition, PSNR is equivalent to the per-pixel loss , so as measured by PSNR a model trained to minimize per-pixel loss should always outperform a model trained to minimize feature reconstruction loss. We therefore emphasize that the goal of these experiments is not to achieve state-of-the-art PSNR or SSIM results, but instead to showcase the qualitative difference between models trained with per-pixel and feature reconstruction losses.
We train models to perform and super-resolution by minimizing feature
reconstruction loss at layer
relu2_2 from the VGG-16 loss network . We train with
patches from 10k images from the MS-COCO training set, and prepare low-resolution
inputs by blurring with a Gaussian kernel of width and downsampling with bicubic
interpolation. We train with a batch size of 4 for 200k iterations using Adam 
with a learning rate of without weight decay or dropout. As a post-processing step,
we perform histogram matching between our network output and the low-resolution input.
Baselines. As a baseline model we use SRCNN  for its state-of-the-art performance. SRCNN is a three-layer convolutional network trained to minimize per-pixel loss on patches from the ILSVRC 2013 detection dataset. SRCNN is not trained for super-resolution, so we can only evaluate it on .
SRCNN is trained for more than iterations, which is not computationally feasible for our models. To account for differences between SRCNN and our model in data, training, and architecture, we train image transformation networks for and super-resolution using ; these networks use identical data, architecture, and training as the networks trained to minimize .
Evaluation. We evaluate all models on the standard Set5 , Set14 , and BSD100  datasets. We report PSNR and SSIM , computing both only on the Y channel after converting to the YCbCr colorspace, following [1, 39].
Results. We show results for super-resolution in Figure 8. Compared to the other methods, our model trained for feature reconstruction does a very good job at reconstructing sharp edges and fine details, such as the eyelashes in the first image and the individual elements of the hat in the second image. The feature reconstruction loss gives rise to a slight cross-hatch pattern visible under magnification, which harms its PSNR and SSIM compared to baseline methods.
Results for super-resolution are shown in Figure 9. Again we see that our model does a good job at edges and fine details compared to other models, such as the horse’s legs and hooves. The model does not sharpen edges indiscriminately; compared to the model, the model sharpens the boundary edges of the horse and rider but the background trees remain diffuse, suggesting that the model may be more aware of image semantics.
Since our and our models share the same architecture, data, and training procedure, all differences between them are due to the difference between the and losses. The loss gives fewer visual artifacts and higher PSNR values but the loss does a better job at reconstructing fine details, leading to pleasing visual results.
In this paper we have combined the benefits of feed-forward image transformation tasks and optimization-based methods for image generation by training feed-forward transformation networks with perceptual loss functions. We have applied this method to style transfer where we achieve comparable performance and drastically improved speed compared to existing methods, and to single-image super-resolution where we show that training with a perceptual loss allows the model to better reconstruct fine details and edges.
In future work we hope to explore the use of perceptual loss functions for other image transformation tasks, such as colorization and semantic segmentation. We also plan to investigate the use of different loss networks to see whether for example loss networks trained on different tasks or datasets can impart image transformation networks with different types of semantic knowledge.
In: Proceedings of the IEEE Conf. on Computer Vision and Pattern Recognition (CVPR). (2015)
Conditional random fields as recurrent neural networks.In: Proceedings of the IEEE International Conference on Computer Vision. (2015) 1529–1537
Image superresolution using support vector regression.Image Processing, IEEE Transactions on 16(6) (2007) 1596–1610
In: Proceedings of The 32nd International Conference on Machine Learning. (2015) 448–456