pytorch 获取神经网络中间图像Variable to img

本文介绍如何在PyTorch中将Variable类型的数据转化为图片输出,通过定义一个名为tensor_to_PIL的函数实现这一过程。该函数首先将Variable类型的张量转化为普通的tensor,然后逐个保存为图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 pytorch中使用Variable 转化为图片输出,

 

import os
import torch.nn as nn
import torch.optim as optim
from base_networks import *
from torchvision.transforms import *

def tensor_to_PIL(variable):                           #新加函数将Variable转换为图片
    image = variable.cpu().clone()
    image=image.data      #Variable张量转化为tensor
    for i in range(len(image)):
        save_file="./record/process_img/up4/"+str(i)+".jpg"
        temp_image=image[i].clone()
        temp_image = temp_image.unsqueeze(0)                  #压缩数组维数,去掉axis=''的维,0代表None 去掉一维的
        temp_image = transforms.ToPILImage()(temp_image.float()).convert("L")  #ToPILImage 需要一个三维的图像
        temp_image.save(save_file,quality=95)

 

### 使用卷积神经网络(CNN)进行Python图像风格迁移 #### CNN在图像风格转换中的作用 卷积神经网络不仅擅长于传统的图像分类任务,还能够用于更复杂的操作,比如艺术风格转移。这种技术允许一张图片的内容与另一张图片的艺术风格相结合[^1]。 #### 图像风格迁移的基本流程 为了完成这一目标,通常会采用预训练好的CNN模型作为特征提取器。该过程涉及定义两个损失函数:一个是用来衡量内容相似度的内容损失;另一个则是捕捉风格差异的风格损失。通过优化这两者之间的平衡来调整输入图像直至获得满意的输出效果[^3]。 #### 实现步骤概述 以下是利用PyTorch框架实现简单版图像风格迁移的一个简化版本: ```python import torch from torchvision import models, transforms from PIL import Image import matplotlib.pyplot as plt device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 加载VGG19模型并移除全连接层部分 cnn_normalization_mean = [0.485, 0.456, 0.406] cnn_normalization_std = [0.229, 0.224, 0.225] transform = transforms.Compose([ transforms.Resize(512), transforms.ToTensor(), ]) def image_loader(image_name): image = Image.open(image_name) image = transform(image).unsqueeze(0) return image.to(device, torch.float) content_img = image_loader("path_to_content_image.jpg") style_img = image_loader("path_to_style_image.jpg") class ContentLoss(nn.Module): def __init__(self, target, ): super(ContentLoss, self).__init__() # we 'detach' the target content from the tree used # to dynamically compute the gradient: this is a stated value, # not a variable. Otherwise the forward method of the criterion # will throw an error. self.target = target.detach() def forward(self, input): self.loss = F.mse_loss(input, self.target) return input class StyleLoss(nn.Module): def __init__(self, target_feature): super(StyleLoss, self).__init__() self.target = gram_matrix(target_feature).detach() def forward(self, input): G = gram_matrix(input) self.loss = F.mse_loss(G, self.target) return input model = models.vgg19(pretrained=True).features.to(device).eval() ``` 这段代码展示了如何加载必要的库以及准备数据集,并构建了一个基于VGG19架构的基础结构来进行风格迁移实验。需要注意的是这里只给出了部分内容和样式损失类的定义,完整的程序还需要加入更多细节如Gram矩阵计算、不同层次的选择等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值