• 使用PyTorch搭建VGG模型进行图像风格迁移实战(附源码和数据集)


    需要源码和图片集请点赞关注收藏后评论区留言或者私信~~~

    一、VGG模型

    VGG模型是科学家们提出的图像分类模型,这一模型采用了简单粗暴的堆砌3×3卷积层的方式构建模型,并花费大量的时间逐层训练,最终在ImageNet图像分类比赛中获得了亚军,这一模型的优点是结构简单,容易理解,便于利用到其他任务当中

    VGG-19网络的卷积部分由5哥卷积块构成,每个卷积块中有多个卷积层,结尾处有一个池化层 结构如下图所示

     二、图像风格迁移介绍

    图像风格迁移是指将一张风格图的风格与另一张内容图的内容想结合并生成新的图像,利用预训练的VGG网络提取图像特征,并基于图像特征组合出了两种特征度量,一种用于表示图像的内容,另一种用于表示图像的风格,它们将这两种特征度量加权组合,通过最优化的方式生成新的图像,使新的图像同时具有一幅图像的风格和另一幅图像的内容 

    风格图如下 是梵高著名的画作《星空》

     内容图如下 选自意大利的一个街道(可以看出是个阳光晴朗的日子,非常的暖色调)

     让我们来看看进行图像风格迁移,即把梵高的风格加到这幅图的内容上会是什么效果!

    哈哈 显示是有一点抽象和模糊的感觉,但这也正是星空的风格!

     

    三、内容损失函数 

    内容损失函数用于衡量两幅图像之间的内容差异大小,通过两幅图片由VGG网络某一卷积层提取的特征图来表示

    四、风格损失函数

    风格损失函数用于衡量两幅图像之间的风格差异大小,首先需要通过计算特征图的Gram矩阵得到图像风格的数学表示

    五、主程序代码的实现

    程序分为以下几部分

    1:图像预处理  接收一个PIL图片,改变图片大小,转换为张量,进行标准化然后乘以255

    2:参数定义

    3:模型初始化  

    4:运行主函数

    5:利用VGG网络建立损失函数

    6:优化

    7:可视化

    最后  部分源码如下

    1. import torch
    2. import torch.nn as nn
    3. import torchvision
    4. import torchvision.transforms as transforms
    5. from PIL import Image
    6. def g = input.size()
    7. features = input.view(a * b, c * d)
    8. G = torch.mm(features, features.t())
    9. return G
    10. class ContentLoss(nn.Module):
    11. def __init__(self, target):
    12. super(ContentLoss, self).__init__()
    13. self.target = target.detach()
    14. def forward(self, input):
    15. self.loss = torch.sum((input-self.target) ** 2) / 2.0
    16. return input
    17. class Style
    18. def __init__(self, target_feature):
    19. super(StyleLoss, self).__init__()
    20. self.target = gram_matrix(target_feature).detach()
    21. def forward(self, input):
    22. a, b, c, d = input.size()
    23. G = gram_matrix(input)
    24. self.loss = torch.sum((G-self.target) ** 2) / (4.0 * b * b * c * d)
    25. return input
    26. class ImagCder:
    27. def __init__(self, image_size, device):
    28. self.device = device
    29. self.preproc = transforms.Compose([
    30. transforms.Resize(image_size), # 改变图像大小
    31. transforms.ToTensor(),
    32. transforms.Normalize(mean=[0.485, 0.456, 0.406], # 标准化
    33. std=[1, 1, 1]),
    34. transforms.Lambda(lambda x: x.mul_(255))
    35. ])
    36. self.postproc = transforms.Compose([
    37. transforms.Lambda(lambda x: x.mul_(1./255)),
    38. transforms.Normalize(mean=[-0.485, -0.456, -0.406], std=[1,1,1])
    39. ])
    40. self.to_image = transforms.ToPILImage()
    41. def encode(self, image_path):
    42. image = Image.open(image_path)
    43. image = self.preproc(image)
    44. image = image.unsqueeze(0)
    45. return image.to(self.device, torch.float)
    46. def decode(self, image):
    47. image = image.cpu().clone()
    48. image = image.squeeze()
    49. image = self.postproc(image)
    50. image = image.clamp(0, 1)
    51. return self.to_image(image)
    52. content_layers = ['conv_4_2'] # 内容损失函数使用的卷积层
    53. style_layers = ['conv_1_1', 'conv2_1', 'conv_3_1', 'conv_4_1', 'conv5_1'] # 风格损失函数使用的卷积层
    54. content_weights = [1] # 内容损失函数的权重
    55. style_weights = [1e3, 1e3, 1e3, 1e3, 1e3] # 风格损失函数的权重
    56. num_steps=200 # 最优化的步数
    57. class Mo:
    58. def __init__(self, device, image_size):
    59. cnn = torchvision.models.vgg19(weights=True).features.to(device).eval()
    60. self.cnn = deepcopy(cnn) # 获取预训练的VGG19卷积神经网络
    61. self.device = device
    62. self.content_losses = []
    63. self.style_losses = []
    64. self.image_proc = ImageCoder(image_size, device)
    65. def run(self, content_image_path, style_image_path):
    66. content_image = self.image_proc.encode(content_image_path)
    67. style_image = self.image_proc.encode(style_image_path)
    68. self._build(content_image, style_image) # 建立损失函数
    69. output_image = self._transfer(content_image) # 进行最优化
    70. return self.image_proc.decode(output_image)
    71. def _bd(self, content_image, style_image):
    72. self.model = nn.Sequential()
    73. block_idx = 1
    74. conv_idx = 1
    75. # 逐层遍历VGG19,取用需要的卷积层
    76. for layer in self.cnn.children():
    77. # 识别该层类型并进行编号命名
    78. if= 'conv_{}_{}'.format(block_idx, conv_idx)
    79. conv_idx += 1
    80. elif isinstance(layer, nn.ReLU):
    81. name = 'relu_{}_{}'.format(block_idx, conv_idx)
    82. layer = nn.ReLU(inplace=False)
    83. elif isinstance(layer, nn.MaxPool2d):
    84. name = 'pool_{}'.format(block_idx)
    85. block_idx += 1
    86. conv_idx = 1
    87. elif isinstance(layer, nn.BatchNorm2d):
    88. name = 'bn_{}'.format(block_idx)
    89. else:
    90. raise Exception("invalid layer")
    91. self.model.add_module(name, layer)
    92. # 添加内容损失函数
    93. if name in content_layers:
    94. target = self.model(content_image).detach()
    95. content_loss = ContentLoss(target)
    96. self.model.add_module("content_loss_{}_{}".format(block_idx, conv_idx), content_loss)
    97. self.content_losses.append(content_loss)
    98. # 添加风格损失函数
    99. if name in style_layers:
    100. target_feature = self.model(style_image).detach()
    101. style_l StyleLoss(target_feature)
    102. self.model.add_module("style_loss_{}_{}".format(block_idx, conv_idx), style_loss)
    103. self.style_losses.append(style_loss)
    104. # 留下有用的部分
    105. i = 0
    106. for i in range(len(self.model) - 1, -1, -1):
    107. if isinstance(self.model[i], ContentLoss) or isinstance(self.model[i], StyleLoss):
    108. break
    109. self.model = self.model[:(i + 1)]
    110. def _transfer(self, content_image):
    111. output_image = content_image.clone()
    112. random_image = torch.randn(content_image.data.size(), device=self.device)
    113. output_image = 0.4 * output_image + 0.6 * random_image
    114. optimizer = torch.optim.LBFGS([output_image.requires_grad_()])
    115. print('Optimizing..')
    116. run = [0]
    117. while run[0] <= num_steps:
    118. def closure():
    119. optimizer.zero_grad()
    120. self.model(output_image)
    121. style_score = 0
    122. content_score = 0
    123. for sl, sw in zip(self.style_losses, style_weights):
    124. style_score += sl.loss * sw
    125. for cl, cw in zip(self.content_losses, content_weights):
    126. content_score += cl.loss * cw
    127. loss = style_score + content_score
    128. loss.backward()
    129. run[0] += 1
    130. if run[0] % 50 == 0:
    131. print("iteration {}: Loss: {:4f} Style Loss: {:4f} Content Loss: {:4f}"
    132. .format(run, loss.item(), style_score.item(), content_score.item()))
    133. return loss
    134. optimizer.step(closure)
    135. return output_image
    136. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    137. image_size = 256
    138. model = Model(device, image_size)
    139. style_image_path =
    140. content_image_path =
    141. out_image = del.run(content_image_path, style_image_path)
    142. plt.imshow(out_image)
    143. plt.show()

     创作不易 觉得有帮助请点赞关注收藏~~~

  • 相关阅读:
    亚马逊鲲鹏测评系统:全自动注册下单及留评
    使用STM32控制TMC5160驱动步进电机
    真卷,隔壁半夜房间还亮着灯,原来在偷偷学习分布式服务框架
    Azure DevOps Server 设置项目管理用户,用户组
    【python】任务调度编排工具 schedule | python定时任务工具
    【DevPress】V2.1.0版本发布,优化博文详情页
    极智Paper | 单级特征检测网络 YOLOF
    数据结构【栈】
    优思学院|韦伯的组织理论在今天还有意义吗?
    jxTMS设计思想之流程追溯
  • 原文地址:https://blog.csdn.net/jiebaoshayebuhui/article/details/127809992