Horizontally flip and crop an image together with its boxes
Why it matters Every detection training pipeline, from torchvision to YOLO dataloaders, applies these box-aware augmentations.
Augmenting detection data means moving the boxes with the pixels. Forgetting to swap x1 and x2 on a flip is the classic bug.
Write flip_and_crop(img, boxes, flip, top, left, h, w). img is (H, W, C) and boxes is (n, 4) as (x1, y1, x2, y2) in pixel units (continuous, so a box covering column 0 only is x1 = 0, x2 = 1). If flip, mirror the image left-right and map boxes to (W - x2, y1, W - x1, y2). Then crop img[top:top + h, left:left + w], shift boxes by (-left, -top), clip x to [0, w] and y to [0, h], and drop boxes whose clipped width or height is 0. Return (img_out, boxes_out) with boxes_out a float array of shape (m, 4).
def flip_and_crop(img, boxes, flip, top, left, h, w)Example
a 2 x 4 x 1 image with boxes [[0, 0, 1, 2]], flip = True, top = 0, left = 1, h = 2, w = 3 gives boxes [[2, 0, 3, 2]] (the box moved to the right edge).
Understand the idea
Augmentation creates new training images by flipping, cropping and so on. For detection, the labels are boxes, so they must move with the pixels. When you mirror an image, what was on the left is now on the right, and the box's left edge is the mirror of its old right edge. Like reading a name tag in a mirror: the first letter ends up last.
Tiny example: width 4, a box from x = 0 to 1. After a flip it spans 4 - 1 = 3 to 4 - 0 = 4. Cropping from left = 1 shifts it to 2 to 3.
Rules: flip: (x1, x2) becomes (W - x2, W - x1). Crop: subtract (left, top), clip to [0, w] x [0, h], drop empty boxes.
Detection libraries apply random flips and crops like this on every training batch.
Shapes and data flow
img (H,W,C) -> (h,w,C); boxes (n,4) -> (m,4), m <= n