风格迁移+pytorch+python实现

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

风格迁移简介

平台介绍

相关软件

pytorch简介
python简介
conda简介

相关硬件

Tesla显卡简介
ubuntu简介
Linux简介

相关算法

网络架构

VGG19网络模型

算法

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
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芷汀若静

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值