Pytorch学习笔记--Transforms的使用(totensor,normalize)

先导入相关库:

from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from  torchvision import transforms
from py.Transforms import write

再导入图片:

img_path="D:/Pychram_Project/Learn_Pytorch/Projects/dataset/train/ants/69639610_95e0de17aa.jpg"
img=Image.open(img_path)
#print(img)

totensor的使用,之前已经提过这里不再赘述。

#ToTensor的使用
trans_totensor = transforms.ToTensor() #创建对象
img_tensor=trans_totensor(img)   #转换成imgtensor类型
#print(type(img_tensor))
write.add_image("Totensor",img_tensor)

 Normalize的使用,归一化:注释说明如下

"""Normalize a tensor image with mean and standard deviation.
   This transform does not support 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.

   """

公式为:output[channel] = (input[channel] - mean[channel]) / std[channel]

print(img_tensor[0][0][0])   #归一化之前的
trans_norm=transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
#公式:output[channel] = (input[channel] - mean[channel]) / std[channel]
#在这里(input-0.5)/0.5=2*input-1
img_norm=trans_norm(img_tensor)   #参数只支持image类型
print(img_norm[0][0][0])   #归一化之后的
write.add_image("nomralize",img_norm)
write.close()

在这里传入的根据参数,output=(input-0.5)/0.5=2*input-1   在上文这里归一化之前print输出为tensor(0.9294),归一化之后输出为tensor(0.8588),正好符合公式。

归一化这里参数只支持image类型。

查看归一化前后图片对比:

常见的transform:

 

学习内容来自b站小土堆 ,这里只作为学习笔记。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值