Sub topic 12
Augmenting Masks and Bounding Boxes Together with Images
Assume you know Python, NumPy arrays, supervised learning, and basic image augmentation. This chapter focuses on detection and segmentation, where every image has targets that must remain aligned with it.
Why paired augmentation matters
A segmentation mask stores a class label for each pixel. A bounding box stores an object's location, commonly as (x_min, y_min, x_max, y_max).
When you transform an image, transform its targets with the same operation. A horizontal flip changes the image and mask pixels, and it also changes each box's horizontal coordinates. A color change affects only the image because it does not change object locations.
If the image and target disagree, the model receives incorrect supervision. This is a form of label noise that can prevent training from converging.
Apply the same geometric operation
For a horizontal flip of an image with width W, a box transforms as follows:
new_x_min = W - old_x_maxnew_x_max = W - old_x_min- The y coordinates stay unchanged.
The mask must be flipped across the same axis. Use nearest-neighbor interpolation for masks so class IDs remain integers. Bilinear interpolation can create invalid values such as 1.4 between classes.
import numpy as np
def horizontal_flip(image, mask, boxes, probability=0.5, rng=None):
"""Flip an image, mask, and xyxy boxes using one random decision."""
if rng is None:
rng = np.random.default_rng()
if rng.random() >= probability:
return image, mask, boxes
height, width = image.shape[:2]
flipped_image = image[:, ::-1].copy()
flipped_mask = mask[:, ::-1].copy()
flipped_boxes = boxes.copy()
flipped_boxes[:, 0] = width - boxes[:, 2]
flipped_boxes[:, 2] = width - boxes[:, 0]
return flipped_image, flipped_mask, flipped_boxes
image = np.zeros((100, 200, 3), dtype=np.uint8)
mask = np.zeros((100, 200), dtype=np.uint8)
boxes = np.array([[20, 10, 80, 60]], dtype=np.float32)
image, mask, boxes = horizontal_flip(
image, mask, boxes, probability=1.0, rng=np.random.default_rng(7)
)
print(boxes) # [[120. 10. 180. 60.]]The code uses one random draw. Do not call separate random flip transforms for the image and mask. They could make different decisions.
Cropping and resizing
Cropping removes part of the image. Subtract the crop's left and top offsets from every box:
x' = x - crop_lefty' = y - crop_top
Then clip coordinates to the crop boundaries. Remove boxes whose visible area is too small, or mark them as truncated according to your dataset's rules.
Resizing scales both coordinates and image dimensions. If the width changes from old_width to new_width, multiply every x coordinate by new_width / old_width. Apply the equivalent scale to y coordinates.
For detection, check whether a crop removes an object's center or leaves only a tiny fragment. For segmentation, cropped masks must use the same crop rectangle as the image.
> callout note > Geometric transforms require paired targets. Photometric transforms, such as brightness or contrast changes, usually apply only to the image. Never apply color jitter to a class-index mask.
Use task-aware transform libraries
Libraries such as Albumentations and torchvision's newer transform APIs can manage images, masks, and boxes together. You still need to declare the box format, coordinate convention, and label fields correctly. A library cannot fix metadata that you provide incorrectly.
Common box formats include:
| Format | Meaning |
|---|---|
| `xyxy` | left, top, right, bottom |
| `xywh` | left, top, width, height |
| `cxcywh` | center x, center y, width, height |
Mixing these formats silently produces wrong targets. After each new transform, draw the boxes and mask boundaries over the transformed image and inspect several examples.
Exercise
An image is 640 pixels wide and contains a box (100, 40, 220, 180). What is the box after a horizontal flip?
Show answer
(420, 40, 540, 180), because the new x coordinates are 640 - 220 and 640 - 100.