Pytorch torchvision.transforms 数据标准化(tensor 和 numpy 的相互转换和可视化)

关于pytorch torchvision.transforms 数据标准化的一些使用

转自:https://blog.csdn.net/u014484247/article/details/79997357

这里在做一点补充,对于把数据转换回去,只要把公式带回去就能得到结果

对应的,关键公式如下:

image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0

先进行把对应的通道 转换回去,然后乘上方差,再加上均值,再把范围回到0-255

对应的参考代码如下

# Converts a Tensor into a Numpy array
# |imtype|: the desired type of the converted numpy array
def tensor2im(image_tensor, imtype=np.uint8):
    image_numpys = []
    for i in xrange(image_tensor.shape[0]):
        image_numpy = image_tensor[i].cpu().float().numpy()
        image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0
        image_numpy.astype(imtype)
        image_numpys.append(image_numpy)
    return image_numpys

关于cv2,matplotlib,PIL比较及与Tensor的转换

https://blog.csdn.net/m0_37673307/article/details/81271155

 

在此进行扩充,其实我们平时,很多时候都需要显示一下图片,查看当前的操作或者思路是否正确,那么就需要对Tensor进行转化和显示,保证正确。

#现在进行扩展:
#即如果对应的归一化和去均值方法都是根据设定好的值得话,那么recover的形式也是一样的

def convert_image_np(inp):
    """Convert a Tensor to numpy image."""
    inp = inp.numpy().transpose((1, 2, 0))
    # mean = np.array([0.485, 0.456, 0.406])
    # std = np.array([0.229, 0.224, 0.225])
    mean = [0.5071, 0.4867, 0.4408]
    std = [0.2675, 0.2565, 0.2761]
    inp = std * inp + mean
    inp = np.clip(inp, 0, 1)
    return inp

def debug_show(input_tensor):
    plt.imshow(convert_image_np(input_tensor[0].detach()),vmin=0,vmax=1)
    plt.show()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值