使用卷积神经网络,自动将一个图像中的风格应用在另一图像之上,即风格迁移(style transfer)。需要输入两张图片,一张是原图,另一张是想要应用的风格图像,如下图所示,最后输出风格迁移后的合成图像。
8.1 方法
首先,初始化最后的合成图像,例如将其初始化为内容图像,该合成图像是风格迁移过程中唯一需要更新的变量。然后,选择一个预训练的卷积神经网络来抽取图像的特征,其中的模型参数在训练中无须更新。 这个深度卷积神经网络凭借多个层逐级抽取图像的特征,我们可以选择其中某些层的输出作为内容特征或风格特征。
这里的三个卷积层都是同一个卷积网络中的,如图所示,将第二层的输出作为内容特征(越靠近底层的风格特征越接近原图),第一层和第三层的输出作为风格特征。
这里通过控制合成图像与内容图像和样式图像之间的损失,来得到最终的合成图像。减少合成图像中的噪点还引入了总变差损失。
8.2 预处理和后处理函数
预处理函数用来对输入图像在RGB三个通道分别做标准化,并将结果变换成卷积神经网络接受的输入格式。后处理函数用来对输出图像中的像素值还原回标准化之前的值。
#均值和方差是先验经验
rgb_mean = torch.tensor([0.485, 0.456, 0.406])
rgb_std = torch.tensor([0.229, 0.224, 0.225])
#预处理函数实现对图片进行resize并对三个通道进行标准化
def preprocess(img,image_shape):
transforms = torchvision.transforms.Compose(
[torchvision.transforms.Resize(image_shape),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=rgb_mean,std=rgb_std)])
return transforms(img).unsqueeze(0)
#后处理函数
def postprocess(img):
img = img[0].to(rgb_std.device)
#Tensor将输入input张量每个元素的夹紧到区间 [min,max][min,max],并返回结果到一个新张量。
#这里就是把img返回到标准化前的值并固定到0-1之间便于打印图片
img = torch.clamp(img.permute(1,2,0)* rgb_std + rgb_mean,0,1)
return torchvision.transforms.ToPILImage()(img.permute(2,0,1))
8.3 抽取图像的特征
使用基于ImageNet数据集预训练的VGG-19模型来抽取图像特征。这里将0,5,10,19,28层的输出作为风格特征(选择不同层的输出来匹配局部和全局的风格),将25层的输出作为内容特征(为了避免合成图像过多保留内容图像的细节)。
pretrained_net = torchvision.models.vgg19(pretrained=True)
style_layers, content_layers = [0, 5, 10, 19, 28], [25]
net = nn.Sequential(*[pretrained_net.features[i] for i in
range(max(content_layers + style_layers) + 1)])
给定输入X
,如果我们简单地调用前向传播net(X)
,只能获得最后一层的输出。 由于我们还需要中间层的输出,因此这里我们逐层计算,并保留内容层和风格层的输出。
def extract_features(X, content_layers, style_layers):
contents = []
styles = []
for i in range(len(net)):
X = net[i](X)
if i in style_layers:
styles.append(X)
if i in content_layers:
contents.append(X)
return contents, styles
get_contents
函数对内容图像抽取内容特征; get_styles
函数对风格图像抽取风格特征。 因为在训练时无须改变预训练的VGG的模型参数,所以可以在训练开始之前就提取出内容特征和风格特征。
def get_contents(image_shape, device):
content_X = preprocess(content_img, image_shape).to(device)
contents_Y, _ = extract_features(content_X, content_layers, style_layers)
return content_X, contents_Y
def get_styles(image_shape, device):
style_X = preprocess(style_img, image_shape).to(device)
_, styles_Y = extract_features(style_X, content_layers, style_layers)
return style_X, styles_Y
8.3 定义损失函数
由内容损失、风格损失和全变分损失3部分组成。这里全变分损失是由于学到的合成图像里面有大量高频噪点,即有特别亮或者特别暗的颗粒像素。 能够尽可能使邻近的像素值相似。假设xi,j表示坐标(i,j)处的像素值。全变分损失表示为:
#内容损失
def content_loss(Y_hat, Y):
# 我们从动态计算梯度的树中分离目标:
# 这是一个规定的值,而不是一个变量。
return torch.square(Y_hat - Y.detach()).mean()
#风格损失
def gram(X):
num_channels, n = X.shape[1], X.numel() // X.shape[1]
X = X.reshape((num_channels, n))
return torch.matmul(X, X.T) / (num_channels * n)
def style_loss(Y_hat, gram_Y):
return torch.square(gram(Y_hat) - gram_Y.detach()).mean()
#全变分损失
def tv_loss(Y_hat):
return 0.5 * (torch.abs(Y_hat[:, :, 1:, :] - Y_hat[:, :, :-1, :]).mean() +
torch.abs(Y_hat[:, :, :, 1:] - Y_hat[:, :, :, :-1]).mean())
损失函数是内容损失、风格损失和总变化损失的加权和,调节这些权重超参数,我们可以权衡合成图像在保留内容、迁移风格以及去噪三方面的相对重要性。
content_weight,style_weight,tv_weight = 1,1e4,10
def compute_loss(X,contents_Y_hat,styles_Y_hat,contents_Y,styles_Y_gram):
contents_l = [content_loss(Y_hat,Y)*content_weight for Y_hat, Y in zip(
contents_Y_hat, contents_Y)]
styles_l = [style_loss(Y_hat, Y) * style_weight for Y_hat, Y in zip(
styles_Y_hat, styles_Y_gram)]
tv_l = tv_loss(X) * tv_weight
l = sum(10*styles_l + contents_l + [tv_l])
return contents_l, styles_l, tv_l, l
8.4 初始化合成图像
训练期间唯一需要更新的变量就是合成的图像,定义一个简单的模型SynthesizedImage
,并将合成的图像视为模型参数。模型的前向传播只需返回模型参数即可。
class SynthesizedImage(nn.Module):
def __init__(self, img_shape, **kwargs):
super(SynthesizedImage, self).__init__(**kwargs)
self.weight = nn.Parameter(torch.rand(*img_shape))
def forward(self):
return self.weight
定义get_inits
函数创建了合成图像的模型实例,并将其初始化为图像X,并提前计算好风格图像在各个风格层的格拉姆矩阵。
def get_inits(X, device, lr, styles_Y):
gen_img = SynthesizedImage(X.shape).to(device)
gen_img.weight.data.copy_(X.data)
trainer = torch.optim.Adam(gen_img.parameters(), lr=lr)
#风格图像在各个风格层的格拉姆矩阵
styles_Y_gram = [gram(Y) for Y in styles_Y]
return gen_img(), styles_Y_gram, trainer
8.5 训练
def train(X, contents_Y, styles_Y, device, lr, num_epochs, lr_decay_epoch):
X, styles_Y_gram, trainer = get_inits(X, device, lr, styles_Y)
scheduler = torch.optim.lr_scheduler.StepLR(trainer, lr_decay_epoch, 0.8)
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[10, num_epochs],
legend=['content', 'style', 'TV'],
ncols=2, figsize=(7, 2.5))
for epoch in range(num_epochs):
trainer.zero_grad()
contents_Y_hat, styles_Y_hat = extract_features(
X, content_layers, style_layers)
contents_l, styles_l, tv_l, l = compute_loss(
X, contents_Y_hat, styles_Y_hat, contents_Y, styles_Y_gram)
l.backward()
trainer.step()
scheduler.step()
if (epoch + 1) % 10 == 0:
animator.axes[1].imshow(postprocess(X))
animator.add(epoch + 1, [float(sum(contents_l)),
float(sum(styles_l)), float(tv_l)])
return X
device, image_shape = d2l.try_gpu(), (300, 450)
net = net.to(device)
content_X, contents_Y = get_contents(image_shape, device)
_, styles_Y = get_styles(image_shape, device)
output = train(content_X, contents_Y, styles_Y, device, 0.3, 500, 50)
运行结果如下,前面两张图分别是输入的内容图片和风格样式图片,最后一张图为格迁移后的合成图像。
这里我将第一次的输出结果又作为输入再次进行了风格迁移,运行结果如下所示,这里可以看出输出的图像跟style_image更加接近。