Get Started

Data Preprocessing Techniques for Annotated Computer Vision Data

Data preprocessing turns raw, annotated images into the clean and consistent inputs a computer vision model needs to train well. With Ultralytics YOLO26, the core pixel operations — RGB conversion, scaling to [0, 1], and resizing — run automatically inside the training pipeline, so the work that remains is splitting your dataset correctly, balancing classes, and choosing augmentations. This guide covers those essential techniques: resizing, normalization, dataset splitting, data augmentation, exploratory data analysis (EDA) with a runnable dataset audit, and fixing class imbalance.



Watch: How to Use Data Preprocessing and Augmentation to Improve Model Accuracy in Real-World Scenarios 🚀

This step comes after you've defined your project's goals and collected and annotated your data, and it sits early in the computer vision project workflow.

Why Preprocessing Matters#

Preprocessing gets your data into a format that reduces computational load and improves model performance. It addresses three common issues in raw data:

  • Noise: Irrelevant or random variations in the data.
  • Inconsistency: Variations in image sizes, formats, and quality.
  • Imbalance: Unequal distribution of classes or categories across the dataset.

Preprocessing Techniques#

The main techniques are resizing, normalization, dataset splitting, and augmentation. With YOLO26 the first two are automatic, while splitting and augmentation are where your choices matter most.

Resizing Images#

Many models require a consistent input size, so resizing makes images uniform and reduces computational complexity. Two common interpolation methods are:

  • Bilinear Interpolation: Smooths pixel values by taking a weighted average of the four nearest pixels.
  • Nearest Neighbor: Copies the nearest pixel value without averaging — faster, but produces a blockier image.

Libraries like OpenCV and PIL (Pillow) provide these functions, but with YOLO26 you usually don't resize manually. The imgsz argument handles it. On the fixed-size square path, validation and inference letterbox images toward an imgsz × imgsz input such as 640 × 640, preserving the aspect ratio and padding with gray (value 114). Larger images are scaled down to fit, while smaller images are not enlarged when scale-up is disabled. On the default training path, mosaic=1.0 instead tiles four images onto a larger canvas and crops back to imgsz; once close_mosaic disables mosaic for the final epochs, images are letterboxed and then still randomly transformed rather than passed through untouched. Rectangular batches (rect=True) and multi_scale use different input shapes.

Normalizing Pixel Values#

Normalization scales pixel values to a standard range, which helps the model converge faster during training. Two common techniques are:

  • Min-Max Scaling: Scales pixel values to a range of 0 to 1.
  • Z-Score Normalization: Scales pixel values based on their mean and standard deviation.

YOLO26 handles normalization automatically as part of its preprocessing pipeline: it converts images to RGB and scales pixel values to the range [0, 1] by dividing by 255 (min-max scaling). YOLO does not apply ImageNet-style mean/standard-deviation (z-score) normalization by default, so no manual normalization step is required.

Splitting the Dataset#

Splitting the data into training, validation, and test sets lets you evaluate the model on unseen data and measure its generalization. A common split is 70% for training, 20% for validation, and 10% for testing. Tools like scikit-learn or TensorFlow make this straightforward.

Keep these points in mind when splitting:

  • Maintain class distribution: Ensure each class is represented proportionally across the training, validation, and test sets.
  • Balance classes: For imbalanced datasets, rebalance the training set only, never validation or test. See Handling Class Imbalance for the order of fixes.
Avoid data leakage

Split the dataset before applying any augmentation or other preprocessing, and apply those transforms only to the training set. Augmenting before the split lets information from the validation or test images influence training, producing misleadingly high scores that collapse on real-world data.

Augmenting the Dataset#

Data augmentation artificially increases the size of a dataset by creating modified versions of existing images. It helps reduce overfitting and improves generalization, with several benefits:

  • More robust models: Variations in lighting, orientation, and scale make the model resilient to real-world distortions.
  • Cost-effective: You expand the training set without collecting and labeling new data.
  • Better use of data: Every annotated image yields multiple training variations.

Examples of data augmentation techniques including flips, rotations, scaling, and color adjustments applied to a sample image

