0
0
PyTorchml~5 mins

Compose transforms in PyTorch

Choose your learning style9 modes available
Introduction
Compose transforms lets you combine many image changes into one step. This makes preparing images for a model easy and organized.
When you want to resize and normalize images before training a model.
When you need to apply multiple changes like cropping, flipping, and converting images to tensors.
When you want to keep your image processing steps clear and reusable.
When you want to apply the same set of changes to all images in a dataset.
When you want to chain simple image edits without writing separate code for each.
Syntax
PyTorch
transforms.Compose([
    transforms.Transform1(),
    transforms.Transform2(),
    ...
])
Each transform inside Compose is applied in order, one after another.
Use Compose to keep your image processing steps neat and easy to read.
Examples
Resize images to 128x128 pixels, then convert them to tensors.
PyTorch
transform = transforms.Compose([
    transforms.Resize((128, 128)),
    transforms.ToTensor()
])
Flip images randomly left-right, convert to tensor, then normalize pixel values.
PyTorch
transform = transforms.Compose([
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
Sample Model
This code downloads an image, resizes it to 64x64 pixels, converts it to a tensor, and normalizes its pixel values. Then it prints the tensor shape and pixel value range.
PyTorch
import torch
from torchvision import transforms
from PIL import Image
import requests
from io import BytesIO

# Download an example image
url = 'https://pytorch.org/assets/images/deeplab1.png'
response = requests.get(url)
img = Image.open(BytesIO(response.content))

# Compose transforms: resize, convert to tensor, normalize
transform = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])

# Apply transforms
img_t = transform(img)

# Print shape and pixel stats
print(f"Tensor shape: {img_t.shape}")
print(f"Min pixel value: {img_t.min():.3f}")
print(f"Max pixel value: {img_t.max():.3f}")
OutputSuccess
Important Notes
Normalize changes pixel values to a range that helps models learn better.
Transforms are applied in the order you list them inside Compose.
Always convert images to tensors before feeding them to PyTorch models.
Summary
Compose lets you chain many image transforms into one step.
Transforms run in the order you list them inside Compose.
Use Compose to keep image preprocessing clean and easy to manage.