前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >迁移学习实践 深度学习打造图像的别样风格

迁移学习实践 深度学习打造图像的别样风格

作者头像
叶庭云
发布2021-07-01 10:21:58
5990
发布2021-07-01 10:21:58
举报
文章被收录于专栏:Python进阶之路Python进阶之路

文章目录

一、前言

训练环境:Google colab 训练时长:<15min 论文地址:https://arxiv.org/abs/1508.06576

在本教程中,我们将学习如何使用深度学习来创作另一种(毕加索或梵高式)风格的图像,这就是所谓的神经类型迁移!这是列昂·盖茨的论文中概述的一种技术:一种艺术风格的神经算法,非常值得一读。

那么,问题来了,什么是neural style transfer?

答:neural style transfer是一种优化技术,用于取三张图片:内容图片,样式参考图片(如来自同一著名画家的艺术作品),和你想要改造风格的输入图片,将三张图片混合在一起,这样输入图片转化成集内容图片的内容与样式参考图片的样式于一体的别样图片。

例如,让我们来看看这只海龟和葛饰北斋的《神奈川巨浪》:

如果葛饰北斋决定用这种风格来画这只乌龟,那会是什么样子呢?会是这样的吗?

这是魔法还是深度学习?幸运的是,这并不涉及任何巫术:样式转换是一种有趣的技术,它展示了神经网络的功能和内部表示。

神经风格传递的原理是定义两个距离函数,一个描述两幅图像的内容如何不同一个描述两幅图像之间的风格差异。然后,给定三个图像,一个期望的样式图像,一个期望的内容图像,和输入图像(用内容图像初始化),我们尝试转换输入图像,以最小化与内容图像的内容距离和它与样式图像的样式距离。总之,我们将获取基本输入图像、要匹配的内容图像和要匹配的样式图像。我们将通过反向传播最小化内容和样式之间的距离(损失)来转换基本输入图像,创建一个匹配内容图像的内容样式图像的样式的图像。

其中将涉及的具体概念:在这个过程中,我们将围绕以下概念建立实践经验和发展直觉。

  • Eager Execution——使用 TensorFlow 的命令式编程环境,可以立即评估操作。
  • 使用函数API定义模型 ,我们将构建模型的一个子集,它将使我们能够使用函数API访问必要的中间激活。
  • 利用一个预训练模型的特征图—学习如何使用预训练模型及其特征图
  • 创建自定义训练循环——我们将研究如何设置优化器来最小化给定的输入参数损失
  • 我们将按照一般步骤来执行风格转换:可视化数据、基本预处理/准备我们的数据、设置损失函数、创建模型、损失函数优化。

二、代码实践

下载图片(环境:Google colab)

代码语言:javascript
复制
import os
img_dir = '/tmp/nst'
if not os.path.exists(img_dir):
    os.makedirs(img_dir)
!wget --quiet -P /tmp/nst/ https://upload.wikimedia.org/wikipedia/commons/d/d7/Green_Sea_Turtle_grazing_seagrass.jpg
!wget --quiet -P /tmp/nst/ https://upload.wikimedia.org/wikipedia/commons/0/0a/The_Great_Wave_off_Kanagawa.jpg
!wget --quiet -P /tmp/nst/ https://upload.wikimedia.org/wikipedia/commons/b/b4/Vassily_Kandinsky%2C_1913_-_Composition_7.jpg
!wget --quiet -P /tmp/nst/ https://upload.wikimedia.org/wikipedia/commons/0/00/Tuebingen_Neckarfront.jpg
!wget --quiet -P /tmp/nst/ https://upload.wikimedia.org/wikipedia/commons/6/68/Pillars_of_creation_2014_HST_WFC3-UVIS_full-res_denoised.jpg
!wget --quiet -P /tmp/nst/ https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1024px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg
!wget --quiet -P /tmp/nst/ https://img-blog.csdnimg.cn/20210403204754742.jpg

代码运行后,tmp下的 nst 文件夹里有了我们请求下载的图片。

导入需要的依赖库和配置

