使用PyTorch进行图像风格转换

    作者: Alexis Jacq

    本教程主要讲解如何实现由Leon A. Gatys,Alexander S. Ecker和Matthias Bethge提出的 。Neural-Style或者叫Neural-Transfer,可以让你使用一种新的风格将指定的图片进行重构。这个算法使用三张图片,一张输入图片,一张内容图片和一张风格图片,并将输入的图片变得与内容图片相似,且拥有风格图片的优美风格。

    基本原理

    原理很简单:我们定义两个间距,一个用于内容,另一个用于风格D_SD_C测量两张图片内容的不同,而D_S用来测量两张图片风格的不同。然后,我们输入第三张图片,并改变这张图片,使其与内容图片的内容间距和风格图片的风格间距最小化。现在,我们可以导入必要的包,开始图像风格转换。

    下面是一张实现图像风格转换所需包的清单。

    • torch, torch.nn, numpy (使用PyTorch进行风格转换必不可少的包)
    • torch.optim (高效的梯度下降)
    • PIL, PIL.Image, matplotlib.pyplot (加载和展示图片)
    • torchvision.transforms (将PIL图片转换成张量)
    • torchvision.models (训练或加载预训练模型)
    • copy (对模型进行深度拷贝;系统包)

    下一步,我们选择用哪一个设备来运行神经网络,导入内容和风格图片。在大量图片上运行图像风格算法需要很长时间,在GPU上运行可以加速。我们可以使用torch.cuda.is_available()来判断是否有可用的GPU。下一步,我们在整个教程中使用 torch.device.to(device) 方法也被用来将张量或者模型移动到指定设备。

    1. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    加载图片

    现在我们将导入风格和内容图片。原始的PIL图片的值介于0到255之间,但是当转换成torch张量时,它们的值被转换成0到1之间。图片也需要被重设成相同的维度。一个重要的细节是,注意torch库中的神经网络用来训练的张量的值为0到1之间。如果你尝试将0到255的张量图片加载到神经网络,然后激活的特征映射将不能侦测到目标内容和风格。然而,Caffe库中的预训练网络用来训练的张量值为0到255之间的图片。

    注意

    这是一个下载本教程需要用到的图片的链接: picasso.jpg 和 。下载这两张图片并且将它们添加到你当前工作目录中的 images 文件夹。

    1. # desired size of the output image
    2. imsize = 512 if torch.cuda.is_available() else 128 # use small size if no gpu
    3. loader = transforms.Compose([
    4. transforms.Resize(imsize), # scale imported image
    5. transforms.ToTensor()]) # transform it into a torch tensor
    6. def image_loader(image_name):
    7. image = Image.open(image_name)
    8. # fake batch dimension required to fit network's input dimensions
    9. image = loader(image).unsqueeze(0)
    10. return image.to(device, torch.float)
    11. style_img = image_loader("./data/images/neural-style/picasso.jpg")
    12. content_img = image_loader("./data/images/neural-style/dancing.jpg")
    13. assert style_img.size() == content_img.size(), \
    14. "we need to import style and content images of the same size"
    1. unloader = transforms.ToPILImage() # reconvert into PIL image
    2. plt.ion()
    3. def imshow(tensor, title=None):
    4. image = tensor.cpu().clone() # we clone the tensor to not do changes on it
    5. image = image.squeeze(0) # remove the fake batch dimension
    6. image = unloader(image)
    7. plt.imshow(image)
    8. if title is not None:
    9. plt.title(title)
    10. plt.pause(0.001) # pause a bit so that plots are updated
    11. plt.figure()
    12. imshow(style_img, title='Style Image')
    13. plt.figure()
    14. imshow(content_img, title='Content Image')
    • https://pytorch.org/tutorials/_images/sphx_glr_neural_style_tutorial_001.png

    内容损失是一个表示一层内容间距的加权版本。这个方法使用网络中的L层的特征映射F_XL,该网络处理输入X并返回在图片X和内容图片C之间的加权内容间距W_CL*D_C^L(X,C)。该方法必须知道内容图片(F_CL)的特征映射来计算内容间距。我们使用一个以F_CL作为构造参数输入的torch模型来实现这个方法。间距||F_XL-F_CL||^2是两个特征映射集合之间的平均方差,可以使用nn.MSELoss来计算。

    我们将直接添加这个内容损失模型到被用来计算内容间距的卷积层之后。这样每一次输入图片到网络中时,内容损失都会在目标层被计算。而且因为自动求导的缘故,所有的梯度都会被计算。现在,为了使内容损失层透明化,我们必须定义一个forward方法来计算内容损失,同时返回该层的输入。计算的损失作为模型的参数被保存。

    1. class ContentLoss(nn.Module):
    2. def __init__(self, target,):
    3. super(ContentLoss, self).__init__()
    4. # we 'detach' the target content from the tree used
    5. # to dynamically compute the gradient: this is a stated value,
    6. # not a variable. Otherwise the forward method of the criterion
    7. # will throw an error.
    8. self.target = target.detach()
    9. def forward(self, input):
    10. self.loss = F.mse_loss(input, self.target)
    11. return input

    注意

    重要细节:尽管这个模型的名称被命名为 ContentLoss, 它不是一个真实的PyTorch损失方法。如果你想要定义你的内容损失为PyTorch Loss方法,你必须创建一个PyTorch自动求导方法来手动的在backward方法中重计算/实现梯度.

    风格损失

    风格损失模型与内容损失模型的实现方法类似。它要作为一个网络中的透明层,来计算相应层的风格损失。为了计算风格损失,我们需要计算Gram矩阵G_XL。Gram矩阵是将给定矩阵和它的转置矩阵的乘积。在这个应用中,给定的矩阵是L层特征映射F_XL的重塑版本。F_XL被重塑成F̂_XL,一个KxN的矩阵,其中K是L层特征映射的数量,N是任何向量化特征映射F_XL^K的长度。例如,第一行的F̂_XL与第一个向量化的F_XL^1

    最后,Gram矩阵必须通过将每一个元素除以矩阵中所有元素的数量进行标准化。标准化是为了消除拥有很大的N维度F̂_XL在Gram矩阵中产生的很大的值。这些很大的值将在梯度下降的时候,对第一层(在池化层之前)产生很大的影响。风格特征往往在网络中更深的层,所以标准化步骤是很重要的。

    现在风格损失模型看起来和内容损失模型很像。风格间距也用G_XLG_SL之间的均方差来计算。

    1. class StyleLoss(nn.Module):
    2. super(StyleLoss, self).__init__()
    3. self.target = gram_matrix(target_feature).detach()
    4. def forward(self, input):
    5. G = gram_matrix(input)
    6. self.loss = F.mse_loss(G, self.target)
    7. return input

    导入模型

    现在我们需要导入预训练的神经网络。我们将使用19层的VGG网络,就像论文中使用的一样。

    PyTorch的VGG模型实现被分为了两个字Sequential模型:features(包含卷积层和池化层)和classifier(包含全连接层)。我们将使用features模型,因为我们需要每一层卷积层的输出来计算内容和风格损失。在训练的时候有些层会有和评估不一样的行为,所以我们必须用.eval()将网络设置成评估模式。

    1. cnn = models.vgg19(pretrained=True).features.to(device).eval()
    1. cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
    2. # create a module to normalize input image so we can easily put it in a
    3. # nn.Sequential
    4. class Normalization(nn.Module):
    5. def __init__(self, mean, std):
    6. super(Normalization, self).__init__()
    7. # .view the mean and std to make them [C x 1 x 1] so that they can
    8. # directly work with image Tensor of shape [B x C x H x W].
    9. # B is batch size. C is number of channels. H is height and W is width.
    10. self.mean = torch.tensor(mean).view(-1, 1, 1)
    11. self.std = torch.tensor(std).view(-1, 1, 1)
    12. def forward(self, img):
    13. # normalize img
    14. return (img - self.mean) / self.std

    一个Sequential模型包含一个顺序排列的子模型序列。例如,vff19.features包含一个以正确的深度顺序排列的序列(Conv2d, ReLU, MaxPool2d, Conv2d, ReLU…)。我们需要将我们自己的内容损失和风格损失层在感知到卷积层之后立即添加进去。因此,我们必须创建一个新的Sequential模型,并正确的插入内容损失和风格损失模型。

    1. # desired depth layers to compute style/content losses :
    2. content_layers_default = ['conv_4']
    3. style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']
    4. def get_style_model_and_losses(cnn, normalization_mean, normalization_std,
    5. style_img, content_img,
    6. content_layers=content_layers_default,
    7. style_layers=style_layers_default):
    8. cnn = copy.deepcopy(cnn)
    9. # normalization module
    10. normalization = Normalization(normalization_mean, normalization_std).to(device)
    11. # just in order to have an iterable access to or list of content/syle
    12. # losses
    13. content_losses = []
    14. style_losses = []
    15. # assuming that cnn is a nn.Sequential, so we make a new nn.Sequential
    16. # to put in modules that are supposed to be activated sequentially
    17. model = nn.Sequential(normalization)
    18. i = 0 # increment every time we see a conv
    19. for layer in cnn.children():
    20. if isinstance(layer, nn.Conv2d):
    21. i += 1
    22. name = 'conv_{}'.format(i)
    23. elif isinstance(layer, nn.ReLU):
    24. name = 'relu_{}'.format(i)
    25. # The in-place version doesn't play very nicely with the ContentLoss
    26. # and StyleLoss we insert below. So we replace with out-of-place
    27. # ones here.
    28. layer = nn.ReLU(inplace=False)
    29. elif isinstance(layer, nn.MaxPool2d):
    30. name = 'pool_{}'.format(i)
    31. elif isinstance(layer, nn.BatchNorm2d):
    32. name = 'bn_{}'.format(i)
    33. else:
    34. raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))
    35. model.add_module(name, layer)
    36. if name in content_layers:
    37. # add content loss:
    38. target = model(content_img).detach()
    39. content_loss = ContentLoss(target)
    40. model.add_module("content_loss_{}".format(i), content_loss)
    41. content_losses.append(content_loss)
    42. if name in style_layers:
    43. # add style loss:
    44. target_feature = model(style_img).detach()
    45. style_loss = StyleLoss(target_feature)
    46. model.add_module("style_loss_{}".format(i), style_loss)
    47. style_losses.append(style_loss)
    48. for i in range(len(model) - 1, -1, -1):
    49. if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):
    50. break
    51. model = model[:(i + 1)]
    52. return model, style_losses, content_losses

    下一步,我们选择输入图片。你可以使用内容图片的副本或者白噪声。

    https://pytorch.org/tutorials/_images/sphx_glr_neural_style_tutorial_003.png

    和算法的作者Leon Gatys的在 这里建议的一样,我们将使用L-BFGS算法来进行我们的梯度下降。与训练一般网络不同,我们训练输入图片是为了最小化内容/风格损失。我们要创建一个PyTorch的L-BFGS优化器optim.LBFGS,并传入我们的图片到其中,作为张量去优化。

    1. # this line to show that input is a parameter that requires a gradient
    2. optimizer = optim.LBFGS([input_img.requires_grad_()])
    3. return optimizer

    最后,我们必须定义一个方法来展示图像风格转换。对于每一次的网络迭代,都将更新过的输入传入其中并计算损失。我们要运行每一个损失模型的backward方法来计算它们的梯度。优化器需要一个“关闭”方法,它重新估计模型并且返回损失。

    我们还有最后一个问题要解决。神经网络可能会尝试使张量图片的值超过0到1之间来优化输入。我们可以通过在每次网络运行的时候将输入的值矫正到0到1之间来解决这个问题。

    1. def run_style_transfer(cnn, normalization_mean, normalization_std,
    2. content_img, style_img, input_img, num_steps=300,
    3. style_weight=1000000, content_weight=1):
    4. """Run the style transfer."""
    5. print('Building the style transfer model..')
    6. model, style_losses, content_losses = get_style_model_and_losses(cnn,
    7. normalization_mean, normalization_std, style_img, content_img)
    8. optimizer = get_input_optimizer(input_img)
    9. print('Optimizing..')
    10. run = [0]
    11. while run[0] <= num_steps:
    12. def closure():
    13. # correct the values of updated input image
    14. input_img.data.clamp_(0, 1)
    15. optimizer.zero_grad()
    16. model(input_img)
    17. style_score = 0
    18. content_score = 0
    19. for sl in style_losses:
    20. style_score += sl.loss
    21. for cl in content_losses:
    22. content_score += cl.loss
    23. style_score *= style_weight
    24. content_score *= content_weight
    25. loss = style_score + content_score
    26. loss.backward()
    27. run[0] += 1
    28. if run[0] % 50 == 0:
    29. print("run {}:".format(run))
    30. print('Style Loss : {:4f} Content Loss: {:4f}'.format(
    31. style_score.item(), content_score.item()))
    32. print()
    33. return style_score + content_score
    34. optimizer.step(closure)
    35. # a last correction...
    36. input_img.data.clamp_(0, 1)
    37. return input_img

    最后,我们可以运行这个算法。

    1. output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
    2. content_img, style_img, input_img)
    3. plt.figure()
    4. imshow(output, title='Output Image')
    5. # sphinx_gallery_thumbnail_number = 4
    6. plt.ioff()
    7. plt.show()

    输出:

    1. Building the style transfer model..
    2. Optimizing..
    3. run [50]:
    4. Style Loss : 4.169304 Content Loss: 4.235329
    5. run [100]:
    6. Style Loss : 1.145476 Content Loss: 3.039176
    7. run [150]:
    8. Style Loss : 0.716769 Content Loss: 2.663749
    9. run [200]:
    10. Style Loss : 0.476047 Content Loss: 2.500893
    11. run [250]:
    12. Style Loss : 0.347092 Content Loss: 2.410895
    13. run [300]:
    14. Style Loss : 0.263698 Content Loss: 2.358449