关于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()