pytorch torchvision transform:常用数据预处理方法
部分参考:
PyTorch 学习笔记(三):transforms的二十二个方法
pytorch torchvision transform
1.对PIL.Image进行变换
1.1.组合
transform:class torchvision.transforms.Compose(transforms)
将多个transform
组合起来使用。
transforms
: 由transform
构成的列表. 例子:
transforms.Compose([
transforms.CenterCrop(10),
transforms.ToTensor(),
])
1.2.重塑大小
class torchvision.transforms.Scale(size, interpolation=2)
将输入的PIL.Image
重新改变大小成给定的size
,size
是最小边的边长。举个例子,如果原图的height>width
,那么改变大小后的图片大小是(size*height/width, size)
。
用例:
from torchvision import transforms
from PIL import Image
crop = transforms.Scale(12)
img = Image.open('test.jpg')
print(type(img))
print(img.size)
croped_img=crop(img)
print(type(croped_img))
print(croped_img.size)
<class 'PIL.PngImagePlugin.PngImageFile'>
(10, 10)
<class 'PIL.Image.Image'>
(12, 12)
1.3.中心切割
class torchvision.transforms.CenterCrop(size)
将给定的PIL.Image
进行中心切割,得到给定的size
,size
可以是tuple
,(target_height, target_width)
。size
也可以是一个Integer
,在这种情况下,切出来的图片的形状是正方形。
1.4.随机中心切割
class torchvision.transforms.RandomCrop(size, padding=0)
切割中心点的位置随机选取。size
可以是tuple
也可以是Integer
。
1.5.随机水平翻转
class torchvision.transforms.RandomHorizontalFlip(p=0.5)
随机水平翻转给定的PIL.Image
,概率为0.5。即:一半的概率翻转,一半的概率不翻转。
1.6.随机切割+重塑大小
class torchvision.transforms.RandomSizedCrop(size, interpolation=2)
先将给定的PIL.Image
随机切,然后再resize
成给定的size
大小。
1.7.填充
class torchvision.transforms.Pad(padding, fill=0)
将给定的PIL.Image
的所有边用给定的pad value
填充。
padding
:要填充多少像素fill
:用什么值填充
例子:
from torchvision import transforms
from PIL import Image
padding_img = transforms.Pad(padding=10, fill=0)
img = Image.open('test.jpg')
print(type(img))
print(img.size)
padded_img=padding(img)
print(type(padded_img))
print(padded_img.size)
<class 'PIL.PngImagePlugin.PngImageFile'>
(10, 10)
<class 'PIL.Image.Image'>
(30, 30) #由于上下左右都要填充10个像素,所以填充后的size是(30,30)
1.8.随机垂直翻转
class torchvision.transforms.RandomVerticalFlip(p=0.5)
随机垂直翻转给定的PIL.Image
,概率为0.5。即:一半的概率翻转,一半的概率不翻转。
1.9.随机旋转
class torchvision.transforms.Rotation(degrees, resample=False, expand=False, center=None)
依degrees随机旋转一定角度
degress
:(sequence or float or int) ,若为单个数,如 30,则表示在(-30,+30)之间随机旋转
若为sequence,如(30,60),则表示在30-60度之间随机旋转resample
:重采样方法选择,可选 PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC,默认为最近邻center
:可选为中心旋转还是左上角旋转
2.对Tensor进行变换
2.1.标准化
class torchvision.transforms.Normalize(mean, std)
给定均值:(R,G,B)
方差:(R,G,B)
,将会把Tensor
正则化。即:Normalized_image=(image-mean)/std
。
3.Conversion Transforms
3.1.转换为tensor
class torchvision.transforms.ToTensor
把一个取值范围是[0,255]
的PIL.Image
或者shape
为(H,W,C)
的numpy.ndarray
,转换成形状为[C,H,W]
,取值范围是[0,1.0]
的torch.FloadTensor
data = np.random.randint(0, 255, size=300)
img = data.reshape(10,10,3)
print(img.shape)
img_tensor = transforms.ToTensor()(img) # 转换成tensor
print(img_tensor)
3.2.转换为PIL image
class torchvision.transforms.ToPILImage
将shape
为(C,H,W)
的Tensor
或shape
为(H,W,C)
的numpy.ndarray
转换成PIL.Image
,值不变。
4.通用变换
4.1.class torchvision.transforms.Lambda(lambd)
使用lambd作为转换器。