Random Image Transformation Generator for Data Augmentation

  • Share this:

Code introduction


This function generates a random image transformation for data augmentation. It randomly selects one from several transformations such as horizontal flip, rotation, color jitter, random cropping, etc.


Technology Stack : PyTorch, torchvision.transforms, torchvision.models

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
import torch
import torchvision.transforms as transforms
import torchvision.models as models

def generate_random_image_transforms():
    # Define a function that generates random image transformations
    def random_transform():
        # Randomly choose from a set of transformations
        transform_type = torch.rand(1).item() * 5  # 0-4
        if transform_type < 1:
            return transforms.RandomHorizontalFlip()
        elif transform_type < 2:
            return transforms.RandomRotation(90)
        elif transform_type < 3:
            return transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)
        elif transform_type < 4:
            return transforms.RandomResizedCrop(size=256, scale=(0.8, 1.0))
        else:
            return transforms.ToTensor()

    # Apply the random transformation to an image
    transform = random_transform()
    image = torch.randn(3, 224, 224)  # Simulate a random image
    transformed_image = transform(image)

    return transformed_image