Image Augmentation
A classifier trained on 2,000 photos of cats has seen 2,000 specific cats, in specific poses, lighting and framing. Show it the same cat mirrored, slightly darker or shifted ten pixels, and it may hesitate, although for a human nothing has changed. Data augmentation creates such variations on the fly during training: every epoch the model sees a slightly different version of each image, so it learns that these changes do not matter. It is one of the cheapest ways to reduce overfitting in vision, and the rule that governs it is simple: an augmentation must preserve the label.
The toolbox
| Family | Transformations | Preserves the label when... |
|---|---|---|
| geometric | horizontal / vertical flip, random crop and resize, rotation, translation, scaling | orientation and position are not part of the class (a flipped "b" is a "d") |
| photometric | brightness, contrast, saturation, hue shifts | colour is not the class (ripe vs unripe fruit) |
| degradation | Gaussian blur, noise, JPEG compression | fine detail is not the class |
| region dropping | Cutout (erase a random square) | the object is not tiny |
| mixing | MixUp, CutMix (combine two images and their labels) | the labels are mixed in the same proportion |
Augmentation is applied to the training images only, freshly at random in each epoch. Validation and test images stay untouched, because they must measure performance on real data. (Test-time augmentation, averaging predictions over a few flips, is a separate, optional trick.)
Geometric and photometric transforms in NumPy and OpenCV
Each transform is a few lines on an array of shape (height, width, channels). Here they are applied to a downscaled sample photo from scikit-image, with one random draw each:
import numpy as np
import cv2
import matplotlib.pyplot as plt
from skimage import data
rng = np.random.default_rng(0)
img = cv2.resize(data.astronaut(), (128, 128), interpolation=cv2.INTER_AREA) # uint8, RGB
def hflip(x):
return x[:, ::-1]
def random_crop_resize(x, scale=0.7):
h, w = x.shape[:2]
ch, cw = int(h * scale), int(w * scale)
top, left = rng.integers(0, h - ch + 1), rng.integers(0, w - cw + 1)
return cv2.resize(x[top:top + ch, left:left + cw], (w, h), interpolation=cv2.INTER_LINEAR)
def rotate(x, degrees):
h, w = x.shape[:2]
M = cv2.getRotationMatrix2D((w / 2, h / 2), degrees, 1.0)
return cv2.warpAffine(x, M, (w, h), borderMode=cv2.BORDER_REFLECT)
def brightness_contrast(x, b=30, c=1.3):
return np.clip(c * (x.astype(np.float32) - 128) + 128 + b, 0, 255).astype(np.uint8)
def blur(x):
return cv2.GaussianBlur(x, (7, 7), 2)
def noise(x, sigma=20):
return np.clip(x + rng.normal(0, sigma, x.shape), 0, 255).astype(np.uint8)
versions = {"original": img, "flip": hflip(img), "crop+resize": random_crop_resize(img),
"rotate 20": rotate(img, 20), "bright+contrast": brightness_contrast(img),
"blur": blur(img), "noise": noise(img)}
for name, v in versions.items():
print(f"{name:16s} shape {v.shape} mean {v.mean():6.1f} std {v.std():5.1f}")
fig, axes = plt.subplots(1, 7, figsize=(12, 2.2))
for ax, (name, v) in zip(axes, versions.items()):
ax.imshow(v)
ax.set_title(name, fontsize=8)
ax.axis("off")
fig.tight_layout()
plt.show()original shape (128, 128, 3) mean 114.6 std 79.4
flip shape (128, 128, 3) mean 114.6 std 79.4
crop+resize shape (128, 128, 3) mean 104.2 std 81.1
rotate 20 shape (128, 128, 3) mean 119.1 std 78.0
bright+contrast shape (128, 128, 3) mean 137.8 std 96.9
blur shape (128, 128, 3) mean 114.6 std 70.5
noise shape (128, 128, 3) mean 115.4 std 79.4
Every version keeps the shape (128, 128, 3), so they can be batched with the originals. A flip only rearranges pixels (mean and spread unchanged), blur lowers the spread (std 70.5 against 79.4), and brightness and contrast move both. Libraries such as torchvision's transforms.v2 and Albumentations wrap exactly these operations with random parameters per call, and also transform bounding boxes and masks along with the image, which you must do yourself when writing them by hand.
When an augmentation changes the label
Digits are the textbook case. A 6 turned upside down is a 9. If the training set were augmented with 180-degree rotations, the model would be taught that this shape is a 6, and its knowledge of 9s would suffer. The digit images that ship with scikit-learn show what a model trained on upright digits makes of rotated 6s:
import numpy as np
from collections import Counter
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
digits = load_digits()
X_tr, X_te, y_tr, y_te = train_test_split(digits.images, digits.target, test_size=0.3,
random_state=0, stratify=digits.target)
model = LogisticRegression(max_iter=2000).fit(X_tr.reshape(len(X_tr), -1), y_tr)
sixes = X_te[y_te == 6]
upright = model.predict(sixes.reshape(len(sixes), -1))
rotated = model.predict(np.rot90(sixes, 2, axes=(1, 2)).reshape(len(sixes), -1))
mirrored = model.predict(sixes[:, :, ::-1].reshape(len(sixes), -1))
print("test sixes:", len(sixes))
print("upright ->", dict(Counter(upright.tolist()).most_common(3)))
print("rot 180 ->", dict(Counter(rotated.tolist()).most_common(3)))
print("mirrored ->", dict(Counter(mirrored.tolist()).most_common(3)))test sixes: 54
upright -> {6: 53, 1: 1}
rot 180 -> {9: 47, 7: 4, 1: 3}
mirrored -> {3: 23, 7: 15, 2: 5}
Upright, 53 of 54 sixes are recognised. Rotated by 180 degrees, 47 of them are read as 9, which is the correct reading of that shape. Mirrored digits are no longer digits at all and the predictions scatter. So for digits, text and road signs (left-turn vs right-turn arrows) flips and large rotations are invalid; for satellite images or microscopy, where there is no "up", all eight flips and right-angle rotations are fine. Ask "would a human annotator still give the same label?" for every transform.
Cutout, MixUp and CutMix
These three regularise by making the task harder in a controlled way:
- Cutout erases a random square (sets it to zero or the mean). The label is unchanged; the model must use more than one part of the object.
- MixUp blends two images and their one-hot labels with the same weight drawn from a Beta distribution:
- CutMix pastes a random box from image into image ; the label weight of is the share of the image it still covers:
All three fit in a few lines of NumPy on a batch:
import numpy as np
rng = np.random.default_rng(42)
H = W = 8
cat = np.ones((H, W)) # stand-in images: all ones and all zeros make the mixing visible
dog = np.zeros((H, W))
y_cat, y_dog = np.array([1.0, 0.0]), np.array([0.0, 1.0]) # one-hot: [cat, dog]
def cutout(x, size=4):
x = x.copy()
top, left = rng.integers(0, H - size + 1), rng.integers(0, W - size + 1)
x[top:top + size, left:left + size] = 0
return x
def mixup(xa, ya, xb, yb, alpha=0.4):
lam = rng.beta(alpha, alpha)
return lam * xa + (1 - lam) * xb, lam * ya + (1 - lam) * yb, lam
def cutmix(xa, ya, xb, yb, alpha=1.0):
lam = rng.beta(alpha, alpha)
bh, bw = int(round(H * np.sqrt(1 - lam))), int(round(W * np.sqrt(1 - lam)))
top, left = rng.integers(0, H - bh + 1), rng.integers(0, W - bw + 1)
x = xa.copy()
x[top:top + bh, left:left + bw] = xb[top:top + bh, left:left + bw]
lam_area = 1 - bh * bw / (H * W) # the label follows the real box area
return x, lam_area * ya + (1 - lam_area) * yb, lam_area
c = cutout(cat)
print("cutout: share of cat pixels left", c.mean(), "| label", y_cat.tolist())
x, y, lam = mixup(cat, y_cat, dog, y_dog)
print(f"mixup: lambda {lam:.3f} | every pixel {x[0, 0]:.3f} | label {np.round(y, 3).tolist()}")
x, y, lam = cutmix(cat, y_cat, dog, y_dog)
print(f"cutmix: cat pixels {x.mean():.3f} | label {np.round(y, 3).tolist()}")
print(x.astype(int))cutout: share of cat pixels left 0.75 | label [1.0, 0.0]
mixup: lambda 0.157 | every pixel 0.157 | label [0.157, 0.843]
cutmix: cat pixels 0.859 | label [0.859, 0.141]
[[1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1]
[1 1 1 1 1 0 0 0]
[1 1 1 1 1 0 0 0]
[1 1 1 1 1 0 0 0]
[1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1]]
The label always matches the content: the MixUp image is 0.157 cat in every pixel and its label says so; the CutMix box is 3 by 3 pixels, so the image keeps 55 of 64 cat pixels (0.859), and the label is computed from the actual box size after rounding, not from the sampled . Mixing methods are applied per batch (each image mixed with a shuffled partner), only during training, and need a loss that accepts soft labels (cross-entropy with probability targets).
Pitfalls
- Augmenting before the split: an augmented copy of a test image in the training set is a near-duplicate leak. Split first, augment the training set only, ideally on the fly.
- Forgetting the annotations: a flipped image needs flipped bounding boxes, masks and keypoints (and "left eye" becomes "right eye").
- Too strong: a crop that removes the object or a colour shift that changes "ripe" to "unripe" produces wrong labels. Look at a grid of augmented samples before training.
- Statistics after augmentation: compute normalisation means and standard deviations on the original training images, not on augmented ones.
Practice
- Which augmentations are safe for chest X-rays used to detect an enlarged heart (which sits on the patient's left)?
Answer
Small rotations, small translations and crops that keep the whole heart, brightness and contrast changes, mild noise. Not horizontal flips: they move the heart to the right side, which is a different (rare) condition, dextrocardia, and would teach the model wrong anatomy.
- A CutMix box of 3 by 4 pixels is pasted into an 8 by 8 image of class A from an image of class B. What is the label?
Answer
The box covers 12 of 64 pixels, so : label A and B.
Test yourself
What is the basic rule for any data augmentation?
- It must make images smaller
- It must preserve the label
- It must be applied to the test set too
- It must use a neural network
For which task is a horizontal flip invalid?
- Cat vs dog photos
- Satellite images of fields
- Recognising left-turn vs right-turn road signs
- Flowers
MixUp with mixes a cat image (a) with a dog image (b). What is the target?
- cat 1.0
- cat 0.7, dog 0.3
- cat 0.3, dog 0.7
- cat 0.5, dog 0.5
When should augmentation be applied?
- To the whole dataset before splitting
- To the training data only, freshly at random during training
- To the test data only
- Once, saving all copies to disk with the test set