代码语言:javascript
复制
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams['figure.figsize'] = (10,10)
mpl.rcParams['axes.grid'] = False

import numpy as np
from PIL import Image
import time
import functools
代码语言:javascript
复制
%tensorflow_version 1.x
import tensorflow as tf

from tensorflow.python.keras.preprocessing import image as kp_image
from tensorflow.python.keras import models 
from tensorflow.python.keras import losses
from tensorflow.python.keras import layers
from tensorflow.python.keras import backend as K

我们将从启用 Eager execution 开始。Eager execution允许我们以最清晰和最易读的方式完成这项技术。

代码语言:javascript
复制
tf.enable_eager_execution()
print("Eager execution: {}".format(tf.executing_eagerly()))

定义我们的图片路径

代码语言:javascript
复制
# Set up some global values here
content_path = '/tmp/nst/chongzi.jpg'
style_path = '/tmp/nst/The_Great_Wave_off_Kanagawa.jpg'

可视化输入图像

代码语言:javascript
复制
def load_img(path_to_img):
  max_dim = 512
  img = Image.open(path_to_img)
  long = max(img.size)
  scale = max_dim/long
  img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS)
  
  img = kp_image.img_to_array(img)
  
  # We need to broadcast the image array such that it has a batch dimension 
  img = np.expand_dims(img, axis=0)
  return img
代码语言:javascript
复制
def imshow(img, title=None):
  # Remove the batch dimension
  out = np.squeeze(img, axis=0)
  # Normalize for display 
  out = out.astype('uint8')
  plt.imshow(out)
  if title is not None:
    plt.title(title)
  plt.imshow(out)
代码语言:javascript
复制
plt.figure(figsize=(10,10))

content = load_img(content_path).astype('uint8')
style = load_img(style_path).astype('uint8')

plt.subplot(1, 2, 1)
imshow(content, 'Content Image')

plt.subplot(1, 2, 2)
imshow(style, 'Style Image')
plt.show()

我们期望输出的图像是输入图片转化成集内容图片的内容与样式参考图片的样式于一体的别样图片

准备数据:让我们创建便捷化加载和预处理图像流程的方法。根据 VGG 训练流程,我们执行与预期相同的预处理流程。VGG网络在图像上进行训练,每个通道归一化的平均值为[103.939,116.779,123.68](通道BGR)。

代码语言:javascript
复制
def load_and_process_img(path_to_img):
  img = load_img(path_to_img)
  img = tf.keras.applications.vgg19.preprocess_input(img)
  return img

为了查看优化的输出,我们需要执行逆预处理步骤。此外,由于我们的优化图像的值可能在负无穷和正无穷之间的任何地方,我们必须剪切,以保持我们的值在 0-255 范围内。

代码语言:javascript
复制
def deprocess_img(processed_img):
  x = processed_img.copy()
  if len(x.shape) == 4:
    x = np.squeeze(x, 0)
  assert len(x.shape) == 3, ("Input to deprocess image must be an image of "
                             "dimension [1, height, width, channel] or [height, width, channel]")
  if len(x.shape) != 3:
    raise ValueError("Invalid input to deprocessing image")
  
  # perform the inverse of the preprocessing step
  x[:, :, 0] += 103.939
  x[:, :, 1] += 116.779
  x[:, :, 2] += 123.68
  x = x[:, :, ::-1]

  x = np.clip(x, 0, 255).astype('uint8')
  return x

定义内容和样式表示:为了获得图像的内容和样式表示,我们将查看模型中的一些中间层。随着我们深入模型,这些中间层代表越来越高的阶特征。在这种情况下,我们使用网络架构VGG19,一个预先训练的图像分类网络。这些中间层对于从图像定义内容和样式的表示是必要的。对于输入图像,我们将尝试匹配这些中间层上相应的样式和内容目标表示。

