How to Configure Data Augmentation Techniques in YOLOv5 Training

You configure data augmentation in YOLOv5 by editing probability values in a hyper-parameter YAML file (e.g., data/hyps/hyp.scratch-med.yaml) and enabling the --augment flag during training, which triggers the augmentation pipeline in utils/dataloaders.py.

The Ultralytics YOLOv5 repository provides a flexible, YAML-driven system for controlling how training images are transformed. By adjusting probabilities and strength coefficients, you can tune the balance between regularization and fidelity without modifying Python source code. This guide explains exactly where these settings live, how the pipeline applies them, and how to customize them for your dataset.

Where YOLOv5 Stores Augmentation Settings

Hyper-parameter YAML Files

Augmentation probabilities and strength coefficients are stored in the data/hyps/ directory. Files such as hyp.scratch-med.yaml expose tunable variables that the dataloader consumes at runtime:

hsv_h: 0.015          # hue jitter fraction (0-1)

hsv_s: 0.7            # saturation jitter fraction

hsv_v: 0.4            # value jitter fraction

mosaic: 1.0           # mosaic probability (0-1)

mixup: 0.1            # mixup probability

copy_paste: 0.0       # copy-paste probability (segmentation only)

When you launch training with --hyp data/hyps/custom.yaml, YOLOv5 loads these values into the hyp dictionary that controls every stochastic transform.

The --augment Flag

The --augment command-line argument (defaulting to True in train.py) sets the augment parameter when constructing the LoadImagesAndLabels dataloader in utils/dataloaders.py. Without this flag set to True, the pipeline skips all random augmentations and returns only letterboxed images.

Core Augmentation Techniques in YOLOv5

Mosaic and Mosaic9 Compositing

Mosaic combines four training images into a single composite, forcing the model to learn object detection across non-natural boundaries. In utils/dataloaders.py (lines 771–777), the dataloader checks the hyper-parameter probability before invoking load_mosaic():

if mosaic := self.mosaic and random.random() < hyp["mosaic"]:
    img, labels = self.load_mosaic(index)

Mosaic9 extends this to nine images (lines 931–939) and is controlled by the mosaic9 key in your YAML file.

MixUp and Copy-Paste

MixUp blends two images with random weighting to improve generalization. The dataloader applies it immediately after Mosaic when random.random() < hyp["mixup"] (lines 777–782):

if random.random() < hyp["mixup"]:
    img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, len(self.labels) - 1)))

Copy-Paste (segmentation only) copies object masks from one image to another. It resides in utils/segment/augmentations.py (lines 236–247) and triggers when hyp["copy_paste"] exceeds a random threshold.

HSV Color Jitter and Geometric Transforms

HSV augmentation shifts hue, saturation, and value according to the hsv_h, hsv_s, and hsv_v coefficients. The implementation in utils/augmentations.py (lines 73–86) converts the image to HSV space, applies random gains, and clips the result.

Random perspective (rotation, scale, shear, translation) is handled by random_perspective() in utils/augmentations.py (lines 152–192). The dataloader invokes this whenever self.augment is True, using degrees and translation values from the hyper-parameter dictionary.

Customizing Your Augmentation Pipeline

Editing the Hyper-parameter YAML

Create a custom file (e.g., data/hyps/custom.yaml) and adjust probabilities to suit your dataset. Lower mosaic for small objects that get lost in compositing, or increase hsv_h for datasets with variable lighting.

Command-line Training Example

Pass your custom YAML and ensure augmentation is active:

python train.py \
  --data coco.yaml \
  --cfg yolov5s.yaml \
  --weights '' \
  --batch 16 \
  --epochs 100 \
  --img 640 \
  --hyp data/hyps/custom.yaml \
  --augment

Python API Usage

For programmatic control, load the YAML and pass it to create_dataloader:

from utils.dataloaders import create_dataloader
import yaml

# Load custom hyperparameters

with open('data/hyps/custom.yaml') as f:
    hyp = yaml.safe_load(f)

# Build loader with augmentation enabled

train_loader, dataset = create_dataloader(
    path='train/images',
    imgsz=640,
    batch_size=16,
    stride=32,
    hyp=hyp,               # augmentation probabilities

    augment=True,          # enable pipeline

    cache=False,
    rect=False,
    workers=8,
    prefix='train: '
)

Debugging and Manual Augmentation Testing

To verify augmentation behavior without running full training, invoke individual functions from utils/augmentations.py:

import cv2
import numpy as np
from utils.augmentations import augment_hsv, random_perspective

# Load a sample image

img = cv2.imread('sample.jpg')  # BGR format

# Test HSV jitter with default training gains

img_hsv = augment_hsv(img.copy(), hgain=0.015, sgain=0.7, vgain=0.4)

# Test geometric augmentation

labels = np.array([[0, 0.5, 0.5, 0.2, 0.2]])  # [class, x_center, y_center, w, h]

img_geo, labels_geo = random_perspective(
    img_hsv,
    targets=labels,
    degrees=0.0,
    translate=0.1,
    scale=0.9,
    shear=0.0,
    perspective=0.0,
    border=(0, 0)
)

cv2.imwrite('augmented_sample.jpg', img_geo)

Summary

  • Hyper-parameter YAML files (data/hyps/*.yaml) control augmentation probabilities and strengths such as mosaic, mixup, hsv_h, and copy_paste.
  • The --augment flag in train.py enables the augmentation pipeline in utils/dataloaders.py, specifically within the LoadImagesAndLabels class.
  • Mosaic, MixUp, and Copy-Paste are applied stochastically based on YAML probabilities in utils/dataloaders.py (lines 771–782 and 931–939).
  • HSV jitter and geometric transforms (rotation, scale, shear) are implemented in utils/augmentations.py (lines 73–86 and 152–192) and invoked when augment=True.
  • Customization involves editing YAML values and passing the file via --hyp, or programmatically setting augment=True and supplying a custom hyp dictionary to create_dataloader.

Frequently Asked Questions

What is the default augmentation setting in YOLOv5?

By default, train.py sets --augment to True, which enables the full augmentation pipeline defined in the hyper-parameter YAML file (usually hyp.scratch-low.yaml or hyp.scratch-med.yaml). This includes Mosaic (probability 1.0), HSV jitter, and random geometric transforms.

How do I disable Mosaic augmentation in YOLOv5?

To disable Mosaic, set mosaic: 0.0 in your custom hyper-parameter YAML file and pass it to training with --hyp custom.yaml. Alternatively, you can disable all augmentations by omitting the --augment flag or setting augment=False when constructing the dataloader programmatically.

Can I use Copy-Paste augmentation for object detection (not segmentation)?

No. According to the source code in utils/segment/augmentations.py (lines 236–247), Copy-Paste is implemented only for segmentation masks. It requires polygonal annotation data and is controlled by the copy_paste hyper-parameter, which defaults to 0.0 in standard detection configs.

Where are the augmentation functions implemented in the YOLOv5 source code?

Core image transformations reside in utils/augmentations.py, including augment_hsv() (lines 73–86) for color jitter and random_perspective() (lines 152–192) for geometric warping. The dataloader logic that orchestrates Mosaic, MixUp, and Copy-Paste is located in utils/dataloaders.py within the LoadImagesAndLabels class (lines 771–782 and 931–939).

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →