pytorch的nn.Upsample,查看上采样效果

本文通过两个实例展示了如何使用PyTorch中的nn.Upsample模块进行图像上采样,包括设置输出形状和缩放因子,以及从图片文件读取数据到转换为Tensor并进行上采样的完整流程。

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

一个简单的使用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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值