一个简单的使用torch.nn.Upsample的例子
import torch
import torch.nn as nn
output_shape = [64,48]
up = nn.Upsample(size=output_shape, mode='bilinear', align_corners=True)
#up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
input = torch.rand(32,17,32,24)
output = up(input)
print(output.shape)
使用Image类读取图片,转为numpy数组,HWC转为CHW,然后转为[1,C,H,W],再转为Tensor,数据类型转为float。利用upsample进行上采样。再按相反的顺序,最终转为Image类的格式,显示出来。
import torch
import torch.nn as nn
from PIL import Image
import numpy as np
m = nn.Upsample(scale_factor=2, mode='nearest')
up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
file = 'lena.png'
img = Image.open(file)
# img.show()
im_array = np.array(img).transpose((2,0,1))[np.newaxis, :]
im_array = torch.from_numpy(im_array).type(torch.FloatTensor)
img_up = up(im_array)
img = img_up.numpy().squeeze().transpose((1,2,0)).astype(np.int8)
img = Image.fromarray(img, 'RGB')
img.show()