Mindspore框架:CycleGAN模型实现图像风格迁移算法
- Mindspore框架CycleGAN模型实现图像风格迁移|(一)CycleGAN神经网络模型构建
- Mindspore框架CycleGAN模型实现图像风格迁移|(二)实例数据集(苹果2橘子)
- Mindspore框架CycleGAN模型实现图像风格迁移|(三)损失函数计算
- Mindspore框架CycleGAN模型实现图像风格迁移|(四)CycleGAN模型训练
- Mindspore框架CycleGAN模型实现图像风格迁移|(五)CycleGAN模型推理与资源下载
CycleGAN神经网络模型构建
1. 关于CycleGAN神经网络模型
CycleGAN(Cycle Generative Adversarial Network)
即循环对抗生成网络。
该模型实现了一种在没有配对示例的情况下学习将图像从源域 X 转换到目标域 Y 的方法。实现图像风格迁移。
经典风格迁移模型
Pix2Pix
,要求训练数据必须是成对的,而现实生活中,要找到两个域(画风)成对出现的图片是相当困难的。CycleGAN
是一种新的无监督的图像迁移网络。更有可行性。
CycleGAN 网络本质上是由两个镜像对称的 GAN 网络组成,其结构如下:
X是一种风格,比如苹果;Y 是另一种风格,比如橘子。
𝐺为将苹果风格X生成橘子风格Y的生成器网络;𝐹为将橘子生成的苹果风格的生成器网络。
𝐷𝑋和 𝐷𝑌为其相应判别器网络。
模型最终能够输出两个模型的权重,分别将两种图像的风格进行彼此迁移,生成新的图像。
2.CycleGAN构建
输入大小为256×256以上的,需要采用9个残差块相连,超参数 n_layers=9 参数控制残差块数。
构建ConvNormReLU
,ResidualBlock
子网络,搭建ResNetGenerator
实现G、F生成器。
- 生成器网络构建
import mindspore.nn as nn
import mindspore.ops as ops
from mindspore.common.initializer import Normal
weight_init = Normal(sigma=0.02)
class ConvNormReLU(nn.Cell):
def __init__(self, input_channel, out_planes, kernel_size=4, stride=2, alpha=0.2, norm_mode='instance',
pad_mode='CONSTANT', use_relu=True, padding=None, transpose=False):
super(ConvNormReLU, self).__init__()
norm = nn.BatchNorm2d(out_planes)
if norm_mode == 'instance':
norm = nn.BatchNorm2d(out_planes, affine=False)
has_bias = (norm_mode == 'instance')
if padding is None:
padding = (kernel_size - 1) // 2
if pad_mode == 'CONSTANT':
if transpose:
conv = nn.Conv2dTranspose(input_channel, out_planes, kernel_size, stride, pad_mode='same',
has_bias=has_bias, weight_init=weight_init)
else:
conv = nn.Conv2d(input_channel, out_planes