transform.Compose
时间: 2023-10-12 22:11:57 浏览: 119
`transform.Compose` is a PyTorch utility class that allows us to combine multiple transformations together, in a sequential manner. It takes a list of individual transformations as input and returns a single transformation that applies all the transformations in the list in the order they are passed.
Here is an example of how `transform.Compose` can be used with PyTorch transformations:
```python
import torchvision.transforms as transforms
# Define individual transformations
transform1 = transforms.ToTensor()
transform2 = transforms.Normalize((0.5,), (0.5,))
# Combine multiple transformations
composed_transform = transforms.Compose([transform1, transform2])
```
In the above example, we define two individual transformations, `transform1` which converts the input PIL image to a PyTorch tensor, and `transform2` which normalizes the tensor with mean 0.5 and standard deviation 0.5. We then combine these two transformations using `transform.Compose` to create a single transformation `composed_transform` that first applies `transform1` and then `transform2` in sequence.
We can then use this `composed_transform` object to transform a PIL image as follows:
```python
from PIL import Image
# Load an image
img = Image.open("image.jpg")
# Apply the composed transformation to the image
transformed_img = composed_transform(img)
```
The `transformed_img` object will contain the normalized PyTorch tensor representation of the input image after applying both the `transform1` and `transform2` transformations in sequence.
阅读全文