Sub topic 12
Augmenting masks and bounding boxes together with images
This chapter assumes you can read NumPy arrays, you know the common image augmentations from the earlier chapters, and you have seen how segmentation masks and detection boxes are stored. Classification needs only the image to change. Segmentation and detection also have targets that live in pixel coordinates, so a transform that moves pixels must move the targets by the same amount.
Why the targets must move with the image
A segmentation mask has one label per pixel. If you flip the image and leave the mask alone, every label now points at the wrong pixel. A bounding box stores coordinates, so after a flip or crop it describes empty background. The model still trains, but it learns from wrong labels, and the validation score only drops slightly. This makes the bug hard to notice.
Two rules cover most cases.
- Share the random draw. Sample the transform parameters once (flip or not, crop offset, angle) and apply that one draw to the image and to every target.
- Match each transform to what it changes. Geometric transforms change the image and the targets. Photometric transforms change only the image. Occlusion transforms change the image and usually leave the targets alone.
| Transform family | Image | Mask | Boxes |
|---|---|---|---|
| Flip, crop, rotate, scale | Transformed | Same geometry, nearest-neighbor interpolation | Coordinates recomputed, clipped, filtered |
| Brightness, contrast, color, noise, blur | Transformed | Unchanged | Unchanged |
| Random erasing, cutout | Pixels overwritten | Unchanged (see the note below) | Unchanged, but the object may be hidden |
| Mixup | Blended | Not meaningful | Usually not used |
| CutMix | Region pasted | Same region pasted | Boxes pasted and clipped |
Flipping an image and its mask
The simplest correct version draws one random number and uses it for both arrays.
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, maskThe mistake to avoid is calling two separate random transforms, one on the image and one on the mask. Each would flip on different draws, and about half the samples would be misaligned. This happens easily when you pass image and mask through two separate transforms.Compose pipelines from torchvision's older API.
Transforming bounding boxes by hand
Boxes need arithmetic. This chapter uses the (x_min, y_min, x_max, y_max) format in pixels. Other formats exist, such as (x, y, w, h) in COCO and normalized center-based boxes in YOLO. Convert to one format first and keep it the same throughout the pipeline.
A horizontal flip mirrors the x coordinates, and the old right edge becomes the new left edge:
import numpy as np
def hflip_boxes(boxes, width):
out = boxes.copy()
out[:, 0] = width - boxes[:, 2]
out[:, 2] = width - boxes[:, 0]
return out
boxes = np.array([[100, 50, 300, 200], [500, 100, 620, 300]], dtype=float)
print(hflip_boxes(boxes, width=640))
# [[340. 50. 540. 200.]
# [ 20. 100. 140. 300.]]If you wrote width - x_min and width - x_max without swapping, you would get x_min > x_max, which many loss functions reject or silently mishandle.
A crop is harder because it can cut boxes. Shift the coordinates by the crop origin, clip them to the crop window, and drop boxes that are mostly or fully outside.
import numpy as np
def crop_boxes(boxes, labels, x0, y0, w, h, min_visible=0.3):
shifted = boxes - np.array([x0, y0, x0, y0], dtype=float)
area = (shifted[:, 2] - shifted[:, 0]) * (shifted[:, 3] - shifted[:, 1])
clipped = shifted.copy()
clipped[:, [0, 2]] = clipped[:, [0, 2]].clip(0, w)
clipped[:, [1, 3]] = clipped[:, [1, 3]].clip(0, h)
new_area = (clipped[:, 2] - clipped[:, 0]) * (clipped[:, 3] - clipped[:, 1])
keep = (new_area > 0) & (new_area >= min_visible * area)
return clipped[keep], labels[keep]
boxes = np.array([[100, 50, 300, 200], [500, 100, 620, 300]], dtype=float)
labels = np.array([1, 2])
new_boxes, new_labels = crop_boxes(boxes, labels, x0=200, y0=0, w=300, h=300)
print(new_boxes, new_labels)
# [[ 0. 50. 100. 200.]] [1]The first box loses its left third but keeps 50% of its area, so it survives with its coordinates clipped. The second box lies entirely outside the crop, so it is removed along with its label. Always filter the labels together with the boxes. Otherwise the arrays have different lengths and the label at index i no longer belongs to box i.
The `min_visible` threshold
How much of an object must survive a crop before you still call it that object? A box that keeps 5% of its area is a sliver that looks like nothing, yet the label says "dog". A threshold of 0.25 to 0.5 is common. Too low teaches the model to hallucinate objects from fragments. Too high deletes boxes for objects that are still recognizable, which teaches the model to treat them as background. Treat it as a tunable setting and check it visually, as described in the later chapter on validation.
Rotation and other non-axis-aligned transforms
A rotated rectangle is not an axis-aligned rectangle. The usual approach is to rotate the four corners and then take the smallest axis-aligned box around them. That box is larger than the object, and the error grows with the angle. At 45 degrees a square object's box has about 41% more width and height than the object itself. For small angles, up to roughly 10 degrees, this is acceptable. For large angles, prefer masks or rotated-box formats, or avoid rotation for detection.
Masks do not have this problem. They are rotated pixel by pixel, so they stay exact.
Interpolation and padding for masks
Masks hold class IDs, not intensities. Bilinear interpolation between class 3 and class 7 produces class 5, a label that may not exist in your dataset. Resize, rotate, and scale masks with nearest-neighbor interpolation. Also decide what the padding value means. If rotation exposes new border pixels, the image gets black or reflected pixels, and the mask should get the background or "ignore" label (often 255 in PyTorch segmentation code), not a real class.
Letting torchvision do the bookkeeping
Writing every case by hand does not scale. The torchvision.transforms.v2 API handles images, masks, and boxes in one call. It identifies each part of the input by its type, so the same transform is applied with the right rule for each: bilinear for images, nearest for masks, coordinate math for boxes, and no change to masks or boxes under color transforms.
import torch
from torchvision import tv_tensors
from torchvision.transforms import v2
transform = v2.Compose([
v2.RandomResizedCrop(size=(224, 224), antialias=True),
v2.RandomHorizontalFlip(p=0.5),
v2.ColorJitter(brightness=0.2, contrast=0.2),
v2.SanitizeBoundingBoxes(),
])
image = tv_tensors.Image(torch.randint(0, 256, (3, 480, 640), dtype=torch.uint8))
boxes = tv_tensors.BoundingBoxes(
[[100, 100, 300, 300], [400, 50, 600, 200]],
format="XYXY",
canvas_size=(480, 640),
)
mask = tv_tensors.Mask(torch.zeros(480, 640, dtype=torch.uint8))
labels = torch.tensor([1, 2])
sample = {"image": image, "boxes": boxes, "mask": mask, "labels": labels}
out = transform(sample)
print(out["image"].shape, out["boxes"].shape, out["mask"].shape, out["labels"])Four details matter here:
- The wrapper types
tv_tensors.Image,tv_tensors.Mask, andtv_tensors.BoundingBoxesare what tell the transform how to treat each tensor. A plain tensor is handled as an image, so an unwrapped mask would get bilinear interpolation. BoundingBoxescarries itsformatandcanvas_size, so clipping uses the correct image bounds.SanitizeBoundingBoxesremoves boxes that became degenerate after the crop and removes the matching entries fromlabels. It finds the labels through the"labels"key by default. It only removes boxes with near-zero size, not boxes that are mostly cropped away, so it does not replace amin_visiblerule. If you need one, usev2.RandomIoUCropfor detection, which keeps crops that overlap enough with existing boxes.- Run the same transform object on every sample. It draws new random parameters per call, and within one call all parts of the sample share that draw.
Albumentations offers the same idea through A.Compose(..., bbox_params=A.BboxParams(format="pascal_voc", label_fields=["labels"])) and a call such as transform(image=img, mask=m, bboxes=b, labels=l).
Mixing methods and occlusion with targets
Mixup blends pixel values, so for segmentation there is no sensible blended mask. CutMix works: paste a rectangle from image B into image A and paste the same rectangle from mask B into mask A, so the pixels and labels stay aligned. For detection, mosaic-style methods combine several images and shift each one's boxes. The same crop rule applies to boxes cut by a tile border.
Random erasing leaves masks and boxes unchanged, which means the label can say an object is present when it is now hidden. Small erased patches are fine. Erasing a large part of the only object gives the model an unlearnable example. Keep the erased area small, or choose erase locations that avoid covering most of any box.
Checking that targets stayed aligned
Draw the transformed targets on the transformed image before you train. Overlay the mask with some transparency and draw the box rectangles for 20 or 30 random samples. Look for boxes offset from the object, masks shifted by one side, and objects that vanished while their boxes stayed. This takes five minutes and catches the bugs described above. A programmatic check also helps: assert that every box satisfies x_min < x_max, y_min < y_max, and lies within the image, and that len(boxes) == len(labels).
Exercise
You write a detection pipeline with a random crop followed by a horizontal flip. A crop removes the right half of one box, leaving 40% of its original area, and your min_visible is 0.5. What happens to that box, and what is the risk if you lower min_visible to 0.05?
Show answer
The box is dropped, along with its label, because 0.4 is below 0.5. The object stays in the image as unlabeled background, which can teach the model to ignore partly visible objects. With min_visible at 0.05, almost any fragment keeps its label, so the model sees tiny slivers labeled as full objects and may learn to predict objects from fragments. Check the effect visually and compare validation results.
Exercise
A segmentation model trained with rotation augmentation predicts new class IDs that do not exist in your dataset, mostly along object edges. What is the likely cause and the fix?
Show answer
The mask was rotated with bilinear (or bicubic) interpolation, which averages neighboring class IDs into values that match no real class. Resize and rotate masks with nearest-neighbor interpolation. In torchvision v2, wrap the mask as tv_tensors.Mask so the transform selects nearest-neighbor automatically.