SoFunction
Updated on 2025-03-03

Python implements random enhanced transformation of images

Randomly select a certain number of images from the folder and perform a random data augmentation transformation on each selected image.

import os
import random
import cv2
import numpy as np
from PIL import Image, ImageEnhance, ImageOps

# Define various data enhancement methodsdef random_rotate(image, angle_range=(-30, 30)):
    angle = (angle_range[0], angle_range[1])
    (h, w) = [:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    rotated = (image, M, (w, h), borderMode=cv2.BORDER_REFLECT)
    return rotated

def random_translate(image, translate_range=(-50, 50)):
    tx = (translate_range[0], translate_range[1])
    ty = (translate_range[0], translate_range[1])
    (h, w) = [:2]
    M = np.float32([[1, 0, tx], [0, 1, ty]])
    translated = (image, M, (w, h), borderMode=cv2.BORDER_REFLECT)
    return translated

def random_flip(image):
    flip_code = ([-1, 0, 1])
    flipped = (image, flip_code)
    return flipped

def random_scale(image, scale_range=(0.8, 1.2)):
    scale = (scale_range[0], scale_range[1])
    (h, w) = [:2]
    new_dim = (int(w * scale), int(h * scale))
    scaled = (image, new_dim, interpolation=cv2.INTER_LINEAR)
    return scaled

def random_crop(image, crop_size=(224, 224)):
    (h, w) = [:2]
    if crop_size[0] > h or crop_size[1] > w:
        # When the crop size is larger than the image size, throw an exception or adjust the crop size        raise ValueError("Crop size is larger than image size.")
    top = (0, h - crop_size[0])
    left = (0, w - crop_size[1])
    cropped = image[top:top+crop_size[0], left:left+crop_size[1]]
    return cropped

def random_color_jitter(image):
    pil_image = ((image, cv2.COLOR_BGR2RGB))
    color_jitter = (pil_image).enhance((0.6, 1.4))
    contrast_jitter = (color_jitter).enhance((0.5, 1.5))
    brightness_jitter = (contrast_jitter).enhance((0.6, 1.4))
    sharpness_jitter = (brightness_jitter).enhance((0.6, 1.4))
    jittered = ((sharpness_jitter), cv2.COLOR_RGB2BGR)
    return jittered

def random_add_noise(image):
    row, col, ch = 
    mean = 0
    var = 0.1
    sigma = var ** 0.5
    gauss = (mean, sigma, (row, col, ch))
    gauss = (row, col, ch)
    noisy = image + gauss
    return (noisy, 0, 255).astype(np.uint8)

# Data Enhanced Main Functiondef augment_random_images(src_folder, dst_folder, num_images_to_select, num_augmentations_per_image):
    if not (dst_folder):
        (dst_folder)

    # Get all image file names    all_filenames = [f for f in (src_folder) if ().endswith(('.png', '.jpg', '.jpeg'))]

    # If the number of selected images is greater than the total number of images, only all images are processed    num_images_to_process = min(num_images_to_select, len(all_filenames))

    # Randomly select images    selected_filenames = (all_filenames, num_images_to_process)

    # Create a list of enhanced methods    augmentation_methods = [
        random_rotate,
        #random_translate,
        random_flip,
        random_scale,
        #random_crop,
        random_color_jitter,
        random_add_noise
    ]

    for filename in selected_filenames:
        img_path = (src_folder, filename)
        image = (img_path)

        for i in range(num_augmentations_per_image):
            # Randomly select an enhancement method            augmentation_method = (augmentation_methods)
            
            # Apply the selected enhancement method            augmented_img = augmentation_method(image)

            # Save enhanced image            base_name, ext = (filename)
            save_path = (dst_folder, f"{base_name}_aug_{i}{ext}")
            (save_path, augmented_img)

if __name__ == "__main__":
    src_folder = 'path/to/source/folder'  # Replace with your source folder path    dst_folder = 'path/to/destination/folder'  # Replace with the folder path where you want to save the enhanced image    num_images_to_select = 10  # Number of images randomly selected from the source folder    num_augmentations_per_image = 5  # Number of enhanced images generated per image
    augment_random_images(src_folder, dst_folder, num_images_to_select, num_augmentations_per_image)
    print(f"Image enhancement completed,The enhanced image has been saved to {dst_folder}")

illustrate

  • Randomly select images: Randomly select the number of images with num_images_to_select from the source folder.
  • Randomly select an enhancement method: for each selected image, randomly select a data enhancement method.
  • Apply Enhancement Method: Apply the selected enhancement method to each selected image.
  • Save enhanced image: Save the enhanced image to the target folder.

parameter

•src_folder: source folder path.

•dst_folder: The destination folder path.

•num_images_to_select: The number of images randomly selected from the source folder.

•num_augmentations_per_image: The number of enhanced images generated by each selected image.

Make sure to set the src_folder and dst_folder variables to the folder path you are actually using and adjust the values ​​of num_images_to_select and num_augmentations_per_image as needed. After running this code, you will get the images randomly selected from the source folder and perform random data-enhanced transformations on these images.

This is the end of this article about python's random enhancement transformation of images. For more related python random enhancement content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!