torchvision transform
时间: 2023-11-06 19:03:38 浏览: 63
The torchvision transform module provides a set of common image transformations for data augmentation and preprocessing. These transformations can be applied to PIL images or tensors in PyTorch.
Some of the common transformations provided by torchvision transform module are:
1. Resize: Resizes the image to a given size.
2. RandomCrop: Crops a random portion of the image.
3. RandomHorizontalFlip: Flips the image horizontally with a probability of 0.5.
4. ToTensor: Converts a PIL image or numpy array to a PyTorch tensor.
5. Normalize: Normalizes the tensor with given mean and standard deviation.
Example usage:
```
import torch
import torchvision.transforms as transforms
# Define transforms
transform = transforms.Compose([
transforms.Resize(256),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# Apply transforms to an image
image = PIL.Image.open('image.jpg')
image_tensor = transform(image)
# Apply transforms to a batch of images
batch = [PIL.Image.open(f'image{i}.jpg') for i in range(4)]
batch_tensor = torch.stack([transform(image) for image in batch])
```
阅读全文