AI Logic

Data Augmentation

Mosaic

Updated:

Mosaic diagram. The left shows the flow for building one training image (pick 4 images, pick the center, place the 4 images around the center, shift the box coordinates, crop with scaling and other transforms, object detection model). The right shows an example in which 4 images with objects and boxes are placed upper left, upper right, lower left, and lower right around the center of a 2s × 2s canvas, with boxes cut off at the edges, the s × s output region, and areas with no image

What is Mosaic

Mosaic is a data augmentation method for object detection that stitches four training images into one and moves each object's bounding box along with it for training. It was introduced as a new data augmentation in the 2020 YOLOv4 paper (Bochkovskiy et al.). According to the paper's acknowledgments, the idea came from Glenn Jocher, who created the Ultralytics YOLOv3 implementation.

Whereas CutMix mixes two images, Mosaic mixes four. Because one training image contains four different scenes (contexts), the model practices finding objects without relying on their "usual background."

The paper summarizes the benefits of Mosaic in two points.

  • The model learns to detect objects outside their normal context: Because the four scenes sit next to each other, objects appear beside backgrounds where they would not normally be seen.
  • Training works well even with small mini-batches: Batch normalization ends up computing statistics in each layer from the four images contained in a single training image. The paper says this greatly reduces the need for a large mini-batch.

As an analogy, it is like making a collage out of four photos and practicing finding everything in it. Objects are sometimes cut off at the seams between photos, which also builds the ability to find objects from only part of them.

Unlike CutMix for classification, Mosaic does not compute a ratio for mixing labels. In object detection, the ground truth is a list of boxes saying "what is where," so the boxes of the four images are shifted to match where each image was pasted and combined into the ground truth for one image.

How it is built

The YOLOv4 paper describes Mosaic as "mixing four training images" and only shows example images (Figure 3); it does not give detailed placement steps. This section shows the procedure shared by Ultralytics YOLOv5, the successor of the implementation credited in the paper's acknowledgments, and the MMDetection implementation (figure at the top). ss is the size of one image (e.g., 640 pixels).

  1. Pick four images: Take one image from the training data and choose three others at random. Resize each so that its longer side is ss.
  2. Prepare a canvas: Fill a 2s×2s2s \times 2s canvas with gray (pixel value 114).
  3. Pick the center: Choose the point (xc,yc)(x_c, y_c) where the four images meet uniformly from the range 0.5s0.5s to 1.5s1.5s on the canvas.
  4. Place the four images: Place the first image to the upper left of the center, the second to the upper right, the third to the lower left, and the fourth to the lower right, each with a corner touching the center. Discard any part that extends beyond the canvas.
  5. Move the boxes: Add the offset of each image's placement to the coordinates of its boxes. Clip any part that extends outside the canvas.
  6. Bring it to the final size: In YOLOv5, the subsequent transform for scaling, translation, and so on (random_perspective) crops the central s×ss \times s region of the canvas. In MMDetection, a transform that plays the same role (RandomAffine) is applied right after Mosaic.

Because the center changes every time, how much of each image appears changes from one training step to the next. When the center is near an edge of the canvas, one image barely appears and another appears large.

The gray areas in the figure at the top are where no image was placed. When the center moves away from ss, bands without any image appear along the edges of the canvas.

Why it works

