{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Neural Transfer Using PyTorch\n",
    "\n",
    "**Author**: [Alexis Jacq](https://alexis-jacq.github.io)\n",
    "\n",
    "**Edited by**: [Winston Herring](https://github.com/winston6)\n",
    "\n",
    "## Introduction\n",
    "\n",
    "This tutorial explains how to implement the [Neural-Style\n",
    "algorithm](https://arxiv.org/abs/1508.06576) developed by Leon A. Gatys,\n",
    "Alexander S. Ecker and Matthias Bethge. Neural-Style, or\n",
    "Neural-Transfer, allows you to take an image and reproduce it with a new\n",
    "artistic style. The algorithm takes three images, an input image, a\n",
    "content-image, and a style-image, and changes the input to resemble the\n",
    "content of the content-image and the artistic style of the style-image.\n",
    "\n",
    "![/\\_static/img/neural-style/neuralstyle.png](https://pytorch.org/tutorials/_static/img/neural-style/neuralstyle.png)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Underlying Principle\n",
    "\n",
    "The principle is simple: we define two distances, one for the content\n",
    "($D_C$) and one for the style ($D_S$). $D_C$ measures how different the\n",
    "content is between two images while $D_S$ measures how different the\n",
    "style is between two images. Then, we take a third image, the input, and\n",
    "transform it to minimize both its content-distance with the\n",
    "content-image and its style-distance with the style-image. Now we can\n",
    "import the necessary packages and begin the neural transfer.\n",
    "\n",
    "# Importing Packages and Selecting a Device\n",
    "\n",
    "Below is a list of the packages needed to implement the neural transfer.\n",
    "\n",
    "-   `torch`, `torch.nn`, `numpy` (indispensables packages for neural\n",
    "    networks with PyTorch)\n",
    "-   `torch.optim` (efficient gradient descents)\n",
    "-   `PIL`, `PIL.Image`, `matplotlib.pyplot` (load and display images)\n",
    "-   `torchvision.transforms` (transform PIL images into tensors)\n",
    "-   `torchvision.models` (train or load pretrained models)\n",
    "-   `copy` (to deep copy the models; system package)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "\n",
    "from PIL import Image\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "import torchvision.transforms as transforms\n",
    "from torchvision.models import vgg19, VGG19_Weights\n",
    "\n",
    "import copy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we need to choose which device to run the network on and import\n",
    "the content and style images. Running the neural transfer algorithm on\n",
    "large images takes longer and will go much faster when running on a GPU.\n",
    "We can use `torch.cuda.is_available()` to detect if there is a GPU\n",
    "available. Next, we set the `torch.device` for use throughout the\n",
    "tutorial. Also the `.to(device)` method is used to move tensors or\n",
    "modules to a desired device.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "torch.set_default_device(device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Loading the Images\n",
    "\n",
    "Now we will import the style and content images. The original PIL images\n",
    "have values between 0 and 255, but when transformed into torch tensors,\n",
    "their values are converted to be between 0 and 1. The images also need\n",
    "to be resized to have the same dimensions. An important detail to note\n",
    "is that neural networks from the torch library are trained with tensor\n",
    "values ranging from 0 to 1. If you try to feed the networks with 0 to\n",
    "255 tensor images, then the activated feature maps will be unable to\n",
    "sense the intended content and style. However, pretrained networks from\n",
    "the Caffe library are trained with 0 to 255 tensor images.\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>Here are links to download the images required to run the tutorial:<a href=\"https://pytorch.org/tutorials/_static/img/neural-style/picasso.jpg\">picasso.jpg</a> and<a href=\"https://pytorch.org/tutorials/_static/img/neural-style/dancing.jpg\">dancing.jpg</a>.Download these two images and add them to a directorywith name <code>images</code> in your current working directory.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# desired size of the output image\n",
    "imsize = 512 if torch.cuda.is_available() else 128  # use small size if no GPU\n",
    "\n",
    "loader = transforms.Compose([\n",
    "    transforms.Resize(imsize),  # scale imported image\n",
    "    transforms.ToTensor()])  # transform it into a torch tensor\n",
    "\n",
    "\n",
    "def image_loader(image_name):\n",
    "    image = Image.open(image_name)\n",
    "    # fake batch dimension required to fit network's input dimensions\n",
    "    image = loader(image).unsqueeze(0)\n",
    "    return image.to(device, torch.float)\n",
    "\n",
    "\n",
    "style_img = image_loader(\"./data/images/neural-style/picasso.jpg\")\n",
    "content_img = image_loader(\"./data/images/neural-style/dancing.jpg\")\n",
    "\n",
    "assert style_img.size() == content_img.size(), \\\n",
    "    \"we need to import style and content images of the same size\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let\\'s create a function that displays an image by reconverting a\n",
    "copy of it to PIL format and displaying the copy using `plt.imshow`. We\n",
    "will try displaying the content and style images to ensure they were\n",
    "imported correctly.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "unloader = transforms.ToPILImage()  # reconvert into PIL image\n",
    "\n",
    "plt.ion()\n",
    "\n",
    "def imshow(tensor, title=None):\n",
    "    image = tensor.cpu().clone()  # we clone the tensor to not do changes on it\n",
    "    image = image.squeeze(0)      # remove the fake batch dimension\n",
    "    image = unloader(image)\n",
    "    plt.imshow(image)\n",
    "    if title is not None:\n",
    "        plt.title(title)\n",
    "    plt.pause(0.001) # pause a bit so that plots are updated\n",
    "\n",
    "\n",
    "plt.figure()\n",
    "imshow(style_img, title='Style Image')\n",
    "\n",
    "plt.figure()\n",
    "imshow(content_img, title='Content Image')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Loss Functions\n",
    "\n",
    "## Content Loss\n",
    "\n",
    "The content loss is a function that represents a weighted version of the\n",
    "content distance for an individual layer. The function takes the feature\n",
    "maps $F_{XL}$ of a layer $L$ in a network processing input $X$ and\n",
    "returns the weighted content distance $w_{CL}.D_C^L(X,C)$ between the\n",
    "image $X$ and the content image $C$. The feature maps of the content\n",
    "image($F_{CL}$) must be known by the function in order to calculate the\n",
    "content distance. We implement this function as a torch module with a\n",
    "constructor that takes $F_{CL}$ as an input. The distance\n",
    "$\\|F_{XL} - F_{CL}\\|^2$ is the mean square error between the two sets of\n",
    "feature maps, and can be computed using `nn.MSELoss`.\n",
    "\n",
    "We will add this content loss module directly after the convolution\n",
    "layer(s) that are being used to compute the content distance. This way\n",
    "each time the network is fed an input image the content losses will be\n",
    "computed at the desired layers and because of auto grad, all the\n",
    "gradients will be computed. Now, in order to make the content loss layer\n",
    "transparent we must define a `forward` method that computes the content\n",
    "loss and then returns the layer's input. The computed loss is saved as a\n",
    "parameter of the module.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class ContentLoss(nn.Module):\n",
    "\n",
    "    def __init__(self, target,):\n",
    "        super(ContentLoss, self).__init__()\n",
    "        # we 'detach' the target content from the tree used\n",
    "        # to dynamically compute the gradient: this is a stated value,\n",
    "        # not a variable. Otherwise the forward method of the criterion\n",
    "        # will throw an error.\n",
    "        self.target = target.detach()\n",
    "\n",
    "    def forward(self, input):\n",
    "        self.loss = F.mse_loss(input, self.target)\n",
    "        return input"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>: although this module is named <code>ContentLoss</code>, itis not a true PyTorch Loss function. If you want to define your contentloss as a PyTorch Loss function, you have to create a PyTorch autograd functionto recompute/implement the gradient manually in the <code>backward</code>method.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Style Loss\n",
    "\n",
    "The style loss module is implemented similarly to the content loss\n",
    "module. It will act as a transparent layer in a network that computes\n",
    "the style loss of that layer. In order to calculate the style loss, we\n",
    "need to compute the gram matrix $G_{XL}$. A gram matrix is the result of\n",
    "multiplying a given matrix by its transposed matrix. In this application\n",
    "the given matrix is a reshaped version of the feature maps $F_{XL}$ of a\n",
    "layer $L$. $F_{XL}$ is reshaped to form $\\hat{F}_{XL}$, a $K$x$N$\n",
    "matrix, where $K$ is the number of feature maps at layer $L$ and $N$ is\n",
    "the length of any vectorized feature map $F_{XL}^k$. For example, the\n",
    "first line of $\\hat{F}_{XL}$ corresponds to the first vectorized feature\n",
    "map $F_{XL}^1$.\n",
    "\n",
    "Finally, the gram matrix must be normalized by dividing each element by\n",
    "the total number of elements in the matrix. This normalization is to\n",
    "counteract the fact that $\\hat{F}_{XL}$ matrices with a large $N$\n",
    "dimension yield larger values in the Gram matrix. These larger values\n",
    "will cause the first layers (before pooling layers) to have a larger\n",
    "impact during the gradient descent. Style features tend to be in the\n",
    "deeper layers of the network so this normalization step is crucial.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def gram_matrix(input):\n",
    "    a, b, c, d = input.size()  # a=batch size(=1)\n",
    "    # b=number of feature maps\n",
    "    # (c,d)=dimensions of a f. map (N=c*d)\n",
    "\n",
    "    features = input.view(a * b, c * d)  # resize F_XL into \\hat F_XL\n",
    "\n",
    "    G = torch.mm(features, features.t())  # compute the gram product\n",
    "\n",
    "    # we 'normalize' the values of the gram matrix\n",
    "    # by dividing by the number of element in each feature maps.\n",
    "    return G.div(a * b * c * d)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the style loss module looks almost exactly like the content loss\n",
    "module. The style distance is also computed using the mean square error\n",
    "between $G_{XL}$ and $G_{SL}$.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class StyleLoss(nn.Module):\n",
    "\n",
    "    def __init__(self, target_feature):\n",
    "        super(StyleLoss, self).__init__()\n",
    "        self.target = gram_matrix(target_feature).detach()\n",
    "\n",
    "    def forward(self, input):\n",
    "        G = gram_matrix(input)\n",
    "        self.loss = F.mse_loss(G, self.target)\n",
    "        return input"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Importing the Model\n",
    "\n",
    "Now we need to import a pretrained neural network. We will use a 19\n",
    "layer VGG network like the one used in the paper.\n",
    "\n",
    "PyTorch's implementation of VGG is a module divided into two child\n",
    "`Sequential` modules: `features` (containing convolution and pooling\n",
    "layers), and `classifier` (containing fully connected layers). We will\n",
    "use the `features` module because we need the output of the individual\n",
    "convolution layers to measure content and style loss. Some layers have\n",
    "different behavior during training than evaluation, so we must set the\n",
    "network to evaluation mode using `.eval()`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cnn = vgg19(weights=VGG19_Weights.DEFAULT).features.eval()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, VGG networks are trained on images with each channel\n",
    "normalized by mean=\\[0.485, 0.456, 0.406\\] and std=\\[0.229, 0.224,\n",
    "0.225\\]. We will use them to normalize the image before sending it into\n",
    "the network.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406])\n",
    "cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225])\n",
    "\n",
    "# create a module to normalize input image so we can easily put it in a\n",
    "# ``nn.Sequential``\n",
    "class Normalization(nn.Module):\n",
    "    def __init__(self, mean, std):\n",
    "        super(Normalization, self).__init__()\n",
    "        # .view the mean and std to make them [C x 1 x 1] so that they can\n",
    "        # directly work with image Tensor of shape [B x C x H x W].\n",
    "        # B is batch size. C is number of channels. H is height and W is width.\n",
    "        self.mean = torch.tensor(mean).view(-1, 1, 1)\n",
    "        self.std = torch.tensor(std).view(-1, 1, 1)\n",
    "\n",
    "    def forward(self, img):\n",
    "        # normalize ``img``\n",
    "        return (img - self.mean) / self.std"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A `Sequential` module contains an ordered list of child modules. For\n",
    "instance, `vgg19.features` contains a sequence (`Conv2d`, `ReLU`,\n",
    "`MaxPool2d`, `Conv2d`, `ReLU`...) aligned in the right order of depth.\n",
    "We need to add our content loss and style loss layers immediately after\n",
    "the convolution layer they are detecting. To do this we must create a\n",
    "new `Sequential` module that has content loss and style loss modules\n",
    "correctly inserted.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# desired depth layers to compute style/content losses :\n",
    "content_layers_default = ['conv_4']\n",
    "style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']\n",
    "\n",
    "def get_style_model_and_losses(cnn, normalization_mean, normalization_std,\n",
    "                               style_img, content_img,\n",
    "                               content_layers=content_layers_default,\n",
    "                               style_layers=style_layers_default):\n",
    "    # normalization module\n",
    "    normalization = Normalization(normalization_mean, normalization_std)\n",
    "\n",
    "    # just in order to have an iterable access to or list of content/style\n",
    "    # losses\n",
    "    content_losses = []\n",
    "    style_losses = []\n",
    "\n",
    "    # assuming that ``cnn`` is a ``nn.Sequential``, so we make a new ``nn.Sequential``\n",
    "    # to put in modules that are supposed to be activated sequentially\n",
    "    model = nn.Sequential(normalization)\n",
    "\n",
    "    i = 0  # increment every time we see a conv\n",
    "    for layer in cnn.children():\n",
    "        if isinstance(layer, nn.Conv2d):\n",
    "            i += 1\n",
    "            name = 'conv_{}'.format(i)\n",
    "        elif isinstance(layer, nn.ReLU):\n",
    "            name = 'relu_{}'.format(i)\n",
    "            # The in-place version doesn't play very nicely with the ``ContentLoss``\n",
    "            # and ``StyleLoss`` we insert below. So we replace with out-of-place\n",
    "            # ones here.\n",
    "            layer = nn.ReLU(inplace=False)\n",
    "        elif isinstance(layer, nn.MaxPool2d):\n",
    "            name = 'pool_{}'.format(i)\n",
    "        elif isinstance(layer, nn.BatchNorm2d):\n",
    "            name = 'bn_{}'.format(i)\n",
    "        else:\n",
    "            raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))\n",
    "\n",
    "        model.add_module(name, layer)\n",
    "\n",
    "        if name in content_layers:\n",
    "            # add content loss:\n",
    "            target = model(content_img).detach()\n",
    "            content_loss = ContentLoss(target)\n",
    "            model.add_module(\"content_loss_{}\".format(i), content_loss)\n",
    "            content_losses.append(content_loss)\n",
    "\n",
    "        if name in style_layers:\n",
    "            # add style loss:\n",
    "            target_feature = model(style_img).detach()\n",
    "            style_loss = StyleLoss(target_feature)\n",
    "            model.add_module(\"style_loss_{}\".format(i), style_loss)\n",
    "            style_losses.append(style_loss)\n",
    "\n",
    "    # now we trim off the layers after the last content and style losses\n",
    "    for i in range(len(model) - 1, -1, -1):\n",
    "        if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):\n",
    "            break\n",
    "\n",
    "    model = model[:(i + 1)]\n",
    "\n",
    "    return model, style_losses, content_losses"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we select the input image. You can use a copy of the content image\n",
    "or white noise.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "input_img = content_img.clone()\n",
    "# if you want to use white noise by using the following code:\n",
    "#\n",
    "# .. code-block:: python\n",
    "#\n",
    "#    input_img = torch.randn(content_img.data.size())\n",
    "\n",
    "# add the original input image to the figure:\n",
    "plt.figure()\n",
    "imshow(input_img, title='Input Image')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Gradient Descent\n",
    "\n",
    "As Leon Gatys, the author of the algorithm, suggested\n",
    "[here](https://discuss.pytorch.org/t/pytorch-tutorial-for-neural-transfert-of-artistic-style/336/20?u=alexis-jacq),\n",
    "we will use L-BFGS algorithm to run our gradient descent. Unlike\n",
    "training a network, we want to train the input image in order to\n",
    "minimize the content/style losses. We will create a PyTorch L-BFGS\n",
    "optimizer `optim.LBFGS` and pass our image to it as the tensor to\n",
    "optimize.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def get_input_optimizer(input_img):\n",
    "    # this line to show that input is a parameter that requires a gradient\n",
    "    optimizer = optim.LBFGS([input_img])\n",
    "    return optimizer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we must define a function that performs the neural transfer.\n",
    "For each iteration of the networks, it is fed an updated input and\n",
    "computes new losses. We will run the `backward` methods of each loss\n",
    "module to dynamically compute their gradients. The optimizer requires a\n",
    "\"closure\" function, which reevaluates the module and returns the loss.\n",
    "\n",
    "We still have one final constraint to address. The network may try to\n",
    "optimize the input with values that exceed the 0 to 1 tensor range for\n",
    "the image. We can address this by correcting the input values to be\n",
    "between 0 to 1 each time the network is run.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def run_style_transfer(cnn, normalization_mean, normalization_std,\n",
    "                       content_img, style_img, input_img, num_steps=300,\n",
    "                       style_weight=1000000, content_weight=1):\n",
    "    \"\"\"Run the style transfer.\"\"\"\n",
    "    print('Building the style transfer model..')\n",
    "    model, style_losses, content_losses = get_style_model_and_losses(cnn,\n",
    "        normalization_mean, normalization_std, style_img, content_img)\n",
    "\n",
    "    # We want to optimize the input and not the model parameters so we\n",
    "    # update all the requires_grad fields accordingly\n",
    "    input_img.requires_grad_(True)\n",
    "    # We also put the model in evaluation mode, so that specific layers \n",
    "    # such as dropout or batch normalization layers behave correctly. \n",
    "    model.eval()\n",
    "    model.requires_grad_(False)\n",
    "\n",
    "    optimizer = get_input_optimizer(input_img)\n",
    "\n",
    "    print('Optimizing..')\n",
    "    run = [0]\n",
    "    while run[0] <= num_steps:\n",
    "\n",
    "        def closure():\n",
    "            # correct the values of updated input image\n",
    "            with torch.no_grad():\n",
    "                input_img.clamp_(0, 1)\n",
    "\n",
    "            optimizer.zero_grad()\n",
    "            model(input_img)\n",
    "            style_score = 0\n",
    "            content_score = 0\n",
    "\n",
    "            for sl in style_losses:\n",
    "                style_score += sl.loss\n",
    "            for cl in content_losses:\n",
    "                content_score += cl.loss\n",
    "\n",
    "            style_score *= style_weight\n",
    "            content_score *= content_weight\n",
    "\n",
    "            loss = style_score + content_score\n",
    "            loss.backward()\n",
    "\n",
    "            run[0] += 1\n",
    "            if run[0] % 50 == 0:\n",
    "                print(\"run {}:\".format(run))\n",
    "                print('Style Loss : {:4f} Content Loss: {:4f}'.format(\n",
    "                    style_score.item(), content_score.item()))\n",
    "                print()\n",
    "\n",
    "            return style_score + content_score\n",
    "\n",
    "        optimizer.step(closure)\n",
    "\n",
    "    # a last correction...\n",
    "    with torch.no_grad():\n",
    "        input_img.clamp_(0, 1)\n",
    "\n",
    "    return input_img"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we can run the algorithm.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,\n",
    "                            content_img, style_img, input_img)\n",
    "\n",
    "plt.figure()\n",
    "imshow(output, title='Output Image')\n",
    "\n",
    "# sphinx_gallery_thumbnail_number = 4\n",
    "plt.ioff()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
