学会CycleGAN进行风格迁移,实现自定义滤镜(1)

数据集介绍与加载


本项目,使用莫奈绘画和自然照片数据集来训练CycleGAN,该数据集来自UC Berkeley的CycleGAN数据集官方目录,同时也可以使用其他风格图片,包括梵高绘画等。

dataset_name = ‘vangogh2photo’

dataset, ds_info = tfds.load(f’cycle_gan/{dataset_name}', with_info=True, as_supervised=True)

train_vangogh, train_photo = dataset[‘trainA’], dataset[‘trainB’]

test_vangogh, test_photo = dataset[‘testA’], dataset[‘testB’]

CycleGAN模型


简单回顾下 CycleGAN 的原理,其模型的精髓主要是利用循环一致性损失,训练两个生成器—鉴别器对,从而实现了用不成对数据进行图像到图像的翻译。

数据预处理

数据预处理环节,首先将图片进行规范化至 [0, 1] 范围内,并且将图片缩放为模型可接受的尺寸。

normalizing the images to [-1, 1]

def normalize(image):

image = tf.cast(image, tf.float32)

image = (image / 127.5) - 1

return image

def preprocess(image, label):

image = tf.image.resize(image, [IMG_WIDTH, IMG_HEIGHT])

image = normalize(image)

return image

train_vangogh = train_vangogh.map(preprocess, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()

train_photo = train_photo.map(preprocess, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()

test_vangogh = test_vangogh.map(preprocess, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()

test_photo = test_photo.map(preprocess, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).repeat()

模型构建

由于在 CycleGAN 中使用了使用了实例规范化,而 Tensorflow 并未提供实例规范化,因此可以自定义实现此层:

class InstanceNormalization(tf.keras.layers.Layer):

def init(self, epsilon=1e-5):

super(InstanceNormalization, self).init()

self.epsilon = epsilon

def build(self, input_shape):

self.scale = self.add_weight(

name=‘scale’,

shape=input_shape[-1:],

initializer=tf.random_normal_initializer(1., 0.02),

trainable=True)

self.offset = self.add_weight(

name=‘offset’,

shape=input_shape[-1:],

in

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值