使用预训练模型VGG19+Tensorflow进行神经风格迁移实战

本文详述了利用TensorFlow和Keras实现神经风格迁移的过程,包括图像预处理、VGG19预训练模型的使用、自定义模型构建、内容代价函数和风格代价函数的定义,以及模型训练和结果展示。在训练过程中,通过调整参数实现了内容与风格的平衡,展示了神经风格迁移的潜力。

  • 一笔一划,一个世界

前言

  • 本次搭建的卷积神经网络使用了VGG19预训练模型搭建神经风格迁移模型,所以使用CPU整个训练过程也很快。
  • 环境和库:windows10+pycharm+tensorflow+keras+python+CPU
  • 使用tensorflow_hub可以快速体验神经风格迁移,不过需要VPN
import tensorflow_hub as hub

# 如果搭了VPN还是出现超时的问题,可以直接点开该url,
# 然后直接download压缩文件,
# 然后解压后把解压后的文件夹路径替换该url即可
hub_module = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/1')
stylized_image = hub_module(tf.constant(content_image), tf.constant(style_image))[0]
# 自定义函数tensor_to_image,实现见下文
tensor_to_image(stylized_image)

正文

库、包、模板

import numpy as np
import pandas as pd

import tensorflow as tf
import keras.preprocessing.image as process_im
from keras.applications import vgg19
from keras.models import Model
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

from PIL import Image		# Python Image Library
import matplotlib.pyplot as plt	# 可视化库
import functools			# 用以为可调用对象(callable objects)定义高阶函数或操作
import IPython.display		# python的交互式shell

图像预处理

  • PIL中的image对象调用resize方法,此处将图像进行缩放为某高宽的高质量图像
  • img_to_array转换前后类型都是一样的,唯一区别是转换前元素类型是整型,转换后元素类型是浮点型(和keras等机器学习框架相适应的图像类型。Keras introduced a special function called img_to_array which accepts an input image and then orders the channels correctly based on the image_data_format setting)
  • expand_dims在数组中增加一个维度,reshape能够达到相同的效果
  • 作用:加载图像;将图像等比例缩放,最长边为512;并返回图像对应三维数组
  • 源码:
# 加载图像;将图像进行缩放,最长边为512;并将图像转换为array输出
def load_img(img_path):
    """

    :param img_path: 
    :return: 
    """
    max_dim = 512
    img = tf.io.read_file(img_path)  # coded
    img = tf.image.decode_image(img, channels=3)  # 0-255
    img = tf.image.convert_image_dtype(img, tf.float32)  # 0-1

    shape = tf.cast(tf.shape(img)[:-1], tf.float32)
    long_dim = max(shape)
    scale = max_dim / long_dim

    new_shape = tf.cast(shape * scale, tf.int32)

    img = tf.image.resize(img, new_shape)
    img = img[tf.newaxis, :]        # 升维,便于卷积神经网络处理
    return img

构建神经风格迁移模型

VGG19预训练模型

  • 函数原型如下,返回一个Kera Model对象
keras.applications.vgg19.VGG19(include_top=True,
							   weights='imagenet', 	
							   input_tensor=None,	
							   input_shape=None, 
							   pooling=None,
							   classes=1000
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值