4/25/2023

image augment python sample code

 code 1

pip install imgaug

.

import os
import cv2
import imgaug.augmenters as iaa

def load_image(image_path):
return cv2.imread(image_path)

def save_image(image, image_path):
cv2.imwrite(image_path, image)

def apply_augmentation(image, augmenter):
augmented_image = augmenter(image=image)
return augmented_image

def augment_images(input_folder, output_folder, augmenter):
os.makedirs(output_folder, exist_ok=True)

for image_filename in os.listdir(input_folder):
input_image_path = os.path.join(input_folder, image_filename)
output_image_path = os.path.join(output_folder, image_filename)

image = load_image(input_image_path)
augmented_image = apply_augmentation(image, augmenter)
save_image(augmented_image, output_image_path)

# Define the augmentations to apply
augmenter = iaa.Sequential([
iaa.Affine(rotate=(-5, 5), scale=(0.9, 1.1)),
iaa.Multiply((0.8, 1.2)),
iaa.AdditiveGaussianNoise(scale=(10, 30)),
iaa.PerspectiveTransform(scale=(0.01, 0.1)),
iaa.PiecewiseAffine(scale=(0.01, 0.05)),
iaa.SomeOf((0, 2), [
iaa.GaussianBlur(sigma=(0, 2)),
iaa.MotionBlur(k=15, angle=[-45, 45]),
iaa.AddToHueAndSaturation((-20, 20))
]),
])

input_folder = "barcodes"
output_folder = "augmented_barcodes"

augment_images(input_folder, output_folder, augmenter)

..



Way #2

pip install albumentations

.

import os
import random
import cv2
from albumentations import (
Compose,
Rotate,
GaussNoise,
RandomBrightnessContrast,
RandomGamma,
HueSaturationValue,
)

def load_image(image_path):
return cv2.imread(image_path)

def save_image(image, image_path):
cv2.imwrite(image_path, image)

def apply_augmentation(image, augmentations):
augmented_image = augmentations(image=image)['image']
return augmented_image

def augment_images(input_folder, output_folder, augmentations):
os.makedirs(output_folder, exist_ok=True)

for image_filename in os.listdir(input_folder):
input_image_path = os.path.join(input_folder, image_filename)
output_image_path = os.path.join(output_folder, image_filename)

image = load_image(input_image_path)
augmented_image = apply_augmentation(image, augmentations)
save_image(augmented_image, output_image_path)

# Define the augmentations to apply
augmentations = Compose([
Rotate(limit=5, p=0.5),
GaussNoise(var_limit=(10, 50), p=0.5),
RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.5),
RandomGamma(gamma_limit=(80, 120), p=0.5),
HueSaturationValue(hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=20, p=0.5),
])

input_folder = "barcodes"
output_folder = "augmented_barcodes"

augment_images(input_folder, output_folder, augmentations)

..


Thank you.

πŸ™‡πŸ»‍♂️

No comments:

Post a Comment