Based on the paper's explanation and the procedure, the reasons Mosaic works for object detection can be organized as follows.

  • Less reliance on context: Since four scenes are lined up in one image, background cues like "ships are on water" or "cars are on roads" are not enough to find objects. The model learns to rely on the appearance of the objects themselves (the paper's explanation).
  • More stable batch normalization statistics: Because one training image contains four images, the data from which batch normalization computes means and variances is more diverse even when the mini-batch has few images (the paper's explanation). The paper aims for an object detector that can be trained on a single GPU and positions Mosaic as one of the techniques for that.
  • More diverse object sizes and positions: Since four images are laid out on a 2s2s canvas and then fit into ss, objects in each image tend to appear smaller. Objects are also cut off at the seams between images, which provides practice in finding objects of which only part is visible.

The third point, "objects appear smaller," is a property derived from the procedure. The paper does not separately show whether Mosaic improved accuracy on small objects.

Results reported in the paper

The YOLOv4 paper adds various improvements, including Mosaic, one at a time and compares their effects.

Object detection (COCO, CSPResNeXt50-PANet-SPP, 512 × 512 input, Table 4)

Improvement addedAPAP50AP75
None (baseline)38.0%60.0%40.8%
Mosaic39.1%61.8%42.0%
Hyperparameter search with a genetic algorithm38.9%61.7%41.9%
Cosine learning rate schedule38.7%60.7%41.9%
CmBN (collecting batch normalization statistics across multiple mini-batches)38.4%60.7%41.3%
Eliminating grid sensitivity37.7%59.9%40.5%

AP is a measure of object detection accuracy (mAP); higher is better. Among the comparisons that add a single improvement while keeping the box loss as MSE, Mosaic raised AP the most (by 1.1 points). Some improvements, such as Label Smoothing (33.0%), lowered AP in detection.

Image classification (ImageNet, CSPResNeXt-50, Table 2)

Data augmentationtop-1top-5
None (baseline)77.9%94.0%
Mixup77.2%94.0%
CutMix78.0%94.3%
Mosaic78.1%94.5%
CutMix + Mosaic + Label Smoothing78.5%94.8%

The improvement in classification was small, at 0.2 points. The paper adopts CutMix, Mosaic, and Label Smoothing as the combination used to train the classifier (backbone).

Effect of mini-batch size (COCO, Table 7)

With the full set of improvements including Mosaic (BoF and BoS), the AP difference between mini-batches of 4 and 8 was 0.1 points (41.6% vs. 41.7%). Without them, the difference was 1.3 points (37.1% vs. 38.4%). Note, however, that this comparison adds the improvements together, so it does not isolate the effect of Mosaic alone.

Caveats

Move the boxes correctly along with the images: Because Mosaic cuts and pastes images, box coordinates must be shifted to match where each image was pasted, and any part extending beyond the canvas or image edges must be clipped. If only the images are pasted and the boxes are not moved, the ground-truth positions are off and training does not go well.

  • Decide how to handle boxes that were cut down to small sizes: When most of an object is cut off at a seam, its box becomes very thin. Whether to keep such boxes as ground truth or remove them is set in the implementation's configuration.
  • Images look different from test images: Images built by Mosaic have seams and tend to show objects small, so they look different from the single photos seen at test time. Mosaic is not applied at evaluation and inference; a single image is fed in as is.
  • Treat the canvas size and the final crop as a pair: MMDetection's Mosaic outputs a 2s×2s2s \times 2s image, so unless a crop or resize transform follows, the input size doubles.
  • The effect on classification is small: In the paper's image classification experiment, top-1 improved by 0.2 points. Consider it mainly a data augmentation for object detection.

Comparison with similar data augmentation methods and how to choose

The table below lines up Mosaic with data augmentation methods that mix or mask images from the same angles.

MethodNumber of images mixedWhat it doesHow the ground truth is builtMain use
Mixup2Adds pixel by pixelMixes labels by the ratioClassification
CutMix2Replaces a rectangular region with another imageMixes labels by area ratioClassification
Cutout1Fills a rectangular regionUnchangedClassification
Mosaic4Stitches images in a 2 × 2 layoutShifts and combines the boxes of the four imagesObject detection
Copy-Paste2Pastes object-shaped regions onto another imageAdds ground truth for the pasted objectsInstance segmentation

Rough guidelines for choosing:

  • Training object detection (especially YOLO-family models): Use Mosaic. In the YOLOv4 comparison, it raised AP the most among improvements added individually.
  • Limited GPU memory makes large mini-batches impossible: Mosaic is a candidate. The paper cites as an advantage that batch normalization statistics can be computed from four images' worth of data.
  • Image classification: CutMix and Mixup are the standard choices. In the paper's classification experiments, Mosaic's improvement was small.

PyTorch example

Show code
python
import random
import torch


def mosaic(images, boxes_list, s=640, pad_val=114):
    """Mosaic that lays out 4 images on a 2s × 2s canvas (same placement as load_mosaic in Ultralytics YOLOv5).

    images:     4 images resized so the longer side is s. Each is a (C, h, w) uint8 tensor
    boxes_list: boxes for each of the 4 images. Each is an (N, 5) tensor [class, x1, y1, x2, y2] (pixel coordinates)
    returns:    a (C, 2s, 2s) image and the combined boxes (M, 5)
    """
    c = images[0].shape[0]
    canvas = torch.full((c, 2 * s, 2 * s), pad_val, dtype=images[0].dtype)
    xc = int(random.uniform(0.5 * s, 1.5 * s))   # center (where the 4 images meet)
    yc = int(random.uniform(0.5 * s, 1.5 * s))
    out_boxes = []
    for i, (img, boxes) in enumerate(zip(images, boxes_list)):
        _, h, w = img.shape
        if i == 0:    # upper left: align bottom-right corner with center
            x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc
            x1b, y1b = w - (x2a - x1a), h - (y2a - y1a)
        elif i == 1:  # upper right: align bottom-left corner with center
            x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, 2 * s), yc
            x1b, y1b = 0, h - (y2a - y1a)
        elif i == 2:  # lower left: align top-right corner with center
            x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(2 * s, yc + h)
            x1b, y1b = w - (x2a - x1a), 0
        else:         # lower right: align top-left corner with center
            x1a, y1a, x2a, y2a = xc, yc, min(xc + w, 2 * s), min(2 * s, yc + h)
            x1b, y1b = 0, 0
        x2b, y2b = x1b + (x2a - x1a), y1b + (y2a - y1a)
        canvas[:, y1a:y2a, x1a:x2a] = img[:, y1b:y2b, x1b:x2b]   # discard what extends beyond

        # shift boxes by the placement offset and clip outside the placed region
        b = boxes.clone().float()
        b[:, [1, 3]] = (b[:, [1, 3]] + (x1a - x1b)).clamp(x1a, x2a)
        b[:, [2, 4]] = (b[:, [2, 4]] + (y1a - y1b)).clamp(y1a, y2a)
        keep = (b[:, 3] - b[:, 1] > 2) & (b[:, 4] - b[:, 2] > 2)   # drop boxes that were almost cut away (threshold is an example)
        out_boxes.append(b[keep])
    return canvas, torch.cat(out_boxes, 0)


# After this, crop the central s × s region of the canvas with a scaling/translation transform (e.g., random_perspective in YOLOv5).
# Use Mosaic only when loading training data; at evaluation and inference, feed a single image as is.

FAQ

Q. Can Mosaic be used for tasks other than object detection?
A.

It can also be used for image classification, but in the YOLOv4 paper's ImageNet experiment the top-1 accuracy improvement was small, at 0.2 points (77.9% → 78.1%). It is a data augmentation whose effect is large in object detection, where the ground truth is boxes.

Q. Can nine images or some other number be used instead of four?
A.

The YOLOv4 paper describes Mosaic with four images. Using more images makes each object even smaller. The effect of other numbers is not examined in the paper, so verify it on validation data if you use one.

Q. How does it differ from CutMix?
A.

CutMix swaps part of one image with another and mixes the classification labels by area ratio. Mosaic arranges four images in a 2 × 2 layout and shifts the object detection boxes to match where each image was pasted. They differ in the number of images mixed and in how the ground truth is built.

References

  1. Bochkovskiy, A., Wang, C.-Y., & Liao, H.-Y. M. (2020). YOLOv4: Optimal Speed and Accuracy of Object Detection. arXiv:2004.10934.
  2. Ultralytics YOLOv5 (load_mosaic in utils/dataloaders.py)
  3. MMDetection (Mosaic in mmdet/datasets/transforms/transforms.py)