Transforms的结构及用法
transforms指的是transforms.py这个文件,像一个工具箱,工具箱中有很多的工具。向transforms中输入一个图片,就能输出我们想要的结果。
首先从torchvision这个工具包中导入transforms
from torchvision import transforms
transforms中有Compose(图片经过中心裁剪后送到ToTensor方法中)方法和ToTensor方法(将图片格式转化为Tensor),还有Normalize(正则化)等等。
ToTensor类
Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. This transform does not support torchscript.
ToTensor类将一个PIL或者numpy格式的图片转换为tensor格式。
from PIL import Image
from torchvision import transforms
img_path = "data/train/ants_image/0013035.jpg"
img = Image.open(img_path)
print(img)
输出:
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=768x512 at 0x1EF1648DE50>
可以看到,图片为PIL格式,我们可以用totensor将其转为tensor格式。
注意ToTensor是一个类,我们需要创建它的实例化对象
tensor_trans = transforms.ToTensor()
ToTensor类中有call方法,这个方法类似于C++中重载()运算符,可以直接通过()进行调用
def __call__(self, pic):
"""
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
return F.to_tensor(pic)
调用call来转换图片类型
tensor_img = tensor_trans(img)
print(tensor_img)
输出:
tensor([[[0.3137, 0.3137, 0.3137, ..., 0.3176, 0.3098, 0.2980],
[0.3176, 0.3176, 0.3176, ..., 0.3176, 0.3098, 0.2980],
[0.3216, 0.3216, 0.3216, ..., 0.3137, 0.3098, 0.3020],
...,
[0.3412, 0.3412, 0.3373, ..., 0.1725, 0.3725, 0.3529],
[0.3412, 0.3412, 0.3373, ..., 0.3294, 0.3529, 0.3294],
[0.3412, 0.3412, 0.3373, ..., 0.3098, 0.3059, 0.3294]],
[[0.5922, 0.5922, 0.5922, ..., 0.5961, 0.5882, 0.5765],
[0.5961, 0.5961, 0.5961, ..., 0.5961, 0.5882, 0.5765],
[0.6000, 0.6000, 0.6000, ..., 0.5922, 0.5882, 0.5804],
...,
[0.6275, 0.6275, 0.6235, ..., 0.3608, 0.6196, 0.6157],
[0.6275, 0.6275, 0.6235, ..., 0.5765, 0.6275, 0.5961],
[0.6275, 0.6275, 0.6235, ..., 0.6275, 0.6235, 0.6314]],
[[0.9137, 0.9137, 0.9137, ..., 0.9176, 0.9098, 0.8980],
[0.9176, 0.9176, 0.9176, ..., 0.9176, 0.9098, 0.8980],
[0.9216, 0.9216, 0.9216, ..., 0.9137, 0.9098, 0.9020],
...,
[0.9294, 0.9294, 0.9255, ..., 0.5529, 0.9216, 0.8941],
[0.9294, 0.9294, 0.9255, ..., 0.8863, 1.0000, 0.9137],
[0.9294, 0.9294, 0.9255, ..., 0.9490, 0.9804, 0.9137]]])
可以看到转为了tensor数据类型。
由于tensor是一个类,因此对transform工具包更确切的表述应该是这样
为什么我们需要tensor数据类型
tensor数据类型包装了反向神经网络需要的一些理论基础的参数,所以在神经网络中我们需要把图片转换为tensor型。