网络编程
位置:首页>> 网络编程>> Python编程>> Pytorch如何把Tensor转化成图像可视化

Pytorch如何把Tensor转化成图像可视化

作者:乱觉先森  发布时间:2021-11-03 20:20:22 

标签:Pytorch,Tensor,图像,可视化

Pytorch把Tensor转化成图像可视化

在调试程序的时候经常想把tensor可视化成来看看,可以这样操作:

from torchvision import transforms
unloader = transforms.ToPILImage()
image = original_tensor.cpu().clone()  # clone the tensor
image = image.squeeze(0)  # remove the fake batch dimension
image = unloader(image)
image.save('example.jpg')

pytorch标准化的Tensor转图像问题

常常在工作之中遇到将dataloader中出来的tensor成image,numpy格式的数据,然后可以可视化出来

但是这种tensor往往经过了channel变换(RGB2BGR),以及归一化(减均值除方差),

然后维度的顺序也发生变化(HWC变成CHW)。为了可视化这种变化比较多的数据,

在tensor转numpy之前需要对tensor做一些处理

如下是一个简单的函数,可以可视化tensor,下次直接拿来用就行

def tensor2im(input_image, imtype=np.uint8):
   """"
   Parameters:
       input_image (tensor) --  输入的tensor,维度为CHW,注意这里没有batch size的维度
       imtype (type)        --  转换后的numpy的数据类型
   """
   mean = [0.485, 0.456, 0.406] # dataLoader中设置的mean参数,需要从dataloader中拷贝过来
   std = [0.229, 0.224, 0.225]  # dataLoader中设置的std参数,需要从dataloader中拷贝过来
   if not isinstance(input_image, np.ndarray):
       if isinstance(input_image, torch.Tensor): # 如果传入的图片类型为torch.Tensor,则读取其数据进行下面的处理
           image_tensor = input_image.data
       else:
           return input_image
       image_numpy = image_tensor.cpu().float().numpy()  # convert it into a numpy array
       if image_numpy.shape[0] == 1:  # grayscale to RGB
           image_numpy = np.tile(image_numpy, (3, 1, 1))
       for i in range(len(mean)): # 反标准化,乘以方差,加上均值
           image_numpy[i] = image_numpy[i] * std[i] + mean[i]
       image_numpy = image_numpy * 255 #反ToTensor(),从[0,1]转为[0,255]
       image_numpy = np.transpose(image_numpy, (1, 2, 0))  # 从(channels, height, width)变为(height, width, channels)
   else:  # 如果传入的是numpy数组,则不做处理
       image_numpy = input_image
   return image_numpy.astype(imtype)

来源:https://blog.csdn.net/weixin_40520963/article/details/105783025

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com