Copy-Paste is a data augmentation technique that cuts objects out of one image along their exact shapes and pastes them onto another image to create new training images. It is used with instance segmentation data, where the region (mask) of each object is known. This article focuses on "Simple Copy-Paste," systematically studied by Ghiasi et al. in 2021.
The idea of cutting out objects and pasting them onto backgrounds existed earlier: Dwibedi et al. (2017) synthesized training images from object and background materials. Dvornik et al. (2018) and InstaBoost (2019) proposed choosing paste locations that match the surrounding context. The Simple Copy-Paste paper showed that simply pasting randomly selected objects as is, without considering context, works well enough. Accuracy improves even with images where a giraffe and a soccer player stand side by side at mismatched scales.
The composite image I is created by the following formula.
I=I1×α+I2×(1−α)
Here, I1 is the source image from which objects are cut out, I2 is the main image being pasted onto, and α is a binary mask that is 1 only where pasted objects are.
As an analogy, it is like a collage made from magazine clippings. Wherever something is pasted, its outline and name are known exactly, so the result is directly "a new photo with ground truth."
Mixup mixes whole images, while CutMix and Mosaic mix rectangular regions. Copy-Paste copies only the pixels within an object's shape, so each object's ground truth (mask, box, class) carries over directly.
Procedure
One training image is created by the following steps (left of the top figure).
Randomly pick two images from the training data.
Apply scale jitter (random scaling and cropping) and horizontal flipping to each of the two images independently.
From one image (the source I1), select a random subset of objects.
Paste the selected objects onto the other image (the main image I2). Their positions are kept as they are in the jittered I1.
Fix the ground truth. Remove objects fully occluded by pasted objects from the ground truth, and adjust the masks and boxes of partially occluded objects to their visible parts. Add the ground truth of the pasted objects as is.
Train a model such as Mask R-CNN on the resulting image and ground truth as usual.
To smooth the edges of pasted objects, the paper also uses "blending," which applies a Gaussian filter to α. However, results were the same without blending (box AP 50.0, mask AP 43.7).
The paper uses the following two kinds of scale jitter. Both include horizontal flipping, and images scaled down below the original size are padded with gray.
Name
Scaling range
Usage
Standard scale jitter (SSJ)
0.8–1.25× the original size
The range used in much prior work
Large scale jitter (LSJ)
0.1–2.0× the original size
The paper's default setting; used together with Copy-Paste
Select a random subset of objects, neither all nor just one. In COCO experiments (EfficientNet-B7 FPN, 640 × 640), pasting a random subset gave box AP 50.0, while pasting only one dropped it to 49.1 and pasting all to 49.7.
Why it works
The paper explains the strengths of Copy-Paste as follows.
The number of combinations is enormous: Combinations of which two images are picked, which objects are copied, and where they are pasted (which varies with jitter) yield a practically unlimited number of new training images. No extra labeling is needed. The paper notes that labeling 1,000 instance masks on COCO took 22 hours, illustrating how costly it is to add data.
It is an object-aware augmentation: Unlike generic augmentations such as scaling or color changes, it modifies images along object classes and shapes. It changes combinations of backgrounds, occlusions, and scales while keeping object ground truth exact.
Harder classes gain more: Comparing AP for each of COCO's 80 classes, Copy-Paste improved AP for every class except hair drier, and classes with lower original AP tended to gain more.
Pasting without regard to context can produce "impossible" images, such as indoor objects pasted into outdoor scenes. When the paper examined COCO, about half (46.8%) of the generated images were indoor/outdoor mismatches. Since accuracy still improves, the paper concludes that the effort of matching context is unnecessary.
Results reported in the paper
Results of adding Copy-Paste to a strong baseline using only large scale jitter (LSJ) on COCO (Mask R-CNN, AP, %) are shown below. Averaged over seven settings, box AP rose by 1.3 and mask AP by 0.8.
In experiments varying the amount of training data, Copy-Paste always improved accuracy. When training on only 10% of COCO, box AP rose by 6.9 on top of SSJ and by 4.8 on top of LSJ. Moreover, a model using Copy-Paste and LSJ on 75% of COCO achieved about the same AP as a model using only LSJ on 100%. In contrast, Mixup helped only when data was scarce and gave no improvement when combined with LSJ.
It is also additive with self-training, which trains on unlabeled images with pseudo-labels (EfficientNet-B7 FPN, 640).
Setting
Box AP
Mask AP
Baseline
48.5
42.7
Self-training
50.0
44.0
Copy-Paste
50.0
43.7
Self-training + Copy-Paste
51.4
45.0
The largest model (Cascade EfficientNet-B7 NAS-FPN, 1280), combined with self-training, reached box AP 57.3 and mask AP 49.1 on COCO test-dev (without test-time augmentation).
On LVIS v1.0, whose 1,203 classes follow a long-tailed distribution, the effect was especially strong for rare classes.
Model (image size)
Mask AP
Rare-class mask AP (APr)
ResNet-50 FPN (1024)
30.3 → 32.3
22.2 → 26.5
EfficientNet-B7 NAS-FPN (1280)
34.7 → 38.1
26.0 → 32.1
The APr of 32.1 for EfficientNet-B7 NAS-FPN exceeded the LVIS Challenge 2020 winning team (28.5, without test-time augmentation) by 3.6.
Practical considerations
Per-object masks are required. Because objects are cut out along their shapes, data with only boxes (object detection data) cannot be used as is.
Do not forget to fix the ground truth. Leaving ground truth for objects hidden under pasted objects would ask the model to find objects that are not visible. Remove fully occluded objects and fix the masks and boxes of partially occluded ones.
Combining with large scale jitter increases the effect. The paper's appendix shows that applying LSJ to the main image is especially important, while widening the range for the source image has only a small effect (0.3 box AP).
Training may need to be longer. The paper trained until validation performance stopped improving; training from scratch with LSJ and Copy-Paste took 576 epochs (96 epochs with SSJ alone). Still, improvements appear even with typical training lengths of 24–36 epochs.
Training and inference compute do not increase. Compositing is done during data loading, and the model is unchanged.
The core PyTorch and torchvision libraries have no Copy-Paste transform. torchvision has transforms.v2.ScaleJitter, which corresponds to the paper's large scale jitter (default scale_range is (0.1, 2.0)). Copy-Paste itself is in torchvision's object detection reference code (SimpleCopyPaste in references/detection), which pastes objects from the neighboring image within a mini-batch. The implementation example below is a compact version of that procedure.
Comparison with similar methods and how to choose
The following table compares data augmentation methods that "mix multiple images" from the same perspectives.
Method
Number of images mixed
What is copied
How ground truth is built
Main use
Copy-Paste
2
Only the pixels within object shapes
Add pasted objects' ground truth and fix occluded objects' ground truth
Training instance segmentation or object detection on data with per-object masks: Use Copy-Paste. The effect is especially large when data is scarce or there are rare classes.
Training object detection (e.g., the YOLO family) on box-only data: Use Mosaic.
Image classification: Use CutMix or Mixup.
Another notable feature of Copy-Paste is that it is additive with other methods such as large scale jitter and self-training.
PyTorch example
▶Show code
python
import torch
import torchvision
from torchvision import ops, tv_tensors
from torchvision.datasets import CocoDetection, wrap_dataset_for_transforms_v2
from torchvision.models.detection import maskrcnn_resnet50_fpn
from torchvision.transforms import v2
import torchvision.transforms.v2.functional as F
from torch.utils.data import DataLoader
"""
COCO instance segmentation (train Mask R-CNN with Copy-Paste)
A compact version of the same procedure as torchvision's reference code (SimpleCopyPaste in references/detection)
"""
# Hyperparameters
batch_size = 4 # batch size
epochs = 1 # number of epochs
learning_rate = 0.02 # learning rate
image_size = 640 # training image size (the paper's small setting is 640 × 640)
blending = True # whether to blur the edges of pasted objects (the paper got the same results without it)
# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
# Large scale jitter (LSJ): scale by 0.1–2.0×, crop to a fixed size (pad where short). Horizontal flip is also used
train_transform = v2.Compose([
v2.ToImage(),
v2.RandomHorizontalFlip(),
v2.ScaleJitter(target_size=(image_size, image_size), scale_range=(0.1, 2.0)),
v2.RandomCrop(image_size, pad_if_needed=True, fill=114),
v2.ToDtype(torch.float32, scale=True),
v2.SanitizeBoundingBoxes(), # remove ground truth of objects cropped out
])
# Change the COCO image and annotation paths to match your environment
dataset = CocoDetection('./coco/train2017', './coco/annotations/instances_train2017.json', transforms=train_transform)
dataset = wrap_dataset_for_transforms_v2(dataset, target_keys=['boxes', 'labels', 'masks'])
def copy_paste(image, target, paste_image, paste_target):
# image, paste_image: [3, H, W] (same size). target masks: [N, H, W], boxes: [N, 4], labels: [N]
n = len(paste_target['masks'])
if n == 0:
return image, target
# Randomly pick a subset of source objects (neither all nor just one)
pick = torch.unique(torch.randint(0, n, (n,)))
paste_masks = paste_target['masks'][pick].bool()
alpha = paste_masks.any(dim=0) # α: 1 only where pasted objects are
a = alpha[None].float()
if blending:
a = F.gaussian_blur(a, kernel_size=[5, 5], sigma=[2.0])
image = paste_image * a + image * (1 - a) # I = I1 × α + I2 × (1 − α)
# Fix the main image's ground truth: remove occluded parts from masks, drop fully occluded objects
masks = target['masks'].bool() & ~alpha
keep = masks.flatten(1).any(dim=1)
masks = masks[keep]
boxes = ops.masks_to_boxes(masks) if len(masks) else torch.zeros(0, 4)
out = {
'masks': torch.cat([masks, paste_masks]).to(torch.uint8),
'boxes': torch.cat([boxes, paste_target['boxes'][pick].as_subclass(torch.Tensor)]),
'labels': torch.cat([target['labels'][keep], paste_target['labels'][pick]]),
}
return image, out
def collate_with_copy_paste(batch):
images = [img for img, _ in batch]
targets = [{'masks': t['masks'].as_subclass(torch.Tensor), 'boxes': t['boxes'].as_subclass(torch.Tensor), 'labels': t['labels']} for _, t in batch]
# Within the mini-batch, use the image shifted by one as the source (same as the reference code)
rolled = list(zip(images[-1:] + images[:-1], targets[-1:] + targets[:-1]))
out_images, out_targets = [], []
for (img, tgt), (p_img, p_tgt) in zip(zip(images, targets), rolled):
img, tgt = copy_paste(img, tgt, p_img, p_tgt)
out_images.append(img)
out_targets.append(tgt)
return out_images, out_targets
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_with_copy_paste)
model = maskrcnn_resnet50_fpn(weights=None, weights_backbone=None, num_classes=91).to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=4e-5)
# Training: in train() mode, Mask R-CNN takes images and targets and returns a dict of losses
model.train()
for epoch in range(epochs):
for images, targets in loader:
images = [img.to(device) for img in images]
targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
losses = model(images, targets)
loss = sum(losses.values())
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Inference: in eval() mode, it takes only images and returns per-object boxes, classes, and masks. Copy-Paste is not used
model.eval()
with torch.no_grad():
image, _ = dataset[0]
pred = model([image.to(device)])[0]
print(pred['boxes'].shape, pred['masks'].shape)
FAQ
Q. Do paste locations need to match the surrounding context?
A.
Not according to the Simple Copy-Paste paper. Simply selecting objects at random and pasting them at their positions in the jittered image improved the accuracy of a strong baseline. On COCO, about half of the generated images were indoor/outdoor mismatches, yet the method was still effective.
Q. Can it be used for object detection (box-only ground truth)?
A.
Per-object masks are needed to cut objects out along their shapes. The paper's experiments were run on COCO and LVIS, which have masks, and box AP also improved. To mix images with box-only data, Mosaic is a candidate.
Q. Which is better, Copy-Paste or Mixup?
A.
For instance segmentation, Copy-Paste was more effective in the paper's comparison. Mixup helped only when data was scarce and gave no improvement when combined with large scale jitter, whereas Copy-Paste raised AP at every data size and on top of either scale jitter.