Augmenting an image and its mask together

MediumData augmentationImage segmentation

Goal: Applying the same geometric transforms to the image and the segmentation mask.

Python — example.py
import numpy as np
import albumentations as A

img = np.random.default_rng(0).integers(0, 255, (128, 128, 3), dtype=np.uint8)
mask = np.zeros((128, 128), dtype=np.uint8); mask[30:60, 10:40] = 1
tf = A.Compose([A.HorizontalFlip(p=1.0), A.RandomBrightnessContrast(p=1.0)], seed=0)
out = tf(image=img, mask=mask)
ys, xs = np.nonzero(out["mask"])
print("Image and mask shape:", out["image"].shape, out["mask"].shape)
print("Mask pixels before and after:", int(mask.sum()), int(out["mask"].sum()))
print("Horizontal mask bounds after flipping:", xs.min(), "to", xs.max())

Code explanation

When image and mask are passed together, Albumentations applies the same geometric transform to both, and colour transforms to the image only. We check that the sum of mask pixels is unchanged after a horizontal flip.

Requirements

Shell
pip install albumentations numpy

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Image and mask shape: (128, 128, 3) (128, 128)
Mask pixels before and after: 900 900
Horizontal mask bounds after flipping: 88 to 117

This example was actually run and tested on 21 November 2026 on a CPU — albumentations 2.0.8, numpy 2.5.5, python 3.13.18

Libraries used

Related examples