torchvision中的transforms主要是用于图片的变化
torchvision中的transforms主要是用于图片的变化
transforms是工具箱,里面有resize,totensor,compose等工具模板,利用模板创建自己需要的工具,然后输入图片得到想要的格式。
1.transforms结构及用法
from torchvision import transforms
查找快捷键
structure
class Compose:
“”“Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
Example:
>>> transforms.Compose([
>>> transforms.CenterCrop(10),
>>> transforms.PILToTensor(),
>>> transforms.ConvertImageDtype(torch.float),
>>> ])”“”
CenterCrop中心裁剪,---》PILToTensor
class ToTensor: """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. This transform does not support torchscript.
正则化
class Normalize(torch.nn.Module): """Normalize a tensor image with mean and standard deviation.
class Resize(torch.nn.Module): """Resize the input image to the given size.
""""python的用法 ——》Tensor数据类型
通过transform.ToTensor去解决两个问题
1.transform如何使用
2.为什么需要Tensor数据类型
"""
class ToTensor: """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. This transform does not support torchscript.
实例:用python内置库Image打开图片,将PIL格式转换为Tensor格式
img_path = "dataset/train/bees/2822388965_f6dca2a275.jpg"
img = Image.open(img_path)
print(img)
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x318 at 0x1E540097640>
新建transforms.ToTensor()对象
ctrl+p(parameter)提示参数
tensor_trans = transforms.ToTensor()
tensor_img = tensor_trans(img)
print(type(tensor_img))
<class 'torch.Tensor'>