torchvision.transforms provides composable, function-like image transformations for preparing data before a deep-learning model evaluates it. A pipeline can resize and crop an image, convert it to a tensor, and normalize its color values. section 2.1.4 section 7.1.3
Common jobs for transforms include:
- Convert PIL images or NumPy arrays into tensors with channel-first C × H × W dimensions. section 7.1.3
- Scale image values from 0–255 to floating-point values from 0.0 to 1.0. section 7.1.3
- Compose several preprocessing steps into one callable pipeline. section 2.1.4
- Apply a transform automatically when a torchvision dataset returns an item. section 7.1.3
Prepare an image for a pretrained model
from torchvision import transforms preprocess = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ]) img_t = preprocess(img) This produces a tensor resized and shaped for the model, with normalized RGB components matching the model's training conditions. A batch dimension can then be added with torch.unsqueeze(img_t, 0). section 2.1.4
# In[6]:
from torchvision import transforms
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)])
Inspect the complete Compose pipeline used to resize, crop, tensorize, and normalize an input image. section 2.1.4