为什么需要中间层? 为了让一个网络执行图像分类(我们的网络已经接受了这样的训练),它必须理解图像。这涉及到将原始图像作为输入像素,并通过将原始图像像素转换为复杂的图像特性理解来构建内部表示。这也是卷积神经网络能够很好地泛化的部分原因:它们能够捕获类(例如,猫vs狗)中的不变性和定义特征,而这些不变性和定义特征对背景噪声和其他滋扰是不可知的。因此,在输入原始图像和输出分类标签之间的某个地方,模型充当一个复杂的特征提取器;因此,通过访问中间层,我们能够描述输入图像的内容和样式。 具体来说,我们将从我们的网络中拉出这些中间层:

代码语言:javascript
复制
# Content layer where will pull our feature maps
content_layers = ['block5_conv2'] 

# Style layer we are interested in
style_layers = ['block1_conv1',
                'block2_conv1',
                'block3_conv1', 
                'block4_conv1', 
                'block5_conv1'
               ]

num_content_layers = len(content_layers)
num_style_layers = len(style_layers)

构建模型:在这种情况下,我们加载VGG19,并将我们的输入张量输入到模型中。这将允许我们提取内容、样式和生成的图像的特征映射(以及随后的内容和样式表示)。我们使用VGG19,正如论文中建议的那样。此外,由于 VGG19 是一个相对简单的模型(与ResNet、Inception等相比),所以功能映射实际上更适合于样式转换。

为了访问与我们的样式和内容特性映射对应的中间层,我们获得了相应的输出,并使用 Keras 函数API,使用所需的输出激活来定义模型。使用函数式 API 定义模型只需定义输入和输出:model = Model(inputs, outputs)。

代码语言:javascript
复制
def get_model():
  """ Creates our model with access to intermediate layers. 
  
  This function will load the VGG19 model and access the intermediate layers. 
  These layers will then be used to create a new model that will take input image
  and return the outputs from these intermediate layers from the VGG model. 
  
  Returns:
    returns a keras model that takes image inputs and outputs the style and 
      content intermediate layers. 
  """
  # Load our model. We load pretrained VGG, trained on imagenet data
  vgg = tf.keras.applications.vgg19.VGG19(include_top=False, weights='imagenet')
  vgg.trainable = False
  # Get output layers corresponding to style and content layers 
  style_outputs = [vgg.get_layer(name).output for name in style_layers]
  content_outputs = [vgg.get_layer(name).output for name in content_layers]
  model_outputs = style_outputs + content_outputs
  # Build model 
  return models.Model(vgg.input, model_outputs)

在上面的代码片段中,我们将加载预先训练好的图像分类网络。然后我们获取前面定义的感兴趣的层。然后,我们通过将模型的输入设置为图像,将输出设置为样式和内容层的输出来定义模型。换句话说,我们创建了一个模型,它将获取输入图像并输出内容和样式中间层!

计算Content Loss:我们将在每一层添加我们的Content Loss。这样,当我们通过模型(在 Eager 中是简单的模型input_image!)提供输入图像时,每次迭代都将正确地计算通过模型的所有内容损失,因为我们正在急切地执行,所以将计算所有的梯度。

其中我们通过一些因子 wl 加权每一层损失的贡献。在我们的例子中,我们将每个层的权重相等(wl=1/|L|)。

Computing style loss

同样,我们将损失作为距离度量。

代码语言:javascript
复制
def gram_matrix(input_tensor):
  # We make the image channels first 
  channels = int(input_tensor.shape[-1])
  a = tf.reshape(input_tensor, [-1, channels])
  n = tf.shape(a)[0]
  gram = tf.matmul(a, a, transpose_a=True)
  return gram / tf.cast(n, tf.float32)

def get_style_loss(base_style, gram_target):
  """Expects two images of dimension h, w, c"""
  # height, width, num filters of each layer
  # We scale the loss at a given layer by the size of the feature map and the number of filters
  height, width, channels = base_style.get_shape().as_list()
  gram_style = gram_matrix(base_style)
  
  return tf.reduce_mean(tf.square(gram_style - gram_target))# / (4. * (channels ** 2) * (width * height) ** 2)

应用样式迁移

