from PIL import Image
from torchvision import transforms as T
import torch
to_tensor = T.ToTensor()
to_pil = T.ToPILImage()
cat = Image.open('./data/image/cat.jpg')
cat_c = to_tensor(cat)
print(cat_c.shape)
cat_c = to_pil(cat_c)
torch.Size([3, 1274, 1280])
t_out = torch.randn(3,256,256)
img1 = T.ToPILImage()(t_out)
img1
torchvision.transforms.CenterCrop:从图像中心裁剪图片
transforms = T.Compose([T.Resize(224),T.CenterCrop(224),T.ToTensor()])
print(transforms)
cat_t = transforms(cat)
print(cat_t.shape)
to_pil(cat_t)
Compose(
Resize(size=224, interpolation=bilinear, max_size=None, antialias=None)
CenterCrop(size=(224, 224))
ToTensor()
)
torch.Size([3, 224, 224])
torchvision.transforms.RandomCrop:从图片中随机裁剪出尺寸为size的图片
transforms = T.Compose([T.Resize(224),T.RandomCrop(256, padding=(16, 64)),T.ToTensor()])
cat_t = transforms(cat)
print(cat_t.shape)
to_pil(cat_t)
torch.Size([3, 256, 256])
transforms = T.Compose([T.Resize(224), T.RandomCrop(352,padding=(64,64),padding_mode = 'constant', fill=66),T.ToTensor()])
cat_t = transforms(cat)
to_pil(cat_t)
transforms = T.Compose([T.Resize(224),T.RandomHorizontalFlip(p=0.5),T.ToTensor()])
cat_t = transforms(cat)
cat_t.shape
to_pil(cat_t)
transforms = T.Compose([T.Resize(224),T.RandomRotation(30, center=(0, 0), expand=True),T.ToTensor()])
cat_t = transforms(cat)
cat_t.shape
to_pil(cat_t)
transform方法
裁剪
- transforms.CenterCrop
- transforms.RandomCrop
- transforms.RandomResizedCrop
- transforms.FiveCrop
- transforms.TenCrop
翻转和旋转
- transforms.RandomHorizontalFlip
- transforms.RandomVerticalFlip
- transforms.RandomRotation
图像变换
- transforms.Pad
- transforms.ColorJitter
- transforms.Grayscale
- transforms.RandomGrayscale
- transforms.RandomAffine
- transforms.LinearTransformation
- transforms.RandomErasing
- transforms.Lambda
- transforms.Resize
- transforms.Totensor
- transforms.Normalize
transforms的操作
- transforms.RandomChoice
- transforms.RandomApply
- transforms.RandomOrder