哔哩大学的PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】
的P12讲讲述了transforms中Normalize(归一化)的使用。
Normalize
Normalize的注释:
class Normalize(torch.nn.Module):
"""Normalize a tensor image with mean and standard deviation.
This transform does not support PIL Image.
用均值和标准差对张量图像进行归一化。这个变换不支持PIL Image。
Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n``
channels, this transform will normalize each channel of the input
``torch.*Tensor`` i.e.,
``output[channel] = (input[channel] - mean[channel]) / std[channel]``
.. note::
This transform acts out of place, i.e., it does not mutate the input tensor.
Args:
mean (sequence): Sequence of means for each channel.
std (sequence): Sequence of standard deviations for each channel.
inplace(bool,optional): Bool to make this operation in-place.
"""
def __init__(self, mean, std, inplace=False):
super().__init__()
self.mean = mean
self.std = std
self.inplace = inplace
def forward(self, tensor: Tensor) -> Tensor:
"""
Args:
tensor (Tensor): Tensor image to be normalized.
Returns:
Tensor: Normalized Tensor image.
"""
return F.normalize(tensor, self.mean, self.std, self.inplace)
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
接上一个的代码后面加上:
trans_norm = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
#需要输入均值和标准差,因为我们的图片不是rgb三层的,提供三声道标准差
img_norm = trans_norm(img_tensor)
#上边做好的image的tensor数据类型
#output[channel] = (input[channel] - mean[channel]) / std[channel]
print(img_norm[0][0][0])
writer.add_image("Normalize",img_norm)
writer.close()
运行结果为:
经过归一化后的图片(上边为归一化后,下边为原图):