Albumentations Tutorial: Advanced Image Augmentation for Computer Vision

# Albumentations - Augmentasi Gambar Tingkat Lanjut ## Daftar Isi 1. [Pendahuluan](#pendahuluan) 2. [Prasyarat](#prasyarat) 3. [Instalasi dan Pengaturan](#instalasi-dan-pengaturan) 4. [Memahami Pipe...

By Ruby Abdullah · · tutorial
AlbumentationsImage AugmentationComputer VisionData AugmentationPyTorchTraining

Albumentations - Advanced Image Augmentation

Table of Contents

  • Introduction
  • Prerequisites
  • Installation and Setup
  • Understanding the Augmentation Pipeline
  • Geometric Transforms
  • Color Transforms
  • Weather and Environmental Effects
  • Building Complex Pipelines with Compose
  • Integration with PyTorch DataLoader
  • Custom Transforms
  • A/B Testing Augmentation Strategies
  • Benchmark: Albumentations vs torchvision
  • Best Practices
  • Conclusion

  • Introduction

    Image augmentation is one of the most effective regularization techniques in computer vision. By artificially expanding your training dataset with transformed versions of existing images, you can significantly improve model generalization and reduce overfitting.

    Albumentations is a fast, flexible, and feature-rich image augmentation library designed for machine learning practitioners. Built on top of OpenCV and NumPy, it provides over 70 different augmentation transforms and is optimized for performance — often 2-10x faster than alternatives like torchvision or imgaug.

    Key advantages of Albumentations:

    • Speed: Highly optimized with OpenCV backend
    • Richness: 70+ transforms covering geometric, color, weather, and more
    • Flexibility: Works with images, masks, bounding boxes, and keypoints simultaneously
    • Integration: Seamless compatibility with PyTorch, TensorFlow, and other frameworks
    • Reproducibility: Deterministic transforms with seed control

    In this tutorial, you will learn how to build production-quality augmentation pipelines, integrate them into deep learning workflows, write custom transforms, and benchmark performance.


    Prerequisites

    Before starting this tutorial, you should have:

    • Python 3.8 or higher
    • Basic understanding of computer vision concepts
    • Familiarity with PyTorch (for DataLoader integration)
    • Experience with NumPy and image processing basics


    Installation and Setup

    Install Albumentations and its dependencies:

    # Install albumentations with all extras
    

    pip install albumentations[all]

    Or minimal installation

    pip install albumentations

    Additional dependencies for this tutorial

    pip install torch torchvision matplotlib opencv-python-headless

    Verify the installation:

    import albumentations as A
    

    import cv2

    import numpy as np

    print(f"Albumentations version: {A.version}")

    Load a sample image

    image = cv2.imread("sample.jpg")

    image = cv2.cvtColor(image, cv2.COLORBGR2RGB)

    print(f"Image shape: {image.shape}")


    Understanding the Augmentation Pipeline

    Albumentations uses a declarative pipeline approach. You define a sequence of transforms, each with a probability of being applied, and then pass your data through the pipeline.

    import albumentations as A
    

    import cv2

    import numpy as np

    Define a simple pipeline

    transform = A.Compose([

    A.HorizontalFlip(p=0.5),

    A.RandomBrightnessContrast(p=0.3),

    A.Resize(height=256, width=256),

    ])

    Load and transform an image

    image = cv2.imread("sample.jpg")

    image = cv2.cvtColor(image, cv2.COLORBGR2RGB)

    Apply the transform

    result = transform(image=image)

    augmentedimage = result["image"]

    print(f"Original shape: {image.shape}")

    print(f"Augmented shape: {augmentedimage.shape}")

    The pipeline also handles masks, bounding boxes, and keypoints simultaneously:

    # Pipeline with bounding box support
    

    transform = A.Compose([

    A.HorizontalFlip(p=0.5),

    A.RandomCrop(height=300, width=300, p=1.0),

    A.Resize(height=256, width=256),

    ], bboxparams=A.BboxParams(

    format='pascalvoc', # [xmin, ymin, xmax, ymax]

    minvisibility=0.3, # Drop boxes that lose >70% visibility

    labelfields=['classlabels']

    ))

    Apply with bounding boxes

    result = transform(

    image=image,

    bboxes=[[50, 60, 200, 300], [100, 150, 350, 400]],

    classlabels=["cat", "dog"]

    )

    augmentedimage = result["image"]

    augmentedbboxes = result["bboxes"]

    augmentedlabels = result["classlabels"]


    Geometric Transforms

    Geometric transforms modify the spatial structure of an image. These are essential for teaching models to be invariant to position, scale, and orientation.

    # Comprehensive geometric augmentation pipeline
    

    geometrictransforms = A.Compose([

    # Flips

    A.HorizontalFlip(p=0.5),

    A.VerticalFlip(p=0.2),

    # Rotation and affine

    A.Rotate(limit=30, bordermode=cv2.BORDERREFLECT101, p=0.5),

    A.Affine(

    scale=(0.8, 1.2),

    translatepercent={"x": (-0.1, 0.1), "y": (-0.1, 0.1)},

    rotate=(-15, 15),

    shear=(-10, 10),

    p=0.5

    ),

    # Elastic and grid distortions

    A.ElasticTransform(

    alpha=120,

    sigma=120 0.05,

    p=0.3

    ),

    A.GridDistortion(numsteps=5, distortlimit=0.3, p=0.3),

    A.OpticalDistortion(distortlimit=0.05, shiftlimit=0.05, p=0.3),

    # Perspective

    A.Perspective(scale=(0.05, 0.1), p=0.3),

    # Crop and resize

    A.RandomResizedCrop(

    size=(256, 256),

    scale=(0.6, 1.0),

    ratio=(0.75, 1.333),

    p=0.5

    ),

    ])

    Apply to image and mask simultaneously

    result = geometrictransforms(image=image, mask=segmentationmask)

    augimage = result["image"]

    augmask = result["mask"]

    Safe Rotation for Object Detection

    When working with bounding boxes, be careful with large rotations:

    # Safe geometric transforms for detection tasks
    

    detectionsafetransforms = A.Compose([

    A.HorizontalFlip(p=0.5),

    A.Rotate(limit=10, p=0.3), # Small rotations only

    A.RandomResizedCrop(

    size=(512, 512),

    scale=(0.7, 1.0),

    p=0.5

    ),

    A.PadIfNeeded(minheight=512, minwidth=512, p=1.0),

    ], bboxparams=A.BboxParams(

    format='coco', # [xmin, ymin, width, height]

    minarea=1024, # Drop boxes smaller than 32x32

    minvisibility=0.3,

    labelfields=['categoryids']

    ))


    Color Transforms

    Color augmentations teach models to be robust to lighting conditions, camera settings, and color variations.

    colortransforms = A.Compose([
    

    # Brightness and contrast

    A.RandomBrightnessContrast(

    brightnesslimit=0.2,

    contrastlimit=0.2,

    p=0.5

    ),

    # Hue, saturation, value

    A.HueSaturationValue(

    hueshiftlimit=20,

    satshiftlimit=30,

    valshiftlimit=20,

    p=0.5

    ),

    # Color jittering

    A.ColorJitter(

    brightness=0.2,

    contrast=0.2,

    saturation=0.2,

    hue=0.1,

    p=0.3

    ),

    # Channel manipulation

    A.ChannelShuffle(p=0.05),

    A.RGBShift(rshiftlimit=15, gshiftlimit=15, bshiftlimit=15, p=0.3),

    # Tone adjustments

    A.CLAHE(cliplimit=4.0, tilegridsize=(8, 8), p=0.3),

    A.Equalize(p=0.2),

    A.Posterize(numbits=4, p=0.1),

    # Gamma correction

    A.RandomGamma(gammalimit=(80, 120), p=0.3),

    # Convert to grayscale occasionally

    A.ToGray(p=0.05),

    ])

    result = colortransforms(image=image)

    coloraugmented = result["image"]

    Domain-Specific Color Augmentations

    # Medical imaging: subtle color shifts
    

    medicalcolor = A.Compose([

    A.RandomBrightnessContrast(brightnesslimit=0.1, contrastlimit=0.1, p=0.5),

    A.CLAHE(cliplimit=2.0, p=0.3),

    A.GaussianBlur(blurlimit=(3, 5), p=0.2),

    ])

    Satellite imagery: strong color variation

    satellitecolor = A.Compose([

    A.RandomBrightnessContrast(brightnesslimit=0.3, contrastlimit=0.3, p=0.7),

    A.HueSaturationValue(hueshiftlimit=30, satshiftlimit=40, p=0.5),

    A.RandomGamma(gammalimit=(60, 140), p=0.5),

    ])


    Weather and Environmental Effects

    Albumentations provides realistic weather simulation transforms that help models generalize to different environmental conditions.

    weathertransforms = A.Compose([
    

    A.OneOf([

    # Rain effect

    A.RandomRain(

    slantlower=-10,

    slantupper=10,

    droplength=20,

    dropwidth=1,

    dropcolor=(200, 200, 200),

    blurvalue=3,

    brightnesscoefficient=0.7,

    raintype="drizzle",

    p=1.0

    ),

    # Snow effect

    A.RandomSnow(

    snowpointlower=0.1,

    snowpointupper=0.3,

    brightnesscoeff=2.0,

    p=1.0

    ),

    # Fog effect

    A.RandomFog(

    fogcoeflower=0.3,

    fogcoefupper=0.5,

    alphacoef=0.1,

    p=1.0

    ),

    # Sun flare

    A.RandomSunFlare(

    flareroi=(0, 0, 1, 0.5),

    anglelower=0,

    angleupper=1,

    numflarecircleslower=3,

    numflarecirclesupper=6,

    srcradius=200,

    p=1.0

    ),

    # Shadow

    A.RandomShadow(

    shadowroi=(0, 0.5, 1, 1),

    numshadowslower=1,

    numshadowsupper=3,

    shadowdimension=5,

    p=1.0

    ),

    ], p=0.4),

    # Noise (simulates sensor noise in bad conditions)

    A.OneOf([

    A.GaussNoise(varlimit=(10.0, 50.0), p=1.0),

    A.ISONoise(colorshift=(0.01, 0.05), intensity=(0.1, 0.5), p=1.0),

    A.MultiplicativeNoise(multiplier=(0.9, 1.1), p=1.0),

    ], p=0.3),

    # Blur (simulates motion or defocus)

    A.OneOf([

    A.MotionBlur(blurlimit=7, p=1.0),

    A.GaussianBlur(blurlimit=7, p=1.0),

    A.MedianBlur(blurlimit=5, p=1.0),

    ], p=0.2),

    ])

    result = weathertransforms(image=image)

    weatheraugmented = result["image"]


    Building Complex Pipelines with Compose

    Albumentations provides powerful composition operators for building sophisticated pipelines.

    # Full production pipeline combining all transform categories
    

    productionpipeline = A.Compose([

    # Spatial-level transforms (applied first)

    A.OneOf([

    A.RandomResizedCrop(size=(384, 384), scale=(0.5, 1.0), p=1.0),

    A.Compose([

    A.Resize(height=420, width=420),

    A.CenterCrop(height=384, width=384),

    ], p=1.0),

    ], p=1.0),

    A.HorizontalFlip(p=0.5),

    A.Rotate(limit=15, p=0.3),

    # Pixel-level transforms

    A.OneOf([

    A.RandomBrightnessContrast(brightnesslimit=0.2, contrastlimit=0.2, p=1.0),

    A.HueSaturationValue(hueshiftlimit=20, satshiftlimit=30, p=1.0),

    A.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1, p=1.0),

    ], p=0.5),

    # Weather effects (low probability)

    A.OneOf([

    A.RandomRain(p=1.0),

    A.RandomFog(p=1.0),

    A.RandomShadow(p=1.0),

    ], p=0.1),

    # Quality degradation

    A.OneOf([

    A.GaussNoise(p=1.0),

    A.GaussianBlur(blurlimit=5, p=1.0),

    A.ImageCompression(qualitylower=60, qualityupper=90, p=1.0),

    ], p=0.2),

    # Cutout / dropout (regularization)

    A.CoarseDropout(

    maxholes=8,

    maxheight=32,

    maxwidth=32,

    minholes=1,

    minheight=8,

    minwidth=8,

    fillvalue=0,

    p=0.3

    ),

    # Normalize for model input

    A.Normalize(

    mean=[0.485, 0.456, 0.406],

    std=[0.229, 0.224, 0.225],

    ),

    ])

    Using ReplayCompose for Debugging

    # ReplayCompose records which transforms were applied
    

    replaytransform = A.ReplayCompose([

    A.HorizontalFlip(p=0.5),

    A.RandomBrightnessContrast(p=0.5),

    A.GaussNoise(p=0.3),

    ])

    result = replaytransform(image=image)

    augmented = result["image"]

    replay = result["replay"]

    Inspect what was applied

    for transforminfo in replay["transforms"]:

    name = transforminfo["_classfullname_"]

    applied = transforminfo.get("applied", False)

    print(f"{name}: applied={applied}")


    Integration with PyTorch DataLoader

    Seamless integration with PyTorch is one of Albumentations' strongest features.

    import torch
    

    from torch.utils.data import Dataset, DataLoader

    import albumentations as A

    from albumentations.pytorch import ToTensorV2

    import cv2

    import os

    class ImageClassificationDataset(Dataset):

    """Custom dataset with Albumentations augmentations."""

    def init(self, imagedir, labels, transform=None):

    self.imagedir = imagedir

    self.imagefiles = sorted(os.listdir(imagedir))

    self.labels = labels

    self.transform = transform

    def len(self):

    return len(self.imagefiles)

    def getitem(self, idx):

    # Load image

    imgpath = os.path.join(self.imagedir, self.imagefiles[idx])

    image = cv2.imread(imgpath)

    image = cv2.cvtColor(image, cv2.COLORBGR2RGB)

    label = self.labels[idx]

    # Apply albumentations transform

    if self.transform:

    result = self.transform(image=image)

    image = result["image"]

    return image, label

    Define train and validation transforms

    traintransform = A.Compose([

    A.RandomResizedCrop(size=(224, 224), scale=(0.6, 1.0)),

    A.HorizontalFlip(p=0.5),

    A.OneOf([

    A.RandomBrightnessContrast(p=1.0),

    A.HueSaturationValue(p=1.0),

    ], p=0.5),

    A.GaussNoise(p=0.2),

    A.CoarseDropout(maxholes=4, maxheight=28, maxwidth=28, p=0.3),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ToTensorV2(),

    ])

    valtransform = A.Compose([

    A.Resize(height=256, width=256),

    A.CenterCrop(height=224, width=224),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ToTensorV2(),

    ])

    Create datasets and dataloaders

    traindataset = ImageClassificationDataset(

    imagedir="/data/train",

    labels=trainlabels,

    transform=traintransform,

    )

    valdataset = ImageClassificationDataset(

    imagedir="/data/val",

    labels=vallabels,

    transform=valtransform,

    )

    trainloader = DataLoader(

    traindataset,

    batchsize=32,

    shuffle=True,

    numworkers=4,

    pinmemory=True,

    persistentworkers=True,

    )

    valloader = DataLoader(

    valdataset,

    batchsize=64,

    shuffle=False,

    numworkers=4,

    pinmemory=True,

    )

    Object Detection Dataset with Bounding Boxes

    class DetectionDataset(Dataset):
    

    """Detection dataset with bbox augmentation support."""

    def init(self, imagedir, annotations, transform=None):

    self.imagedir = imagedir

    self.annotations = annotations

    self.transform = transform

    def len(self):

    return len(self.annotations)

    def getitem(self, idx):

    ann = self.annotations[idx]

    image = cv2.imread(os.path.join(self.imagedir, ann["filename"]))

    image = cv2.cvtColor(image, cv2.COLORBGR2RGB)

    bboxes = ann["bboxes"] # List of [xmin, ymin, xmax, ymax]

    labels = ann["classlabels"] # List of class IDs

    if self.transform:

    result = self.transform(

    image=image,

    bboxes=bboxes,

    classlabels=labels,

    )

    image = result["image"]

    bboxes = result["bboxes"]

    labels = result["classlabels"]

    # Convert to tensors

    bboxes = torch.tensor(bboxes, dtype=torch.float32)

    labels = torch.tensor(labels, dtype=torch.int64)

    target = {"boxes": bboxes, "labels": labels}

    return image, target

    detectiontransform = A.Compose([

    A.HorizontalFlip(p=0.5),

    A.RandomResizedCrop(size=(512, 512), scale=(0.5, 1.0)),

    A.RandomBrightnessContrast(p=0.3),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ToTensorV2(),

    ], bboxparams=A.BboxParams(

    format='pascalvoc',

    minvisibility=0.3,

    labelfields=['classlabels'],

    ))


    Custom Transforms

    You can create custom augmentation transforms by subclassing the appropriate base class.

    import albumentations as A
    

    from albumentations.core.transformsinterface import ImageOnlyTransform, DualTransform

    import numpy as np

    import cv2

    class ChannelWiseNoise(ImageOnlyTransform):

    """Add different noise levels to each channel."""

    def init(self, noiserange=(5, 25), alwaysapply=False, p=0.5):

    super().init(alwaysapply, p)

    self.noiserange = noiserange

    def apply(self, img, noiselevels=None, params):

    if noiselevels is None:

    return img

    result = img.astype(np.float32)

    for ch in range(img.shape[2]):

    noise = np.random.normal(0, noiselevels[ch], img.shape[:2])

    result[:, :, ch] += noise

    return np.clip(result, 0, 255).astype(np.uint8)

    def getparams(self):

    noiselevels = [

    np.random.uniform(self.noiserange[0], self.noiserange[1])

    for in range(3)

    ]

    return {"noiselevels": noiselevels}

    def gettransforminitargsnames(self):

    return ("noiserange",)

    class GridMask(DualTransform):

    """GridMask augmentation: masks out grid-pattern regions."""

    def init(self, numgrid=(3, 7), fillvalue=0, rotate=0,

    alwaysapply=False, p=0.5):

    super().init(alwaysapply, p)

    self.numgrid = numgrid

    self.fillvalue = fillvalue

    self.rotate = rotate

    def apply(self, img, maskarray=None, params):

    if maskarray is None:

    return img

    result = img.copy()

    result[maskarray == 0] = self.fillvalue

    return result

    def applytomask(self, mask, maskarray=None, params):

    return mask # Don't apply grid to segmentation mask

    def getparamsdependentontargets(self, params):

    img = params["image"]

    h, w = img.shape[:2]

    numgrid = np.random.randint(self.numgrid[0], self.numgrid[1] + 1)

    cellh = h // numgrid

    cellw = w // numgrid

    ratio = np.random.uniform(0.3, 0.7)

    maskarray = np.ones((h, w), dtype=np.uint8)

    for i in range(numgrid + 1):

    for j in range(numgrid + 1):

    y1 = int(i cellh)

    x1 = int(j cellw)

    y2 = min(int(y1 + cellh ratio), h)

    x2 = min(int(x1 + cellw ratio), w)

    maskarray[y1:y2, x1:x2] = 0

    return {"maskarray": maskarray}

    @property

    def targetsasparams(self):

    return ["image"]

    def gettransforminitargsnames(self):

    return ("numgrid", "fillvalue", "rotate")

    Use custom transforms in a pipeline

    custompipeline = A.Compose([

    A.HorizontalFlip(p=0.5),

    ChannelWiseNoise(noiserange=(5, 20), p=0.3),

    GridMask(numgrid=(3, 6), p=0.3),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ])


    A/B Testing Augmentation Strategies

    Systematically comparing augmentation strategies is critical for maximizing model performance.

    import json
    

    import time

    from pathlib import Path

    from collections import defaultdict

    def createaugmentationstrategies():

    """Define multiple augmentation strategies for A/B testing."""

    baseresize = [

    A.Resize(height=224, width=224),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ]

    strategies = {

    "baseline": A.Compose([

    A.Resize(height=224, width=224),

    A.HorizontalFlip(p=0.5),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ]),

    "moderate": A.Compose([

    A.RandomResizedCrop(size=(224, 224), scale=(0.7, 1.0)),

    A.HorizontalFlip(p=0.5),

    A.RandomBrightnessContrast(p=0.3),

    A.HueSaturationValue(p=0.3),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ]),

    "aggressive": A.Compose([

    A.RandomResizedCrop(size=(224, 224), scale=(0.5, 1.0)),

    A.HorizontalFlip(p=0.5),

    A.Rotate(limit=20, p=0.4),

    A.OneOf([

    A.RandomBrightnessContrast(p=1.0),

    A.HueSaturationValue(p=1.0),

    A.ColorJitter(p=1.0),

    ], p=0.6),

    A.OneOf([

    A.GaussNoise(p=1.0),

    A.GaussianBlur(p=1.0),

    ], p=0.3),

    A.CoarseDropout(maxholes=8, maxheight=28, maxwidth=28, p=0.4),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ]),

    "weatherfocused": A.Compose([

    A.RandomResizedCrop(size=(224, 224), scale=(0.6, 1.0)),

    A.HorizontalFlip(p=0.5),

    A.OneOf([

    A.RandomRain(p=1.0),

    A.RandomFog(p=1.0),

    A.RandomSnow(p=1.0),

    A.RandomShadow(p=1.0),

    ], p=0.4),

    A.RandomBrightnessContrast(p=0.3),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ]),

    }

    return strategies

    def runabtest(strategies, trainfn, valfn, epochs=20):

    """Run A/B test across augmentation strategies."""

    results = {}

    for name, transform in strategies.items():

    print(f"\n{'='50}")

    print(f"Testing strategy: {name}")

    print(f"{'='50}")

    traindataset = ImageClassificationDataset(

    imagedir="/data/train",

    labels=trainlabels,

    transform=transform,

    )

    trainloader = DataLoader(traindataset, batchsize=32, shuffle=True)

    # Train and evaluate

    model = createmodel()

    history = trainfn(model, trainloader, epochs=epochs)

    valmetrics = valfn(model, valloader)

    results[name] = {

    "valaccuracy": valmetrics["accuracy"],

    "valloss": valmetrics["loss"],

    "trainhistory": history,

    }

    print(f"Strategy '{name}': acc={valmetrics['accuracy']:.4f}")

    # Report results

    print("\n\nA/B Test Results Summary:")

    print("-" 50)

    for name, metrics in sorted(results.items(), key=lambda x: -x[1]["valaccuracy"]):

    print(f" {name:20s}: accuracy={metrics['valaccuracy']:.4f}, loss={metrics['valloss']:.4f}")

    return results


    Benchmark: Albumentations vs torchvision

    Understanding the performance difference helps justify choosing Albumentations for production.

    import time
    

    import albumentations as A

    from albumentations.pytorch import ToTensorV2

    import torchvision.transforms as T

    import numpy as np

    from PIL import Image

    import cv2

    def benchmarkalbumentations(imagenp, numiterations=1000):

    """Benchmark Albumentations pipeline."""

    transform = A.Compose([

    A.RandomResizedCrop(size=(224, 224), scale=(0.5, 1.0)),

    A.HorizontalFlip(p=0.5),

    A.RandomBrightnessContrast(p=0.5),

    A.HueSaturationValue(p=0.5),

    A.GaussNoise(p=0.3),

    A.GaussianBlur(blurlimit=5, p=0.3),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ToTensorV2(),

    ])

    # Warmup

    for in range(10):

    transform(image=imagenp)

    start = time.perfcounter()

    for in range(numiterations):

    transform(image=imagenp)

    elapsed = time.perfcounter() - start

    return elapsed / numiterations

    def benchmarktorchvision(imagepil, numiterations=1000):

    """Benchmark torchvision pipeline."""

    transform = T.Compose([

    T.RandomResizedCrop(224, scale=(0.5, 1.0)),

    T.RandomHorizontalFlip(p=0.5),

    T.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),

    T.GaussianBlur(kernelsize=5),

    T.ToTensor(),

    T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    ])

    # Warmup

    for in range(10):

    transform(imagepil)

    start = time.perfcounter()

    for in range(numiterations):

    transform(imagepil)

    elapsed = time.perfcounter() - start

    return elapsed / numiterations

    Run benchmark

    imagenp = np.random.randint(0, 256, (512, 512, 3), dtype=np.uint8)

    imagepil = Image.fromarray(imagenp)

    albutime = benchmarkalbumentations(imagenp, numiterations=2000)

    tvtime = benchmarktorchvision(imagepil, numiterations=2000)

    print(f"Albumentations: {albutime1000:.2f} ms/image")

    print(f"torchvision: {tvtime1000:.2f} ms/image")

    print(f"Speedup: {tvtime/albutime:.2f}x")

    Typical results on modern hardware:

    Albumentations: ~1.2 ms/image

    torchvision: ~3.5 ms/image

    Speedup: ~2.9x

    Feature Comparison Table

    | Feature | Albumentations | torchvision |

    |-------------------------------|:--------------:|:-----------:|

    | Number of transforms | 70+ | ~25 |

    | Bbox/keypoint support | Yes | Limited |

    | Weather effects | Yes | No |

    | Custom transform base classes | Yes | Yes |

    | Speed (relative) | Fast (1x) | Slower (2-3x)|

    | Mask support | Native | Manual |

    | Serialization (JSON/YAML) | Built-in | No |

    | ReplayCompose | Yes | No |


    Best Practices

    1. Order Your Transforms Correctly

    # Recommended order:
    

    1. Spatial transforms (crop, resize, flip, rotate)

    2. Pixel-level transforms (color, noise, blur)

    3. Dropout/cutout transforms

    4. Normalization

    5. ToTensorV2 (if using PyTorch)

    2. Use OneOf for Mutually Exclusive Transforms

    # Good: only one color transform applied per image
    

    A.OneOf([

    A.RandomBrightnessContrast(p=1.0),

    A.HueSaturationValue(p=1.0),

    A.ColorJitter(p=1.0),

    ], p=0.5)

    3. Serialize Pipelines for Reproducibility

    import albumentations as A
    

    import json

    transform = A.Compose([

    A.HorizontalFlip(p=0.5),

    A.RandomBrightnessContrast(p=0.3),

    ])

    Save to JSON

    serialized = transform.todict()

    with open("augmentationconfig.json", "w") as f:

    json.dump(serialized, f, indent=2)

    Load from JSON

    with open("augmentationconfig.json") as f:

    config = json.load(f)

    loadedtransform = A.fromdict(config)

    4. Tune Augmentation Strength to Dataset Size

    # Small dataset (<1000 images): aggressive augmentation
    

    Medium dataset (1000-10000): moderate augmentation

    Large dataset (>10000): light augmentation

    def gettransformfordatasetsize(datasetsize, imagesize=224):

    if datasetsize < 1000:

    return A.Compose([

    A.RandomResizedCrop(size=(imagesize, imagesize), scale=(0.4, 1.0)),

    A.HorizontalFlip(p=0.5),

    A.Rotate(limit=30, p=0.5),

    A.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.15, p=0.6),

    A.GaussNoise(p=0.4),

    A.CoarseDropout(maxholes=12, maxheight=32, maxwidth=32, p=0.5),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    A.pytorch.ToTensorV2(),

    ])

    elif datasetsize < 10000:

    return A.Compose([

    A.RandomResizedCrop(size=(imagesize, imagesize), scale=(0.6, 1.0)),

    A.HorizontalFlip(p=0.5),

    A.RandomBrightnessContrast(p=0.3),

    A.GaussNoise(p=0.2),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    A.pytorch.ToTensorV2(),

    ])

    else:

    return A.Compose([

    A.RandomResizedCrop(size=(imagesize, imagesize), scale=(0.8, 1.0)),

    A.HorizontalFlip(p=0.5),

    A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

    A.pytorch.ToTensorV2(),

    ])

    5. Validate Augmentations Visually

    import matplotlib.pyplot as plt
    
    

    def visualizeaugmentations(image, transform, nsamples=8, cols=4):

    """Display grid of augmented images for visual inspection."""

    rows = (nsamples + cols - 1) // cols

    fig, axes = plt.subplots(rows, cols, figsize=(4 cols, 4 rows))

    for i, ax in enumerate(axes.flatten()):

    if i == 0:

    ax.imshow(image)

    ax.settitle("Original")

    elif i <= nsamples:

    result = transform(image=image)

    ax.imshow(result["image"])

    ax.settitle(f"Aug {i}")

    ax.axis("off")

    plt.tightlayout()

    plt.savefig("augmentationpreview.png", dpi=150)

    plt.show()


    Conclusion

    Albumentations is a powerful and performant library for image augmentation in machine learning workflows. In this tutorial, you learned how to:

    • Build augmentation pipelines with geometric, color, and weather transforms
    • Integrate Albumentations seamlessly with PyTorch DataLoader
    • Create custom transforms by subclassing base classes
    • Design and run A/B tests to compare augmentation strategies
    • Benchmark Albumentations against torchvision and understand the performance gains

    The key to effective augmentation is matching your strategy to your specific domain and dataset size. Start with moderate augmentation, visualize the results to ensure they look realistic, and systematically test different strategies to find what works best for your task.

    For further reading, check the official Albumentations documentation at albumentations.ai and explore the extensive list of transforms available in the library.

    Related Articles

    TorchServe: Deploying PyTorch Models to Production

    TorchServe: Panduan Lengkap Deployment Model PyTorch ke Production Penulis: Ruby Abdullah Kategori: Tutorial Tags: PyTor...

    Flower (flwr): A Complete Guide to Federated Learning in Python

    Tutorial Lengkap Flower (flwr): Framework Federated Learning dengan Python Federated learning adalah paradigma machine l...

    Complete Keras 3 Tutorial: Multi-Backend Deep Learning Framework for TensorFlow, JAX, and PyTorch

    Tutorial Lengkap Keras 3: Framework Deep Learning Multi-Backend untuk TensorFlow, JAX, dan PyTorch Keras 3 adalah evolus...

    bitsandbytes Tutorial: 4-bit and 8-bit Quantization for Large Language Models

    Tutorial bitsandbytes: Kuantisasi 4-bit dan 8-bit untuk Large Language Models Menjalankan Large Language Model (LLM) sep...