风格迁移简介
平台介绍
相关软件
相关硬件
相关算法
网络架构
算法
CNN卷积神经网络
Gram矩阵,这个是风格损失的主要算法。
LBFGs算法(梯度下降方法)
代码
导入所需包及设备
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
加载图像
导入图像后,需要将图像大小调整为相同尺寸同时将图像的矩阵转换成tensor(这个相当于是numpy,二者的区别就在于tensor可以在GPU上运行而numpy只能在CPU上运行)。最后可以测试一下二者的size。
完成统一后还需要做向PIL image的转变,这个转变就是将输出的结果去掉通道这一项参数。
# desired size of the output image
imsize = 512 if torch.cuda.is_available() else 128 # use small size if no gpu
loader = transforms.Compose([
transforms.Resize([imsize,imsize]), # scale imported image
transforms.ToTensor()]) # transform it into a torch tensor
def image_loader(image_name):
image = Image.open(image_name)
# fake batch dimension required to fit network's input dimensions
image = loader(image).unsqueeze(0)
return image.to(device, torch.float)
style_img = image_loader("image/picasso.jpg")
content_img = image_loader("image/dancing.jpg")
print(style_img.size())
print(content_img.size())
unloader = transforms.ToPILImage() # reconvert into PIL image
plt.ion()
def imshow(tensor, title=None):
image = tensor.cpu().clone() # we clone the tensor to not do changes on it
image = image.squeeze(0) # remove the fake batch dimension
image = unloader(image)
plt.imshow(image)
if title is not None:
plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated
plt.figure()
imshow(style_img, title='Style Image')
plt.figure()
imshow(content_img

本文详细介绍了如何使用PyTorch进行风格迁移,涉及内容包括风格迁移的基本原理、相关软件如PyTorch和Python的介绍、硬件如Tesla显卡的简介,以及算法如VGG19网络模型、CNN和Gram矩阵等。通过构建内容损失和风格损失函数,利用梯度下降方法进行图像优化。最后,通过实际代码展示了如何训练模型并将风格应用到输入图像上,生成具有特定风格的艺术作品。
最低0.47元/天 解锁文章
664

被折叠的 条评论
为什么被折叠?



