{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "g_nWetWWd_ns" }, "outputs": [], "source": [ "##### Copyright 2018 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "2pHVBk_seED1", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "6msVLevwcRhm" }, "source": [ "# 神经风格迁移" ] }, { "cell_type": "markdown", "metadata": { "id": "Ds4o1h4WHz9U" }, "source": [ "\n", " \n", " \n", " \n", " \n", " \n", "
在 TensorFlow.org 上查看 在 Google Colab 中运行 在 GitHub 中查看源代码下载笔记本查看 TF Hub 模型
" ] }, { "cell_type": "markdown", "metadata": { "id": "aDyGj8DmXCJI" }, "source": [ "本教程使用深度学习通过其他图像的风格创造图像(您是否也曾希望自己可以像毕加索或梵高一样绘画?)。 这项技术被称为*神经风格迁移*,有关信息在 A Neural Algorithm of Artistic Style(Gatys 等人)中进行了概述。\n", "\n", "注:本教程演示了原始的风格迁移算法。它将图像内容优化为特定风格。现代方式会训练模型以直接生成风格化图像(类似于 [CycleGAN](./cyclegan.ipynb))。这种方式要快得多(最多可达 1000 倍)。\n", "\n", "有关使用 [TensorFlow Hub](https://tfhub.dev) 中的预训练模型进行风格迁移的简单应用,请查看使用[任意图像风格化模型](https://tensorflow.google.cn/hub/tutorials/tf2_arbitrary_image_stylization)的[任意样式的快速风格迁移](https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2)教程。有关使用 [TensorFlow Lite](https://tensorflow.google.cn/lite) 进行风格迁移的示例,请参阅[使用 TensorFlow Lite 进行艺术风格迁移](https://tensorflow.google.cn/lite/examples/style_transfer/overview)。" ] }, { "cell_type": "markdown", "metadata": { "id": "1b3XwN9V1nvR" }, "source": [ "神经风格迁移是一种优化技术,主要用于获取两个图像(*内容*图像和*风格*参考图像(例如著名画家的艺术作品))并将它们混合在一起,以便使输出图像看起来像内容图像,但却是以风格参考图像的风格“绘制”的。\n", "\n", "这是通过优化输出图像以匹配内容图像的内容统计和风格参考图像的风格统计来实现的。这些统计信息是使用卷积网络从图像中提取的。" ] }, { "cell_type": "markdown", "metadata": { "id": "3kb_UJY-jCEl" }, "source": [ "例如,让我们为这只狗和 Wassily Kandinsky 的构图 7 拍摄一张图像:\n", "\n", " \n", "\n", "[黄色拉布拉多犬](https://commons.wikimedia.org/wiki/File:YellowLabradorLooking_new.jpg),来自 Wikimedia Commons 的 [Elf](https://en.wikipedia.org/wiki/User:Elf)。许可证 [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/deed.en)\n", "\n", " \n", "\n", "现在,如果 Kandinsky 决定用这种风格专门为这只狗绘画,会是什么样子?是否会是类似这样的画作?\n", "\n", " " ] }, { "cell_type": "markdown", "metadata": { "id": "U8ajP_u73s6m" }, "source": [ "## 安装\n" ] }, { "cell_type": "markdown", "metadata": { "id": "eqxUicSPUOP6" }, "source": [ "### 导入和配置模块" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "NyftRTSMuwue", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "import os\n", "import tensorflow as tf\n", "# Load compressed models from tensorflow_hub\n", "os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED'" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "sc1OLbOWhPCO", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "import IPython.display as display\n", "\n", "import matplotlib.pyplot as plt\n", "import matplotlib as mpl\n", "mpl.rcParams['figure.figsize'] = (12, 12)\n", "mpl.rcParams['axes.grid'] = False\n", "\n", "import numpy as np\n", "import PIL.Image\n", "import time\n", "import functools" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GM6VEGrGLh62", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def tensor_to_image(tensor):\n", " tensor = tensor*255\n", " tensor = np.array(tensor, dtype=np.uint8)\n", " if np.ndim(tensor)>3:\n", " assert tensor.shape[0] == 1\n", " tensor = tensor[0]\n", " return PIL.Image.fromarray(tensor)" ] }, { "cell_type": "markdown", "metadata": { "id": "oeXebYusyHwC" }, "source": [ "下载图像并选择风格图像和内容图像:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wqc0OJHwyFAk", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "content_path = tf.keras.utils.get_file('YellowLabradorLooking_new.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/YellowLabradorLooking_new.jpg')\n", "style_path = tf.keras.utils.get_file('kandinsky5.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/Vassily_Kandinsky%2C_1913_-_Composition_7.jpg')" ] }, { "cell_type": "markdown", "metadata": { "id": "xE4Yt8nArTeR" }, "source": [ "## 呈现输入" ] }, { "cell_type": "markdown", "metadata": { "id": "klh6ObK2t_vH" }, "source": [ "定义一个加载图像的函数,并将其最大尺寸限制为 512 像素。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3TLljcwv5qZs", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def load_img(path_to_img):\n", " max_dim = 512\n", " img = tf.io.read_file(path_to_img)\n", " img = tf.image.decode_image(img, channels=3)\n", " img = tf.image.convert_image_dtype(img, tf.float32)\n", "\n", " shape = tf.cast(tf.shape(img)[:-1], tf.float32)\n", " long_dim = max(shape)\n", " scale = max_dim / long_dim\n", "\n", " new_shape = tf.cast(shape * scale, tf.int32)\n", "\n", " img = tf.image.resize(img, new_shape)\n", " img = img[tf.newaxis, :]\n", " return img" ] }, { "cell_type": "markdown", "metadata": { "id": "2yAlRzJZrWM3" }, "source": [ "创建一个简单的函数来显示图像:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "cBX-eNT8PAK_", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def imshow(image, title=None):\n", " if len(image.shape) > 3:\n", " image = tf.squeeze(image, axis=0)\n", "\n", " plt.imshow(image)\n", " if title:\n", " plt.title(title)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_UWQmeEaiKkP", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "content_image = load_img(content_path)\n", "style_image = load_img(style_path)\n", "\n", "plt.subplot(1, 2, 1)\n", "imshow(content_image, 'Content Image')\n", "\n", "plt.subplot(1, 2, 2)\n", "imshow(style_image, 'Style Image')" ] }, { "cell_type": "markdown", "metadata": { "id": "YMzChXSlKTA2" }, "source": [ "## 使用 TF-Hub 进行快速风格迁移\n", "\n", "本教程演示了原始风格迁移算法,这种算法将图像内容优化为特定风格。在了解细节之前,我们先看一下 [TensorFlow Hub 模型](https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2)是如何做到这一点的:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "iYSLexgRKSh-", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "import tensorflow_hub as hub\n", "hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')\n", "stylized_image = hub_model(tf.constant(content_image), tf.constant(style_image))[0]\n", "tensor_to_image(stylized_image)" ] }, { "cell_type": "markdown", "metadata": { "id": "GEwZ7FlwrjoZ" }, "source": [ "## 定义内容和风格的表示\n", "\n", "使用模型的中间层来获取图像的*内容*和*风格*表示。从网络的输入层开始,前几个层的激活表示边缘和纹理等低级特征。随着深入网络,最后几层代表更高级的特征 – 对象部分,如*轮子*或*眼睛*。在此教程中,我们使用的是 VGG19 网络架构,这是一个已经预训练好的图像分类网络。这些中间层是从图像中定义内容和风格的表示所必需的。对于输入图像,我们尝试匹配这些中间层的相应风格和内容目标的表示。\n" ] }, { "cell_type": "markdown", "metadata": { "id": "LP_7zrziuiJk" }, "source": [ "加载 [VGG19](https://keras.io/applications/#vgg19) 并在我们的图像上测试它以确保正常运行:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "fMbzrr7BCTq0", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "x = tf.keras.applications.vgg19.preprocess_input(content_image*255)\n", "x = tf.image.resize(x, (224, 224))\n", "vgg = tf.keras.applications.VGG19(include_top=True, weights='imagenet')\n", "prediction_probabilities = vgg(x)\n", "prediction_probabilities.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1_FyCm0dYnvl", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "predicted_top_5 = tf.keras.applications.vgg19.decode_predictions(prediction_probabilities.numpy())[0]\n", "[(class_name, prob) for (number, class_name, prob) in predicted_top_5]" ] }, { "cell_type": "markdown", "metadata": { "id": "ljpoYk-0f6HS" }, "source": [ "现在,加载没有分类部分的 `VGG19` ,并列出各层的名称:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Yh_AV6220ebD", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')\n", "\n", "print()\n", "for layer in vgg.layers:\n", " print(layer.name)" ] }, { "cell_type": "markdown", "metadata": { "id": "Wt-tASys0eJv" }, "source": [ "从网络中选择中间层的输出以表示图像的风格和内容:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ArfX_6iA0WAX", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "content_layers = ['block5_conv2'] \n", "\n", "style_layers = ['block1_conv1',\n", " 'block2_conv1',\n", " 'block3_conv1', \n", " 'block4_conv1', \n", " 'block5_conv1']\n", "\n", "num_content_layers = len(content_layers)\n", "num_style_layers = len(style_layers)" ] }, { "cell_type": "markdown", "metadata": { "id": "2o4nSwuN0U3X" }, "source": [ "#### 用于表示风格和内容的中间层\n", "\n", "那么,为什么我们预训练的图像分类网络中的这些中间层的输出允许我们定义风格和内容的表示?\n", "\n", "从高层理解,为了使网络能够实现图像分类(该网络已被训练过),它必须理解图像。 这需要将原始图像作为输入像素并构建内部表示,这个内部表示将原始图像像素转换为对图像中存在的 feature (特征)的复杂理解。\n", "\n", "这也是卷积神经网络能够很好地泛化的原因:它们能够捕获不变性并定义类内的特征(例如猫与狗),这些特征与背景噪声和其他滋扰无关。因此,在将原始图像输入模型和输出分类标签之间的某个位置,该模型用作复杂的特征提取程序。通过访问模型的中间层,您可以描述输入图像的内容和风格。" ] }, { "cell_type": "markdown", "metadata": { "id": "Jt3i3RRrJiOX" }, "source": [ "## 构建模型\n", "\n", "`tf.keras.applications` 中的网络让您可以使用 Keras 函数式 API 轻松提取中间层值。\n", "\n", "要使用函数式 API 定义模型,请指定输入和输出:\n", "\n", "`model = Model(inputs, outputs)`\n", "\n", "以下函数构建了一个 VGG19 模型,该模型返回一个中间层输出的列表:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nfec6MuMAbPx", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def vgg_layers(layer_names):\n", " \"\"\" Creates a VGG model that returns a list of intermediate output values.\"\"\"\n", " # Load our model. Load pretrained VGG, trained on ImageNet data\n", " vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')\n", " vgg.trainable = False\n", " \n", " outputs = [vgg.get_layer(name).output for name in layer_names]\n", "\n", " model = tf.keras.Model([vgg.input], outputs)\n", " return model" ] }, { "cell_type": "markdown", "metadata": { "id": "jbaIvZf5wWn_" }, "source": [ "然后建立模型:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "LkyvPpBHSfVi", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "style_extractor = vgg_layers(style_layers)\n", "style_outputs = style_extractor(style_image*255)\n", "\n", "#Look at the statistics of each layer's output\n", "for name, output in zip(style_layers, style_outputs):\n", " print(name)\n", " print(\" shape: \", output.numpy().shape)\n", " print(\" min: \", output.numpy().min())\n", " print(\" max: \", output.numpy().max())\n", " print(\" mean: \", output.numpy().mean())\n", " print()" ] }, { "cell_type": "markdown", "metadata": { "id": "lGUfttK9F8d5" }, "source": [ "## 风格计算\n", "\n", "图像的内容由中间 feature maps (特征图)的值表示。\n", "\n", "事实证明,图像的风格可以通过不同 feature maps (特征图)上的平均值和相关性来描述。 通过在每个位置计算 feature (特征)向量的外积,并在所有位置对该外积进行平均,可以计算出包含此信息的 Gram 矩阵。 对于特定层的 Gram 矩阵,具体计算方法如下所示:\n", "\n", "$$G^l_{cd} = \\frac{\\sum_{ij} F^l_{ijc}(x)F^l_{ijd}(x)}{IJ}$$\n", "\n", "这可以使用 `tf.linalg.einsum` 函数简洁地实现:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "HAy1iGPdoEpZ", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def gram_matrix(input_tensor):\n", " result = tf.linalg.einsum('bijc,bijd->bcd', input_tensor, input_tensor)\n", " input_shape = tf.shape(input_tensor)\n", " num_locations = tf.cast(input_shape[1]*input_shape[2], tf.float32)\n", " return result/(num_locations)" ] }, { "cell_type": "markdown", "metadata": { "id": "pXIUX6czZABh" }, "source": [ "## 提取风格和内容\n" ] }, { "cell_type": "markdown", "metadata": { "id": "1HGHvwlJ1nkn" }, "source": [ "构建一个返回风格和内容张量的模型。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Sr6QALY-I1ja", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "class StyleContentModel(tf.keras.models.Model):\n", " def __init__(self, style_layers, content_layers):\n", " super(StyleContentModel, self).__init__()\n", " self.vgg = vgg_layers(style_layers + content_layers)\n", " self.style_layers = style_layers\n", " self.content_layers = content_layers\n", " self.num_style_layers = len(style_layers)\n", " self.vgg.trainable = False\n", "\n", " def call(self, inputs):\n", " \"Expects float input in [0,1]\"\n", " inputs = inputs*255.0\n", " preprocessed_input = tf.keras.applications.vgg19.preprocess_input(inputs)\n", " outputs = self.vgg(preprocessed_input)\n", " style_outputs, content_outputs = (outputs[:self.num_style_layers],\n", " outputs[self.num_style_layers:])\n", "\n", " style_outputs = [gram_matrix(style_output)\n", " for style_output in style_outputs]\n", "\n", " content_dict = {content_name: value\n", " for content_name, value\n", " in zip(self.content_layers, content_outputs)}\n", "\n", " style_dict = {style_name: value\n", " for style_name, value\n", " in zip(self.style_layers, style_outputs)}\n", "\n", " return {'content': content_dict, 'style': style_dict}" ] }, { "cell_type": "markdown", "metadata": { "id": "Xuj1o33t1edl" }, "source": [ "在图像上调用此模型,可以返回 `style_layers` 的 gram 矩阵(风格)和 `content_layers` 的内容:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "rkjO-DoNDU0A", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "extractor = StyleContentModel(style_layers, content_layers)\n", "\n", "results = extractor(tf.constant(content_image))\n", "\n", "print('Styles:')\n", "for name, output in sorted(results['style'].items()):\n", " print(\" \", name)\n", " print(\" shape: \", output.numpy().shape)\n", " print(\" min: \", output.numpy().min())\n", " print(\" max: \", output.numpy().max())\n", " print(\" mean: \", output.numpy().mean())\n", " print()\n", "\n", "print(\"Contents:\")\n", "for name, output in sorted(results['content'].items()):\n", " print(\" \", name)\n", " print(\" shape: \", output.numpy().shape)\n", " print(\" min: \", output.numpy().min())\n", " print(\" max: \", output.numpy().max())\n", " print(\" mean: \", output.numpy().mean())\n" ] }, { "cell_type": "markdown", "metadata": { "id": "y9r8Lyjb_m0u" }, "source": [ "## 运行梯度下降\n", "\n", "使用此风格和内容提取程序,我们现在可以实现风格传输算法。我们通过计算每个图像的输出和目标的均方误差来做到这一点,然后取这些损失值的加权和。\n", "\n", "设置风格和内容的目标值:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "PgkNOnGUFcKa", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "style_targets = extractor(style_image)['style']\n", "content_targets = extractor(content_image)['content']" ] }, { "cell_type": "markdown", "metadata": { "id": "CNPrpl-e_w9A" }, "source": [ "定义一个 `tf.Variable` 来表示要优化的图像。 为了快速实现这一点,使用内容图像对其进行初始化( `tf.Variable` 必须与内容图像的形状相同)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "J0vKxF8ZO6G8", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "image = tf.Variable(content_image)" ] }, { "cell_type": "markdown", "metadata": { "id": "M6L8ojmn_6rH" }, "source": [ "由于这是一个浮点图像,因此我们定义一个函数来保持像素值在 0 和 1 之间:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "kdgpTJwL_vE2", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def clip_0_1(image):\n", " return tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=1.0)" ] }, { "cell_type": "markdown", "metadata": { "id": "MBU5RFpcAo7W" }, "source": [ "创建一个 optimizer。本教程推荐 LBFGS,但 Adam 也可以正常工作:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "r4XZjqUk_5Eu", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "opt = tf.keras.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1)" ] }, { "cell_type": "markdown", "metadata": { "id": "As-evbBiA2qT" }, "source": [ "为了优化它,我们使用两个损失的加权组合来获得总损失:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Dt4pxarvA4I4", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "style_weight=1e-2\n", "content_weight=1e4" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0ggx2Na8oROH", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def style_content_loss(outputs):\n", " style_outputs = outputs['style']\n", " content_outputs = outputs['content']\n", " style_loss = tf.add_n([tf.reduce_mean((style_outputs[name]-style_targets[name])**2) \n", " for name in style_outputs.keys()])\n", " style_loss *= style_weight / num_style_layers\n", "\n", " content_loss = tf.add_n([tf.reduce_mean((content_outputs[name]-content_targets[name])**2) \n", " for name in content_outputs.keys()])\n", " content_loss *= content_weight / num_content_layers\n", " loss = style_loss + content_loss\n", " return loss" ] }, { "cell_type": "markdown", "metadata": { "id": "vbF2WnP9BI5M" }, "source": [ "使用 `tf.GradientTape` 来更新图像。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0t0umkajFIuh", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "@tf.function()\n", "def train_step(image):\n", " with tf.GradientTape() as tape:\n", " outputs = extractor(image)\n", " loss = style_content_loss(outputs)\n", "\n", " grad = tape.gradient(loss, image)\n", " opt.apply_gradients([(grad, image)])\n", " image.assign(clip_0_1(image))" ] }, { "cell_type": "markdown", "metadata": { "id": "5FHMJq4UBRIQ" }, "source": [ "现在,我们运行几个步来测试一下:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Y542mxi-O2a2", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "train_step(image)\n", "train_step(image)\n", "train_step(image)\n", "tensor_to_image(image)" ] }, { "cell_type": "markdown", "metadata": { "id": "mNzE-mTbBVgY" }, "source": [ "运行正常,我们来执行一个更长的优化:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "rQW1tXYoLbUS", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "import time\n", "start = time.time()\n", "\n", "epochs = 10\n", "steps_per_epoch = 100\n", "\n", "step = 0\n", "for n in range(epochs):\n", " for m in range(steps_per_epoch):\n", " step += 1\n", " train_step(image)\n", " print(\".\", end='', flush=True)\n", " display.clear_output(wait=True)\n", " display.display(tensor_to_image(image))\n", " print(\"Train step: {}\".format(step))\n", " \n", "end = time.time()\n", "print(\"Total time: {:.1f}\".format(end-start))" ] }, { "cell_type": "markdown", "metadata": { "id": "GWVB3anJMY2v" }, "source": [ "## 总变分损失\n", "\n", "此实现只是一个基础版本,它的一个缺点是它会产生大量的高频误差。 我们可以直接通过正则化图像的高频分量来减少这些高频误差。 在风格转移中,这通常被称为*总变分损失*:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7szUUybCQMB3", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def high_pass_x_y(image):\n", " x_var = image[:, :, 1:, :] - image[:, :, :-1, :]\n", " y_var = image[:, 1:, :, :] - image[:, :-1, :, :]\n", "\n", " return x_var, y_var" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Atc2oL29PXu_", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "x_deltas, y_deltas = high_pass_x_y(content_image)\n", "\n", "plt.figure(figsize=(14, 10))\n", "plt.subplot(2, 2, 1)\n", "imshow(clip_0_1(2*y_deltas+0.5), \"Horizontal Deltas: Original\")\n", "\n", "plt.subplot(2, 2, 2)\n", "imshow(clip_0_1(2*x_deltas+0.5), \"Vertical Deltas: Original\")\n", "\n", "x_deltas, y_deltas = high_pass_x_y(image)\n", "\n", "plt.subplot(2, 2, 3)\n", "imshow(clip_0_1(2*y_deltas+0.5), \"Horizontal Deltas: Styled\")\n", "\n", "plt.subplot(2, 2, 4)\n", "imshow(clip_0_1(2*x_deltas+0.5), \"Vertical Deltas: Styled\")" ] }, { "cell_type": "markdown", "metadata": { "id": "lqHElVgBkgkz" }, "source": [ "这显示了高频分量如何增加。\n", "\n", "而且,本质上高频分量是一个边缘检测器。 我们可以从 Sobel 边缘检测器获得类似的输出,例如:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "HyvqCiywiUfL", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "plt.figure(figsize=(14, 10))\n", "\n", "sobel = tf.image.sobel_edges(content_image)\n", "plt.subplot(1, 2, 1)\n", "imshow(clip_0_1(sobel[..., 0]/4+0.5), \"Horizontal Sobel-edges\")\n", "plt.subplot(1, 2, 2)\n", "imshow(clip_0_1(sobel[..., 1]/4+0.5), \"Vertical Sobel-edges\")" ] }, { "cell_type": "markdown", "metadata": { "id": "vv5bKlSDnPP7" }, "source": [ "与此相关的正则化损失是这些值的平方和:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "mP-92lXMIYPn", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def total_variation_loss(image):\n", " x_deltas, y_deltas = high_pass_x_y(image)\n", " return tf.reduce_sum(tf.abs(x_deltas)) + tf.reduce_sum(tf.abs(y_deltas))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "s4OYBUX2KQ25", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "total_variation_loss(image).numpy()" ] }, { "cell_type": "markdown", "metadata": { "id": "pu2hJ8zOKMc1" }, "source": [ "这展示了它的作用。但是没有必要自己去实现它,因为 TensorFlow 包括一个标准的实现:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YQjWW04NKLfJ", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "tf.image.total_variation(image).numpy()" ] }, { "cell_type": "markdown", "metadata": { "id": "nTessd-DCdcC" }, "source": [ "## 重新进行优化\n", "\n", "选择 `total_variation_loss` 的权重:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "tGeRLD4GoAd4", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "total_variation_weight=30" ] }, { "cell_type": "markdown", "metadata": { "id": "kG1-T4kJsoAv" }, "source": [ "现在,将它加入 `train_step` 函数中:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "BzmfcyyYUyWq", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "@tf.function()\n", "def train_step(image):\n", " with tf.GradientTape() as tape:\n", " outputs = extractor(image)\n", " loss = style_content_loss(outputs)\n", " loss += total_variation_weight*tf.image.total_variation(image)\n", "\n", " grad = tape.gradient(loss, image)\n", " opt.apply_gradients([(grad, image)])\n", " image.assign(clip_0_1(image))" ] }, { "cell_type": "markdown", "metadata": { "id": "lcLWBQChsutQ" }, "source": [ "重新初始化图像变量和优化器:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "a-dPRr8BqexB", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "opt = tf.keras.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1)\n", "image = tf.Variable(content_image)" ] }, { "cell_type": "markdown", "metadata": { "id": "BEflRstmtGBu" }, "source": [ "并进行优化:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "q3Cc3bLtoOWy", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "import time\n", "start = time.time()\n", "\n", "epochs = 10\n", "steps_per_epoch = 100\n", "\n", "step = 0\n", "for n in range(epochs):\n", " for m in range(steps_per_epoch):\n", " step += 1\n", " train_step(image)\n", " print(\".\", end='', flush=True)\n", " display.clear_output(wait=True)\n", " display.display(tensor_to_image(image))\n", " print(\"Train step: {}\".format(step))\n", "\n", "end = time.time()\n", "print(\"Total time: {:.1f}\".format(end-start))" ] }, { "cell_type": "markdown", "metadata": { "id": "KKox7K46tKxy" }, "source": [ "最后,保存结果:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "SSH6OpyyQn7w", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "file_name = 'stylized-image.png'\n", "tensor_to_image(image).save(file_name)\n", "\n", "try:\n", " from google.colab import files\n", "except ImportError:\n", " pass\n", "else:\n", " files.download(file_name)" ] }, { "cell_type": "markdown", "metadata": { "id": "tNlwRXagxQZk" }, "source": [ "## 了解更多\n", "\n", "本教程演示了原始风格迁移算法。有关风格迁移的简单应用,请查看此[教程](https://tensorflow.google.cn/hub/tutorials/tf2_arbitrary_image_stylization),以详细了解如何使用 [TensorFlow Hub](https://tfhub.dev) 中的任意图像风格迁移模型。" ] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [], "name": "style_transfer.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }