PyTorch图像预处理

参考:https://pytorch-cn.readthedocs.io/zh/latest/torchvision/torchvision-transform/

1.pytorch torchvision transform

对PIL.Image进行变换: 

2. class torchvision.transforms.Compose(transforms) :将多个transform组合起来使用

transforms.Compose([
     transforms.CenterCrop(10),
     transforms.ToTensor(),
 ])

3. class torchvision.transforms.CenterCrop(size) 

将指定的PIL.Image进行中心切割,得到给定的size,size可以是tuple:(target_height, target_width)。

size也可以是一个 Integer,这种情况下,切出来的图片形状是正方形。

4. class torchvision.transforms.RandomCrop(size, padding=0)

切割中心点的位置随机选取。size可以是tuple也可以是Integer。

5.class torchvision.transforms.RandomHorizontalFlip

随机水平翻转给定的PIL.Image,概率为0.5,一半的概率翻转,一半的概率不翻转。

6. class torchvision.transforms.RandomSizedCrop(size, interpolation=2)

先将PIL.Image随机切,然后再resize成给定的size大小。

7. class torchvison.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)

#output:
<class 'PIL.PngImagePlugin.PngImageFile'>
(10, 10)
<class 'PIL.Image.Image'>
(30, 30) #由于上下左右都要填充10个像素,所以填充后的size是(30,30)

8. 对Tensor进行变换。

class torchvision.transforms.Normalize(mean, std)

给定均值和方差,将会把Tensor正则化。即Normalized_image=(image-mean)/std。

9.Conversion Transforms

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)

10. class torchvision.transforms.ToPILImage

将shape为(C,H,W)的Tensor或者shape为(H,W,C)的numpy.ndarray转换为PIL.Image,值不变。

11. 通用变换

class torchvision.transforms.Lambda(lambd); 使用lambd作为转换器。

猜你喜欢

转载自www.cnblogs.com/Shinered/p/10748732.html