将tensor张量转换成图片格式并保存

Posted UQI-LIUWJ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将tensor张量转换成图片格式并保存相关的知识,希望对你有一定的参考价值。

这是一个工具包,功能:反向操作transforms.Normalize和transforms.ToTensor函数,将tensor格式的图片转换成.jpg、.png格式的图片

import torch
import numpy as np
from PIL import Image
import torchvision.transforms as transforms

def transform_convert(img_tensor, transform):
    """
    param img_tensor: tensor
    param transforms: torchvision.transforms
    """
    if 'Normalize' in str(transform):
        normal_transform = list(filter(lambda x: isinstance(x, transforms.Normalize), transform.transforms))
        mean = torch.tensor(normal_transform[0].mean, dtype=img_tensor.dtype, device=img_tensor.device)
        std = torch.tensor(normal_transform[0].std, dtype=img_tensor.dtype, device=img_tensor.device)
        img_tensor.mul_(std[:,None,None]).add_(mean[:,None,None])
        
    img_tensor = img_tensor.transpose(0,2).transpose(0,1)  # C x H x W  ---> H x W x C
    
    if 'ToTensor' in str(transform) or img_tensor.max() < 1:
        img_tensor = img_tensor.detach().numpy()*255
    
    if isinstance(img_tensor, torch.Tensor):
    	img_tensor = img_tensor.numpy()
    
    if img_tensor.shape[2] == 3:
        img = Image.fromarray(img_tensor.astype('uint8')).convert('RGB')
    elif img_tensor.shape[2] == 1:
        img = Image.fromarray(img_tensor.astype('uint8')).squeeze()
    else:
        raise Exception("Invalid img shape, expected 1 or 3 in axis 2, but got {}!".format(img_tensor.shape[2]))
        
    return img

代码示例

import matplotlib.pyplot as plt
img = Image.open('./lena.jpg')
ToTensor_transform = transforms.Compose([transforms.ToTensor()])
img_tensor = ToTensor_transform(img)
img = transform_convert(img_tensor, ToTensor_transform)
plt.imshow(img)
plt.savefig('./lenaa.png')

 

以上是关于将tensor张量转换成图片格式并保存的主要内容,如果未能解决你的问题,请参考以下文章

如何将csv文件转换成excel文件呢?

php 将base64转换成图片并保存 阿星小栈

如何将PyTorch张量转换为Numpy ndarray

Pytorch深度学习实战3-2:什么是张量?Tensor的创建与索引

PyTorch教程-7:PyTorch中保存与加载tensor和模型详解

怎样将图片格式转换成PDF格式?