With YOLO26, augmentation strength is controlled through training arguments passed to model.train() or the equivalent CLI flags, not by editing the dataset YAML, which defines dataset metadata such as paths, class names, and splits. The one exception is flip_idx: pose datasets declare it in the dataset YAML to map left/right keypoint pairs, and YOLO disables fliplr and flipud entirely when it is missing. The built-in augmentations include:

  • Mosaic, MixUp, and CutMix (mosaic, mixup, cutmix): Combine multiple images into one training sample.
  • Flips (fliplr, flipud): Mirror images horizontally or vertically.
  • Geometric transforms (degrees, translate, scale, shear, perspective): Rotate, shift, zoom, and warp images.
  • HSV color jitter (hsv_h, hsv_s, hsv_v): Vary hue, saturation, and brightness.
  • Copy-paste (copy_paste): Paste extra copies of segmented objects, mirrored within the same image by default or taken from another image with copy_paste_mode=mixup.
  • Channel swap (bgr): Swap the RGB channel order to BGR.
  • Classification transforms (auto_augment, erasing): Apply an automated augmentation policy and random erasing when training a classifier.
Set augmentation strength when training
from ultralytics import YOLO

model = YOLO("yolo26n.pt")

# Augmentation is configured with training arguments, not the dataset YAML
model.train(data="coco8.yaml", epochs=10, hsv_h=0.015, fliplr=0.5, mosaic=1.0, degrees=10.0)

For the full list of augmentation arguments and their default values, see the augmentation settings reference and the dedicated YOLO data augmentation guide. If the albumentations package is installed, YOLO also enables its built-in Albumentations-based augmentations automatically.

A Case Study: Preprocessing for Vehicle Detection#

Consider a project to detect and classify vehicles in traffic images with YOLO26, starting from images annotated with bounding boxes and labels. Here is what each preprocessing decision looks like:

  • Resizing: No manual work — YOLO26 resizes to imgsz during training.
  • Normalization: No manual work — YOLO26 scales pixel values to [0, 1] automatically.
  • Splitting: Divide the dataset into 70% training, 20% validation, and 10% testing, keeping the class distribution consistent across splits.
  • Augmentation: Set training arguments suited to traffic scenes — for example fliplr for direction invariance, hsv_v for day/night lighting, and mosaic for varied object density.

With these decisions made, the dataset is ready for Exploratory Data Analysis (EDA).

Exploratory Data Analysis (EDA)#

EDA uses statistics and visualizations to reveal patterns and distributions in your data, helping you catch issues like class imbalance or outliers before training.

Statistical EDA Techniques#

Statistical EDA starts with basic metrics — mean, median, standard deviation, and range — computed over properties such as pixel-intensity distributions. These give a quick overview of your dataset's quality and surface irregularities early.

Audit Labels with a Script#

Counting labels catches the problems that hurt training most before you spend GPU time on them: classes with far fewer instances than the rest, classes that appear in validation but never in training, and byte-identical images that inflate counts or leak across splits. This script loads each split through the same YOLODataset class that training uses, so it reads a data YAML whose splits are folders, .txt image lists, or lists of either.

Audit a dataset before training
import hashlib
from collections import Counter
from pathlib import Path

from ultralytics.data import YOLODataset
from ultralytics.data.utils import check_det_dataset

data = check_det_dataset("coco8.yaml")  # swap in your data YAML
counts, seen = {}, {}
for split in ("train", "val"):
    dataset = YOLODataset(img_path=data[split], data=data, task="detect", augment=False)  # or segment, pose, obb
    counts[split] = Counter()
    for label in dataset.labels:
        counts[split].update(label["cls"].flatten().astype(int).tolist())
        digest = hashlib.md5(Path(label["im_file"]).read_bytes()).hexdigest()
        if digest in seen:  # byte-identical image, within or across splits
            print(f"duplicate image: {label['im_file']} == {seen[digest]}")
        seen[digest] = label["im_file"]

train, val = counts["train"], counts["val"]
print(f"{'class':<14}{'train':>6}{'val':>6}")
for i, name in data["names"].items():
    if train[i] or val[i]:
        print(f"{name:<14}{train[i]:>6}{val[i]:>6}{'  <- val only' if not train[i] else ''}")
print(f"largest/smallest train class: {max(train.values()) / min(train.values()):.0f}x")

On COCO8, an 8-image smoke-test set where these gaps are expected, the output shows five val-only classes and a 4x imbalance between train classes:

class          train   val
person             0    10  <- val only
dog                0     1  <- val only
horse              0     2  <- val only
elephant           0     2  <- val only
zebra              1     0
giraffe            2     0
umbrella           0     1  <- val only
bowl               3     0
orange             4     0
broccoli           1     0
potted plant       1     1
vase               1     0
largest/smallest train class: 4x