运行梯度下降:如果你不熟悉梯度下降/反向传播或需要复习,你绝对应该看看这个令人敬畏的资源。在这种情况下,我们使用 Adam 优化器来最小化我们的损失。我们迭代地更新我们的输出图像,使其损失最小化。我们不更新与我们的网络相关的权值,而是训练我们的输入图像,使损失最小化。为了做到这一点,我们必须知道如何计算损失和梯度。

请注意L-BFGS,如果您熟悉这个算法推荐,不是本教程中使用本教程因为背后的主要动机是为了说明与渴望执行最佳实践,通过使用亚当,我们可以证明autograd/梯度带功能自定义训练循环。

接下来我们将定义一个小助手函数,它将加载内容和样式图像,并通过我们的网络转发它们,然后该网络将输出模型中的内容和样式特征表示。

代码语言:javascript
复制
def get_feature_representations(model, content_path, style_path):
  """Helper function to compute our content and style feature representations.

  This function will simply load and preprocess both the content and style 
  images from their path. Then it will feed them through the network to obtain
  the outputs of the intermediate layers. 
  
  Arguments:
    model: The model that we are using.
    content_path: The path to the content image.
    style_path: The path to the style image
    
  Returns:
    returns the style features and the content features. 
  """
  # Load our images in 
  content_image = load_and_process_img(content_path)
  style_image = load_and_process_img(style_path)
  
  # batch compute content and style features
  style_outputs = model(style_image)
  content_outputs = model(content_image)
  
  
  # Get the style and content feature representations from our model  
  style_features = [style_layer[0] for style_layer in style_outputs[:num_style_layers]]
  content_features = [content_layer[0] for content_layer in content_outputs[num_style_layers:]]
  return style_features, content_features

计算损失和梯度:这里我们用 tf.GradientTape 计算梯度。它允许我们通过跟踪操作来利用自动微分来计算后面的梯度。它记录前向传递过程中的操作,然后计算出损失函数相对于后向传递的输入图像的梯度。

代码语言:javascript
复制
def compute_loss(model, loss_weights, init_image, gram_style_features, content_features):
  """This function will compute the loss total loss.
  
  Arguments:
    model: The model that will give us access to the intermediate layers
    loss_weights: The weights of each contribution of each loss function. 
      (style weight, content weight, and total variation weight)
    init_image: Our initial base image. This image is what we are updating with 
      our optimization process. We apply the gradients wrt the loss we are 
      calculating to this image.
    gram_style_features: Precomputed gram matrices corresponding to the 
      defined style layers of interest.
    content_features: Precomputed outputs from defined content layers of 
      interest.
      
  Returns:
    returns the total loss, style loss, content loss, and total variational loss
  """
  style_weight, content_weight = loss_weights
  
  # Feed our init image through our model. This will give us the content and 
  # style representations at our desired layers. Since we're using eager
  # our model is callable just like any other function!
  model_outputs = model(init_image)
  
  style_output_features = model_outputs[:num_style_layers]
  content_output_features = model_outputs[num_style_layers:]
  
  style_score = 0
  content_score = 0

  # Accumulate style losses from all layers
  # Here, we equally weight each contribution of each loss layer
  weight_per_style_layer = 1.0 / float(num_style_layers)
  for target_style, comb_style in zip(gram_style_features, style_output_features):
    style_score += weight_per_style_layer * get_style_loss(comb_style[0], target_style)
    
  # Accumulate content losses from all layers 
  weight_per_content_layer = 1.0 / float(num_content_layers)
  for target_content, comb_content in zip(content_features, content_output_features):
    content_score += weight_per_content_layer* get_content_loss(comb_content[0], target_content)
  
  style_score *= style_weight
  content_score *= content_weight

  # Get total loss
  loss = style_score + content_score 
  return loss, style_score, content_score

然后计算梯度就简单了

代码语言:javascript
复制
def compute_grads(cfg):
  with tf.GradientTape() as tape: 
    all_loss = compute_loss(**cfg)
  # Compute gradients wrt input image
  total_loss = all_loss[0]
  return tape.gradient(total_loss, cfg['init_image']), all_loss

优化循环

代码语言:javascript
复制
import IPython.display

