【PyTorch】torchvision.transforms.ToPILImage 与图像分辨率

  • t o r c h v i s i o n . t r a n s f o r m s . T o P I L I m a g e \rm torchvision.transforms.ToPILImage torchvision.transforms.ToPILImage 的官方描述中,它可以将以 [ c , h , w ] [c,h,w] [c,h,w] 形式组织的 T e n s o r \rm Tensor Tensor 和以 [ h , w , c ] [h,w,c] [h,w,c] 形式组织的 n u m p y   n d a r r a y \rm numpy~ndarray numpy ndarray 转换为 P I L . I m a g e . \rm PIL.Image. PIL.Image.
  • 但平时我们提到的图片分辨率,如 1920 × 1080 1920\times1080 1920×1080,是 w × h w\times h w×h 的形式。通常深度学习中会将图片大小统一,例如常见的 256 × 256 256\times256 256×256,但如果遇到长宽不相同的图片,需要注意 T o P I L I m a g e \rm ToPILImage ToPILImage 函数中的要求与日常使用是有区别的。

在这里插入图片描述

torchvision.transforms.ToPILImage(mode=None)

Converts a torch.*Tensor of shape C x H x W or 
a numpy ndarray of shape H x W x C to a PIL Image 
while preserving the value range.

  • 我们在《交换图片通道》中说过 P I L . I m a g e . o p e n ( ) \rm PIL.Image.open() PIL.Image.open() 函数加载图片是以 R G B \rm RGB RGB 通道加载的,并且图片尺寸为 w × h w\times h w×h,展示如下:
# In[]
from PIL import Image

im = Image.open(r'./content.jpg')
print(im.mode)
print(im.size)

'''
RGB
(960, 540)
'''
  • 该图片如下所示,很显然是 w × h w\times h w×h
    在这里插入图片描述
  • 在进行 t o r c h v i s i o n . t r a n s f o r m s . T o T e n s o r \rm torchvision.transforms.ToTensor torchvision.transforms.ToTensor 转换后,会将图片组织成我们开篇所说的 [ c , h , w ] [c,h,w] [c,h,w] 张量形式,代码如下:
# In[]
import torchvision
tensor = torchvision.transforms.ToTensor()(im)
print(tensor.shape)

'''
torch.Size([3, 540, 960])
'''

  • 最后是关于 m a t p l o t l i b . p y p l o t . i m s h o w ( ) \rm matplotlib.pyplot.imshow() matplotlib.pyplot.imshow() 方法可视化时对于图片的要求,对于使用 P I L . I m a g e . o p e n ( ) \rm PIL.Image.open() PIL.Image.open() 方法读入的 I m a g e \rm Image Image 类型, i m s h o w \rm imshow imshow 是能够直接进行显示的:
# In[]
import matplotlib.pyplot as plt
plt.imshow(im)

在这里插入图片描述

  • 但对于转换为 [ c , h , w ] [c,h,w] [c,h,w] 形式的张量,则需要对其进行维度的交换,否则会报如下错误:
TypeError: Invalid shape (3, 540, 960) for image data
  • 正确的可视化代码如下:
# In[]
tensor = tensor.permute(1,2,0)
plt.imshow(tensor)
  • 其中 p e r m u t e ( ) \rm permute() permute() 函数能够实现张量维度的交换,将 [ c , h , w ] [c,h,w] [c,h,w] 重新组织为 [ h , w , c ] [h,w,c] [h,w,c] 形式,用于可视化展示。另一种方式就是使用开篇时介绍的 T o P I L I m a g e \rm ToPILImage ToPILImage 方法对张量进行变换:
# In[]
tensor = torchvision.transforms.ToPILImage()(tensor)
plt.imshow(tensor)
  • 上述两种方法均能成功可视化张量形式的图片。
下面是一个简单的超分辨率图像重建的Pytorch代码: ``` import torch import torch.nn as nn import torchvision.transforms as transforms from torch.autograd import Variable # 定义超分辨率模型 class SuperResolution(nn.Module): def __init__(self): super(SuperResolution, self).__init__() # 定义卷积层 self.conv1 = nn.Conv2d(3, 64, kernel_size=5, padding=2) self.conv2 = nn.Conv2d(64, 64, kernel_size=3, padding=1) self.conv3 = nn.Conv2d(64, 32, kernel_size=3, padding=1) self.conv4 = nn.Conv2d(32, 3, kernel_size=5, padding=2) # 定义激活函数 self.relu = nn.ReLU() def forward(self, x): x = self.relu(self.conv1(x)) x = self.relu(self.conv2(x)) x = self.relu(self.conv3(x)) x = self.conv4(x) return x # 加载图像数据 img = Image.open('input.png') # 定义图像变换 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) ]) # 将图像转换为变量 input_img = Variable(transform(img).unsqueeze(0)) # 创建超分辨率模型 model = SuperResolution() # 加载预训练模型 model.load_state_dict(torch.load('superresolution.pth')) # 将模型设置为评估模式 model.eval() # 使用模型进行图像重建 output_img = model(input_img) # 将输出图像保存为png文件 output_img = output_img.data.squeeze().cpu().clamp(0, 1) transforms.ToPILImage()(output_img).save('output.png') ``` 在这个代码中,我们定义了一个超分辨率模型 `SuperResolution`,它包含了四个卷积层和一个ReLU激活函数。我们还定义了一个图像变换 `transform`,它将图像转换为张量并进行归一化。我们加载了一个预训练模型,并使用它对输入图像进行重建。最后,我们将输出图像保存为png文件。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值