A val only class is scored during validation but has no training examples, so the model can't learn it from your data: move some of its images into training or collect more. A train class well below the per-class targets in Handling Class Imbalance, or a high largest-to-smallest ratio, means the classes are imbalanced. The Dataset Quality Control lesson in Ultralytics Academy extends this audit with invalid class IDs, tiny boxes, and a model-assisted search for missing labels.

Visual EDA Techniques#

Visualizations reveal patterns that summary statistics miss, such as class imbalance and outliers. Common tools include:

  • Histograms and box plots: Show the distribution of pixel values and flag outliers in intensity or feature distributions.
  • Bar charts: Reveal class imbalance by comparing how many examples each class has.
  • Scatter plots: Explore relationships between image features or annotations.
  • Heatmaps: Visualize pixel-intensity distributions or the spatial distribution of annotations across images.

Ultralytics Platform for EDA#

For a no-code approach to EDA, upload your dataset to Ultralytics Platform. The dataset's Charts tab automatically generates key EDA visualizations: split distribution, top class counts, image width/height histograms, and 2D heatmaps of annotation positions and image dimensions. The Images tab lets you browse your data in grid, compact, or table views with annotation overlays, making it easy to spot mislabeled examples or unbalanced classes without writing any code.

Handling Class Imbalance#

Class imbalance means some classes have far fewer labeled instances than others, for example 8,000 forklifts and 700 pallets. The model then sees the rare class too seldom to learn it, so that class's AP and recall trail the common classes. Measure it with the audit script or the Platform Charts tab, then confirm the effect after a first training run with the per-class rows of the validation results.

Fix it in this order:

  1. Collect and label more of the rare class. New, varied examples are the only fix that adds information. As a target, aim for at least 1,500 images and 10,000 labeled instances per class, per the tips for best training results.
  2. Oversample it in the training split only. Point train: in your data YAML at a .txt file of image paths, one per line, and list the images that contain the rare class two or three times. YOLO keeps repeated entries, so each epoch sees those images more often, and augmentation makes each repeat look different. Never copy images into validation or test, and run the audit on the split before you add the repeats, since it reports them as duplicate images.
  3. Weight the loss. The cls_pw training argument weights the classification loss by inverse class frequency, so mistakes on rare classes cost more. See how to train on an imbalanced dataset for its values, formula, and starting points.

Conclusion#

Properly split, normalized, and augmented data reduces noise and improves generalization, turning a raw collection of images into a dependable training set. With your dataset preprocessed, the next step is to train your model. If questions come up along the way, ask the community on the Ultralytics GitHub repository or the Ultralytics Discord server.

FAQ#

  • Preprocessing ensures your data is clean, consistent, and in a format optimized for training. By addressing noise, inconsistency, and class imbalance in raw data, steps like resizing, normalization, augmentation, and dataset splitting reduce computational load and improve model performance. See the steps of a computer vision project for how it fits into the broader workflow.

  • Configure augmentation through training arguments rather than the dataset YAML. Pass arguments such as fliplr, mosaic, hsv_h, and degrees to model.train() (or the equivalent CLI flags) to set the probability and strength of each transform. These are defined in the augmentation settings and explained in the YOLO data augmentation guide. Pose datasets are the exception: their flip_idx keypoint mapping lives in the dataset YAML, and flips are disabled without it.

  • The two most common techniques are min-max scaling (rescaling pixels to a range of 0 to 1) and z-score normalization (rescaling based on mean and standard deviation). YOLO26 applies min-max scaling automatically — converting images to RGB and dividing pixel values by 255 — so you don't need a manual normalization step. It does not apply z-score normalization by default.

  • A common practice is 70% for training, 20% for validation, and 10% for testing. Maintain the class distribution across all three splits, and avoid data leakage by applying augmentation only to the training set after the split. Tools like scikit-learn or TensorFlow handle the split efficiently.

  • Yes. The imgsz argument controls the target input size with no manual work. On the fixed-size square path, validation and inference letterbox images toward the specified shape while preserving the aspect ratio; larger images are scaled down to fit, while smaller images are not enlarged when scale-up is disabled. During training, the default mosaic augmentation reaches the target size by tiling four images and cropping instead. Rectangular batches (rect=True) and multi_scale use different input shapes. See the model training documentation for details.

Comments

Ask a question, share your results, or help someone else.