def run_style_transfer(content_path, 
                       style_path,
                       num_iterations=1000,
                       content_weight=1e3, 
                       style_weight=1e-2): 
  # We don't need to (or want to) train any layers of our model, so we set their
  # trainable to false. 
  model = get_model() 
  for layer in model.layers:
    layer.trainable = False
  
  # Get the style and content feature representations (from our specified intermediate layers) 
  style_features, content_features = get_feature_representations(model, content_path, style_path)
  gram_style_features = [gram_matrix(style_feature) for style_feature in style_features]
  
  # Set initial image
  init_image = load_and_process_img(content_path)
  init_image = tf.Variable(init_image, dtype=tf.float32)
  # Create our optimizer
  opt = tf.train.AdamOptimizer(learning_rate=5, beta1=0.99, epsilon=1e-1)

  # For displaying intermediate images 
  iter_count = 1
  
  # Store our best result
  best_loss, best_img = float('inf'), None
  
  # Create a nice config 
  loss_weights = (style_weight, content_weight)
  cfg = {
      'model': model,
      'loss_weights': loss_weights,
      'init_image': init_image,
      'gram_style_features': gram_style_features,
      'content_features': content_features
  }
    
  # For displaying
  num_rows = 2
  num_cols = 5
  display_interval = num_iterations/(num_rows*num_cols)
  start_time = time.time()
  global_start = time.time()
  
  norm_means = np.array([103.939, 116.779, 123.68])
  min_vals = -norm_means
  max_vals = 255 - norm_means   
  
  imgs = []
  for i in range(num_iterations):
    grads, all_loss = compute_grads(cfg)
    loss, style_score, content_score = all_loss
    opt.apply_gradients([(grads, init_image)])
    clipped = tf.clip_by_value(init_image, min_vals, max_vals)
    init_image.assign(clipped)
    end_time = time.time() 
    
    if loss < best_loss:
      # Update best loss and best image from total loss. 
      best_loss = loss
      best_img = deprocess_img(init_image.numpy())

    if i % display_interval== 0:
      start_time = time.time()
      
      # Use the .numpy() method to get the concrete numpy array
      plot_img = init_image.numpy()
      plot_img = deprocess_img(plot_img)
      imgs.append(plot_img)
      IPython.display.clear_output(wait=True)
      IPython.display.display_png(Image.fromarray(plot_img))
      print('Iteration: {}'.format(i))        
      print('Total loss: {:.4e}, ' 
            'style loss: {:.4e}, '
            'content loss: {:.4e}, '
            'time: {:.4f}s'.format(loss, style_score, content_score, time.time() - start_time))
  print('Total time: {:.4f}s'.format(time.time() - global_start))
  IPython.display.clear_output(wait=True)
  plt.figure(figsize=(14,4))
  for i,img in enumerate(imgs):
      plt.subplot(num_rows,num_cols,i+1)
      plt.imshow(img)
      plt.xticks([])
      plt.yticks([])
      
  return best_img, best_loss

模型跑起来!

代码语言:javascript
复制
best, best_loss = run_style_transfer(content_path, style_path, num_iterations=1000)

可视化输出 我们对输出图像进行“deprocess”,以去除对其进行的处理,展示。

代码语言:javascript
复制
def show_results(best_img, content_path, style_path, show_large_final=True):
  plt.figure(figsize=(10, 5))
  content = load_img(content_path) 
  style = load_img(style_path)

  plt.subplot(1, 2, 1)
  imshow(content, 'Content Image')

  plt.subplot(1, 2, 2)
  imshow(style, 'Style Image')

  if show_large_final: 
    plt.figure(figsize=(10, 10))

    plt.imshow(best_img)
    plt.title('Output Image')
    plt.show()
代码语言:javascript
复制
show_results(best, content_path, style_path)

迁移学习打造图像的别样风格,一只玉米螟的图像也能成为艺术品,看起来还不错吧!

推荐阅读: Neural_Style_Transfer_with_Eager_Execution https://zhuanlan.zhihu.com/p/93388054 https://blog.csdn.net/weixin_43264420/article/details/104441258

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-06-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、前言
  • 二、代码实践
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档