Skip to main content

Image Augmentation in Computer Vision using PyTorch Transforms v2

Why Image Augmentation is Essential in Deep Learning

In computer vision, image augmentation plays a critical role in improving the generalization of deep neural networks. By artificially expanding the diversity of the training dataset through transformations that preserve the label, image augmentation helps reduce overfitting and increases model robustness.

Especially for convolutional neural networks (CNNs) and vision transformers (ViTs), which learn hierarchical and spatial features, input variability introduced by augmentation forces the model to learn more invariant and meaningful representations. This is analogous to improving the mutual information between relevant features and output predictions while discarding noise.

Common Image Augmentation Techniques and Parameter Descriptions

1. RandomHorizontalFlip

Purpose: Introduces horizontal symmetry by flipping the image left-to-right with a certain probability.

from torchvision.transforms import v2 as transforms

transform = transforms.Compose([
    transforms.RandomHorizontalFlip(p=0.5)
])
  
  • p: Probability of flipping the image horizontally. A value of 0.5 means there's a 50% chance of flipping.

2. RandomResizedCrop

Purpose: Randomly crops a region of the image and resizes it to a target size, improving scale invariance.

transform = transforms.Compose([
    transforms.RandomResizedCrop(size=(224, 224), scale=(0.8, 1.0), ratio=(0.75, 1.33))
])
  
  • size: Target output size of the crop (height, width).
  • scale: Tuple indicating the range of the area of the crop relative to the original image. (0.8, 1.0) means the crop will cover 80%–100% of the original image area.
  • ratio: Tuple for aspect ratio range (width / height) of the crop.

3. ColorJitter

Purpose: Randomly changes brightness, contrast, saturation, and hue to simulate lighting variation.

transform = transforms.Compose([
    transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)
])
  
  • brightness: Float or tuple. Brightness factor is randomly chosen from [1-0.2, 1+0.2].
  • contrast: Similar to brightness but for contrast.
  • saturation: Saturation factor range.
  • hue: Float in [-0.5, 0.5]. Small changes in hue simulate color temperature variations.

4. GaussianBlur

Purpose: Applies Gaussian blur to simulate defocus or sensor noise.

transform = transforms.Compose([
    transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0))
])
  
  • kernel_size: Integer or tuple. Defines the size of the convolution kernel.
  • sigma: Standard deviation for the Gaussian kernel. Can be a range (min, max) for random sampling.

5. RandomAffine

Purpose: Applies rotation, translation, scaling, and shearing in one transformation for geometric augmentation.

transform = transforms.Compose([
    transforms.RandomAffine(degrees=30, translate=(0.1, 0.1), scale=(0.9, 1.1), shear=10)
])
  
  • degrees: Maximum rotation angle in degrees.
  • translate: Tuple (x, y) with max translation as a fraction of image dimensions.
  • scale: Tuple indicating scaling range (e.g., (0.9, 1.1)).
  • shear: Shear angle in degrees.

6. Normalize

Purpose: Standardizes pixel values using the dataset mean and standard deviation. Required for pretrained models.

transform = transforms.Compose([
    transforms.ToImage(),
    transforms.ConvertImageDtype(torch.float32),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225])
])
  
  • mean: Per-channel mean to subtract (usually from ImageNet).
  • std: Per-channel standard deviation to divide by.

7. Full Augmentation Pipeline

from torchvision.transforms import v2 as transforms
import torch

train_transforms = transforms.Compose([
    transforms.RandomResizedCrop((224, 224)),
    transforms.RandomHorizontalFlip(),
    transforms.ColorJitter(0.2, 0.2, 0.2, 0.1),
    transforms.RandomAffine(15),
    transforms.GaussianBlur(3),
    transforms.ToImage(),
    transforms.ConvertImageDtype(torch.float32),
    transforms.Normalize([0.485, 0.456, 0.406],
                         [0.229, 0.224, 0.225]),
])
  

Conclusion

Image augmentation is a critical strategy in computer vision deep learning pipelines. By leveraging PyTorch’s modern torchvision.transforms.v2 API, engineers can easily implement powerful transformations that improve training robustness, generalization, and overall model accuracy.

References

  • PyTorch Documentation: torchvision.transforms.v2
  • Shorten, C. & Khoshgoftaar, T.M. (2019). "A survey on image data augmentation for deep learning". Journal of Big Data, 6(60).
  • Dosovitskiy, A., et al. (2021). "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale". ICLR.

Comments

Popular

Understanding SentencePiece: A Language-Independent Tokenizer for AI Engineers

In the realm of Natural Language Processing (NLP), tokenization plays a pivotal role in preparing text data for machine learning models. Traditional tokenization methods often rely on language-specific rules and pre-tokenized inputs, which can be limiting when dealing with diverse languages and scripts. Enter SentencePiece—a language-independent tokenizer and detokenizer designed to address these challenges and streamline the preprocessing pipeline for neural text processing systems. What is SentencePiece? SentencePiece is an open-source tokenizer and detokenizer developed by Google, tailored for neural-based text processing tasks such as Neural Machine Translation (NMT). Unlike conventional tokenizers that depend on whitespace and language-specific rules, SentencePiece treats the input text as a raw byte sequence, enabling it to process languages without explicit word boundaries, such as Japanese, Chinese, and Korean. This approach allows SentencePiece to train subword models di...

Mastering the Byte Pair Encoding (BPE) Tokenizer for NLP and LLMs

Byte Pair Encoding (BPE) is one of the most important and widely adopted subword tokenization algorithms in modern Natural Language Processing (NLP), especially in training Large Language Models (LLMs) like GPT. This guide provides a deep technical dive into how BPE works, compares it with other tokenizers like WordPiece and SentencePiece, and explains its practical implementation with Python code. This article is optimized for AI engineers building real-world models and systems. 1. What is Byte Pair Encoding? BPE was originally introduced as a data compression algorithm by Gage in 1994. It replaces the most frequent pair of bytes in a sequence with a single, unused byte. In 2015, Sennrich et al. adapted BPE for NLP to address the out-of-vocabulary (OOV) problem in neural machine translation. Instead of working with full words, BPE decomposes them into subword units that can be recombined to represent rare or unseen words. 2. Why Tokenization Matters in LLMs Tokenization is th...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...