Sub topic 4
Geometric transforms: flips, crops, rotations, and scaling
This chapter assumes you can read basic PyTorch code, know that an image is an array of shape (height, width, channels), and have trained a classifier with a train/validation split. Geometric transforms change where pixels sit in the image. They do not change pixel colors. That makes them the most widely used augmentations, and also the easiest to misuse.
What a geometric transform does
A geometric transform maps each output pixel position to a position in the input image. A flip mirrors the coordinates. A crop selects a window. A rotation turns the coordinates around a center point. A scale stretches or shrinks them.
Each transform encodes an assumption: the label does not change when the object moves, turns, or appears at a different size. A cat is still a cat when mirrored. A handwritten "6" rotated by 180 degrees looks like a "9", so the assumption fails there. Check each transform against your task before you add it. The previous chapter on label-preserving transforms covers this reasoning in general.
Flips
A horizontal flip mirrors the image left to right. It suits natural photos of animals, vehicles, and objects, because the world has no preferred left or right. A vertical flip mirrors top to bottom. It suits aerial, satellite, and microscopy images, where "up" has no meaning, but not street scenes or portraits.
Flips fail when orientation carries meaning:
- Text and digits: a flipped "b" looks like a "d", and a mirrored word is unreadable.
- Chirality: in medical imaging, the heart sits on the left of the body, so a flipped chest X-ray shows a condition that does not exist.
- Tasks that predict direction, such as "is the car turning left or right?"
Flips cost almost nothing and add no artifacts, because no interpolation is needed. In torchvision, use RandomHorizontalFlip(p=0.5) or RandomVerticalFlip(p=0.5). With p=0.5, the model sees the original half the time.
Crops
Cropping cuts a window out of the image. There are three common forms.
| Transform | Behavior | Typical use |
|---|---|---|
| `CenterCrop(size)` | Always takes the middle window | Evaluation |
| `RandomCrop(size, padding=4)` | Takes a random window of fixed size, optionally after padding | Small images such as CIFAR |
| `RandomResizedCrop(size, scale, ratio)` | Takes a random window of random area and aspect ratio, then resizes it to `size` | ImageNet-style training |
RandomResizedCrop does two jobs at once. It shifts the object and changes its apparent scale. Its two main parameters are scale, the fraction of the original area to keep, and ratio, the range of aspect ratios. The defaults are scale=(0.08, 1.0) and ratio=(3/4, 4/3). A window with 8 percent of the area often misses the object. If your objects are small or fill a small part of the image, raise the lower bound, for example scale=(0.5, 1.0).
A crop can remove the evidence for the label. If a classification image shows a small bird in a corner and the crop excludes the corner, the label "bird" is now wrong for that sample. This noise is small when it happens rarely. It becomes harmful when objects are small or the minimum crop area is aggressive.
Rotations
RandomRotation(degrees) rotates the image by an angle drawn uniformly from [-degrees, +degrees]. Small angles, up to about 15 degrees, mimic a tilted camera. Large angles are only appropriate when the data has no natural orientation, as in aerial or microscopy images.
Rotation introduces two issues:
- Empty corners. A rotated rectangle does not fill the original frame, so the corners need filling. The next section on interpolation and borders covers how to fill them. By default torchvision fills them with black (zeros).
- Resampling blur. Unless the angle is a multiple of 90 degrees, every output pixel is computed by interpolation between input pixels, which slightly softens the image.
For right angles on square images, you can rotate exactly with torch.rot90, which moves pixels without any interpolation. This is useful for datasets with full rotational symmetry.
Scaling and affine transforms
Scaling zooms in or out. A single transform can combine rotation, translation, scale, and shear: RandomAffine. Shear slants the image so that rectangles become parallelograms. Together these are called affine transforms, which preserve straight lines and parallelism.
from torchvision import transforms
affine = transforms.RandomAffine(
degrees=10, # rotation in [-10, 10] degrees
translate=(0.1, 0.1), # shift up to 10% of width and height
scale=(0.9, 1.1), # zoom between 90% and 110%
shear=5, # shear in [-5, 5] degrees on the x axis
)Using one RandomAffine is better than chaining separate rotate, translate, and scale transforms. It composes the parameters into a single matrix and resamples the image once. Chained transforms resample multiple times and blur the result more.
Zooming out (scale below 1) leaves empty borders. Zooming in (scale above 1) discards the edges, which has the same label risk as cropping.
A runnable example
The script below applies a flip, a resized crop, and an affine transform to a synthetic image and prints the output shapes. It needs only torch, torchvision, and Pillow.
import torch
from PIL import Image
from torchvision import transforms
from torchvision.transforms import functional as TF
torch.manual_seed(0)
# A 256x192 RGB image with a horizontal gradient, so flips are visible.
width, height = 256, 192
row = torch.linspace(0, 255, width).to(torch.uint8)
pixels = row.repeat(height, 1)
array = torch.stack([pixels, pixels.flip(1), torch.zeros_like(pixels)], dim=0)
img = Image.fromarray(array.permute(1, 2, 0).numpy())
pipeline = transforms.Compose([
transforms.RandomHorizontalFlip(p=1.0),
transforms.RandomResizedCrop(224, scale=(0.5, 1.0)),
transforms.RandomAffine(degrees=10, translate=(0.1, 0.1), scale=(0.9, 1.1)),
])
out = pipeline(img)
print("input size (W, H):", img.size)
print("output size (W, H):", out.size)
# Compare the left-edge red value before and after a deterministic flip.
before = TF.to_tensor(img)[0, 0, 0].item()
after = TF.to_tensor(TF.hflip(img))[0, 0, 0].item()
print("red at top-left before flip:", round(before, 3))
print("red at top-left after flip:", round(after, 3))The output size is always 224 by 224, because RandomResizedCrop fixes it. After the flip, the top-left red value moves from near 0 to near 1, which shows the pixels moved.
Applying the transform to a single random draw
A random transform picks its parameters each time it is called. This matters when you must apply the same geometry to two things, such as an image and its mask. Calling two random transforms separately gives each a different flip. The paired-targets chapter covers this fully. For now, note the rule: draw the random numbers once, then apply them to every array.
import numpy as np
rng = np.random.default_rng(0)
def random_hflip(image, mask, p=0.5):
# image: (H, W, C), mask: (H, W)
if rng.random() < p:
image = image[:, ::-1].copy()
mask = mask[:, ::-1].copy()
return image, maskChoosing strength
Strength is how far a transform departs from the original. Choose it by asking how much variation your deployment data has.
- If test images come from a fixed camera setup, use mild geometry. Heavy rotation teaches the model invariances it never needs and uses capacity on them.
- If test images come from users' phones, expect tilt, varying zoom, and off-center subjects. Stronger geometry matches that spread.
- Keep the objects visible. Before training, view a grid of augmented samples and confirm the label is still obvious to a person.
Common errors
- Flipping where direction matters. Digits, text, and medical scans are the usual cases.
- Using
RandomResizedCropfor evaluation. Evaluation should be deterministic, so useResizeandCenterCropinstead. - Aggressive minimum crop area. The default of 0.08 can remove the object. Raise it for small-object data.
- Rotating without handling corners. Black wedges can become a shortcut the model learns, for example if one class tends to be rotated more.
- Ordering. Geometric transforms operate on the PIL image, before
ToTensorandNormalize. Padding with zeros after normalization is not black, because normalized black is a negative number.
Exercise
You train a classifier on photos of handwritten digits 0 to 9. A colleague adds RandomHorizontalFlip(p=0.5) and RandomRotation(degrees=180). Name two problems with these choices and suggest a safer replacement.
Show answer
A horizontal flip turns digits into mirror images that are not valid digits (a mirrored 2 or 5 looks wrong, and 2 and 5 can look alike). A rotation of up to 180 degrees can turn a 6 into a 9, so the label becomes wrong. A safer choice is a small RandomAffine, for example degrees=10, translate=(0.1, 0.1), scale=(0.9, 1.1), which models natural handwriting variation without changing which digit it is.
Exercise
A RandomResizedCrop with scale=(0.08, 1.0) is used on a dataset where the target object fills only about 10 percent of each image. Training accuracy is fine but you suspect label noise from the crops. What change would you make, and how would you check it?
Show answer
Raise the lower bound of scale, for example to (0.4, 1.0) or higher, so the crop is more likely to contain the object. To check, render a grid of 50 or so augmented samples and count how many no longer show the object. Then compare validation accuracy between the old and new settings with the same seed and everything else fixed.