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

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings Efficient storage and retrieval of vector databases is foundational for building intelligent retrieval-augmented generation (RAG) systems using large language models (LLMs). In this guide, we’ll walk through a professional-grade Python implementation that utilizes LangChain with FAISS and Google Gemini Embeddings to store document embeddings and retrieve similar information. This setup is highly suitable for advanced machine learning (ML) and deep learning (DL) engineers who work with semantic search and retrieval pipelines. Why Vector Databases Matter in LLM Applications Traditional keyword-based search systems fall short when it comes to understanding semantic meaning. Vector databases store high-dimensional embeddings of text data, allowing for approximate nearest-neighbor (ANN) searches based on semantic similarity. These capabilities are critical in applications like: Question Ans...

RF-DETR: Overcoming the Limitations of DETR in Object Detection

RF-DETR (Region-Focused DETR), proposed in April 2025, is an advanced object detection architecture designed to overcome fundamental drawbacks of the original DETR (DEtection TRansformer) . In this technical article, we explore RF-DETR's contributions, architecture, and how it compares with both DETR and the improved model D-FINE . We also provide experimental benchmarks and discuss its real-world applicability. RF-DETR Architecture diagram for object detection Limitations of DETR DETR revolutionized object detection by leveraging the Transformer architecture, enabling end-to-end learning without anchor boxes or NMS (Non-Maximum Suppression). However, DETR has notable limitations: Slow convergence, requiring heavy data augmentation and long training schedules Degraded performance on low-resolution objects and complex scenes Lack of locality due to global self-attention mechanisms Key Innovations in RF-DETR RF-DETR intr...