python Copy code
#!/usr/bin/env python3
"""
Image Augmentation and Processing Pipeline
This script allows users to apply a series of image augmentations to a list of images.
Users can specify the augmentations to apply and the output directory for the augmented images.
Usage:
python image_augmentation_pipeline.py --images img1.jpg img2.png --augmentations rotate flip \
--output_dir augmented_images
"""
import os
import sys
import argparse
from typing import List, Callable, Dict
import cv2
import numpy as np
# Supported image extensions
SUPPORTED_EXTENSIONS = {
'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.gif',
'.webp', '.svg', '.heic', '.raw'
}
def load_image(image_path: str) -> np.ndarray:
"""
Load an image from a file path.
Args:
image_path: Path to the image file.
Returns:
Loaded image as a NumPy array.
Raises:
FileNotFoundError: If the image file does not exist.
ValueError: If the image format is unsupported or not readable.
"""
if not os.path.isfile(image_path):
raise FileNotFoundError(f"Image file not found: {image_path}")
file_ext = os.path.splitext(image_path)[1].lower()
if file_ext not in SUPPORTED_EXTENSIONS:
raise ValueError(f"Unsupported image extension: {file_ext}")
try:
image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
if image is None:
raise ValueError(f"Failed to load image: {image_path}")
return image
except Exception as e:
raise ValueError(f"Error loading image {image_path}: {e}") from e
def save_image(image: np.ndarray, output_path: str) -> None:
"""
Save an image to a specified file path.
Args:
image: Image to save.
output_path: Path where the image will be saved.
Raises:
IOError: If the image cannot be saved.
"""
try:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
cv2.imwrite(output_path, image)
except Exception as e:
raise IOError(f"Error saving image {output_path}: {e}") from e
def rotate_image(image: np.ndarray, angle: float = 90) -> np.ndarray:
"""
Rotate the image by a specified angle.
Args:
image: Image to rotate.
angle: Rotation angle in degrees.
Returns:
Rotated image.
"""
(h, w) = image.shape[:2]
center = (w / 2, h / 2)
rotation_mat = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, rotation_mat, (w, h), flags=cv2.INTER_LINEAR)
return rotated
def flip_image(image: np.ndarray, mode: str = 'horizontal') -> np.ndarray:
"""
Flip the image horizontally or vertically.
Args:
image: Image to flip.
mode: 'horizontal' or 'vertical'.
Returns:
Flipped image.
Raises:
ValueError: If the mode is invalid.
"""
if mode == 'horizontal':
flipped = cv2.flip(image, 1)
elif mode == 'vertical':
flipped = cv2.flip(image, 0)
else:
raise ValueError("Mode must be 'horizontal' or 'vertical'")
return flipped
def brightness_adjustment(image: np.ndarray, beta: float = 50) -> np.ndarray:
"""
Adjust the brightness of the image.
Args:
image: Image to adjust.
beta: Brightness adjustment value. Positive to increase, negative to decrease.
Returns:
Brightness adjusted image.
"""
adjusted = cv2.convertScaleAbs(image, alpha=1.0, beta=beta)
return adjusted
def contrast_adjustment(image: np.ndarray, alpha: float = 1.5) -> np.ndarray:
"""
Adjust the contrast of the image.
Args:
image: Image to adjust.
alpha: Contrast adjustment factor. Greater than 1 to increase contrast.
Returns:
Contrast adjusted image.
"""
adjusted = cv2.convertScaleAbs(image, alpha=alpha, beta=0)
return adjusted
def gaussian_blur(image: np.ndarray, kernel_size: int = 5) -> np.ndarray:
"""
Apply Gaussian blur to the image.
Args:
image: Image to blur.
kernel_size: Size of the Gaussian kernel (must be odd).
Returns:
Blurred image.
"""
if kernel_size % 2 == 0:
kernel_size += 1 # Ensure kernel size is odd
blurred = cv2.GaussianBlur(image, (kernel_size, kernel_size), 0)
return blurred
def noise_injection(image: np.ndarray, mean: float = 0, var: float = 10) -> np.ndarray:
"""
Inject Gaussian noise into the image.
Args:
image: Image to add noise to.
mean: Mean of the Gaussian noise.
var: Variance of the Gaussian noise.
Returns:
Noisy image.
"""
sigma = var ** 0.5
gauss = np.random.normal(mean, sigma, image.shape).astype('float32')
noisy = cv2.add(image.astype('float32'), gauss)
noisy = np.clip(noisy, 0, 255).astype('uint8')
return noisy
def sharpening(image: np.ndarray) -> np.ndarray:
"""
Sharpen the image using a kernel.
Args:
image: Image to sharpen.
Returns:
Sharpened image.
"""
kernel = np.array([[0, -1, 0],
[-1, 5,-1],
[0, -1, 0]], dtype='float32')
sharpened = cv2.filter2D(image, -1, kernel)
return sharpened
def color_jitter(image: np.ndarray, shift_value: int = 50) -> np.ndarray:
"""
Apply color jitter to the image.
Args:
image: Image to jitter.
shift_value: Maximum shift value for color channels.
Returns:
Color jittered image.
"""
jitter = np.random.randint(-shift_value, shift_value, image.shape, dtype='int16')
jittered = image.astype('int16') + jitter
jittered = np.clip(jittered, 0, 255).astype('uint8')
return jittered
def hue_adjustment(image: np.ndarray, delta: int = 10) -> np.ndarray:
"""
Adjust the hue of the image.
Args:
image: Image to adjust.
delta: Hue adjustment value.
Returns:
Hue adjusted image.
"""
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv[..., 0] = (hsv[..., 0].astype(int) + delta) % 180
adjusted = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return adjusted
def saturation_adjustment(image: np.ndarray, scale: float = 1.5) -> np.ndarray:
"""
Adjust the saturation of the image.
Args:
image: Image to adjust.
scale: Saturation scaling factor.
Returns:
Saturation adjusted image.
"""
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv[..., 1] = np.clip(hsv[..., 1] * scale, 0, 255)
adjusted = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return adjusted
def shearing(image: np.ndarray, shear_factor: float = 0.2) -> np.ndarray:
"""
Apply shearing transformation to the image.
Args:
image: Image to shear.
shear_factor: Shearing factor.
Returns:
Sheared image.
"""
(h, w) = image.shape[:2]
M = np.array([[1, shear_factor, 0],
[0, 1, 0]], dtype='float32')
nW = w + abs(shear_factor * h)
sheared = cv2.warpAffine(image, M, (int(nW), h))
return sheared
def resize_image(image: np.ndarray, size: tuple = (256, 256)) -> np.ndarray:
"""
Resize the image to a specified size.
Args:
image: Image to resize.
size: Desired size as (width, height).
Returns:
Resized image.
"""
resized = cv2.resize(image, size, interpolation=cv2.INTER_LINEAR)
return resized
def grayscale_conversion(image: np.ndarray) -> np.ndarray:
"""
Convert the image to grayscale.
Args:
image: Image to convert.
Returns:
Grayscale image.
"""
grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayscale_bgr = cv2.cvtColor(grayscale, cv2.COLOR_GRAY2BGR)
return grayscale_bgr
def inversion(image: np.ndarray) -> np.ndarray:
"""
Invert the colors of the image.
Args:
image: Image to invert.
Returns:
Inverted image.
"""
inverted = cv2.bitwise_not(image)
return inverted
def random_erasing(image: np.ndarray, erase_prob: float = 0.5, area_ratio_range: tuple = (0.02, 0.4)) -> np.ndarray:
"""
Apply random erasing to the image.
Args:
image: Image to erase.
erase_prob: Probability of erasing.
area_ratio_range: Tuple of min and max area ratios.
Returns:
Image with random erasing applied.
"""
if np.random.rand() > erase_prob:
return image
h, w = image.shape[:2]
area = h * w
target_area = np.random.uniform(*area_ratio_range) * area
aspect_ratio = np.random.uniform(0.3, 3.3)
h_erase = int(round(np.sqrt(target_area * aspect_ratio)))
w_erase = int(round(np.sqrt(target_area / aspect_ratio)))
if h_erase <= h and w_erase <= w:
x = np.random.randint(0, h - h_erase)
y = np.random.randint(0, w - w_erase)
image[x:x + h_erase, y:y + w_erase, :] = np.random.randint(0, 256, (h_erase, w_erase, 3), dtype='uint8')
return image
def perspective_transformation(image: np.ndarray) -> np.ndarray:
"""
Apply perspective transformation to the image.
Args:
image: Image to transform.
Returns:
Perspective transformed image.
"""
h, w = image.shape[:2]
pts1 = np.float32([[0, 0], [w - 1, 0], [0, h - 1]])
pts2 = pts1 + np.random.randint(-50, 50, pts1.shape).astype(np.float32)
matrix = cv2.getAffineTransform(pts1, pts2)
transformed = cv2.warpAffine(image, matrix, (w, h))
return transformed
def gamma_correction(image: np.ndarray, gamma: float = 1.5) -> np.ndarray:
"""
Apply gamma correction to the image.
Args:
image: Image to correct.
gamma: Gamma value.
Returns:
Gamma corrected image.
"""
inv_gamma = 1.0 / gamma
table = (np.arange(256) / 255.0) ** inv_gamma * 255
table = np.clip(table, 0, 255).astype('uint8')
corrected = cv2.LUT(image, table)
return corrected
def scaling(image: np.ndarray, scale_factor: float = 1.5) -> np.ndarray:
"""
Scale the image by a scaling factor.
Args:
image: Image to scale.
scale_factor: Scaling factor.
Returns:
Scaled image.
"""
h, w = image.shape[:2]
scaled = cv2.resize(image, (int(w * scale_factor), int(h * scale_factor)), interpolation=cv2.INTER_LINEAR)
return scaled
def cropping(image: np.ndarray, crop_size: tuple = (100, 100)) -> np.ndarray:
"""
Crop the image to a specified size.
Args:
image: Image to crop.
crop_size: Size to crop as (width, height).
Returns:
Cropped image.
Raises:
ValueError: If crop size is larger than image size.
"""
h, w = image.shape[:2]
crop_w, crop_h = crop_size
if crop_w > w or crop_h > h:
raise ValueError("Crop size must be smaller than the image size.")
x = np.random.randint(0, w - crop_w + 1)
y = np.random.randint(0, h - crop_h + 1)
cropped = image[y:y + crop_h, x:x + crop_w]
return cropped
def zooming(image: np.ndarray, zoom_factor: float = 1.2) -> np.ndarray:
"""
Zoom into the image by a zoom factor.
Args:
image: Image to zoom.
zoom_factor: Zoom factor.
Returns:
Zoomed image.
"""
h, w = image.shape[:2]
center_x, center_y = w / 2, h / 2
new_w, new_h = w / zoom_factor, h / zoom_factor
x1 = int(center_x - new_w / 2)
y1 = int(center_y - new_h / 2)
x2 = int(center_x + new_w / 2)
y2 = int(center_y + new_h / 2)
zoomed = image[y1:y2, x1:x2]
zoomed = cv2.resize(zoomed, (w, h), interpolation=cv2.INTER_LINEAR)
return zoomed
# Map of augmentation names to functions
AUGMENTATIONS: Dict[str, Callable[[np.ndarray], np.ndarray]] = {
'rotation': rotate_image,
'scaling': scaling,
'cropping': cropping,
'flipping': flip_image,
'brightness_adjustment': brightness_adjustment,
'contrast_adjustment': contrast_adjustment,
'gaussian_blur': gaussian_blur,
'noise_injection': noise_injection,
'sharpening': sharpening,
'color_jitter': color_jitter,
'hue_adjustment': hue_adjustment,
'saturation_adjustment': saturation_adjustment,
'shearing': shearing,
'resizing': resize_image,
'grayscale_conversion': grayscale_conversion,
'inversion': inversion,
'random_erasing': random_erasing,
'perspective_transformation': perspective_transformation,
'zooming': zooming,
'gamma_correction': gamma_correction,
}
def parse_arguments() -> argparse.Namespace:
"""
Parse command-line arguments.
Returns:
Parsed arguments namespace.
"""
parser = argparse.ArgumentParser(description="Image Augmentation and Processing Pipeline")
parser.add_argument(
'--images', nargs='+', required=True,
help='List of image file paths to process.'
)
parser.add_argument(
'--augmentations', nargs='+', required=True,
choices=AUGMENTATIONS.keys(),
help='List of augmentations to apply.'
)
parser.add_argument(
'--output_dir', required=True,
help='Directory where augmented images will be saved.'
)
return parser.parse_args()
def process_images(
image_paths: List[str],
augmentations: List[str],
output_dir: str
) -> None:
"""
Process and augment images.
Args:
image_paths: List of image file paths.
augmentations: List of augmentation names to apply.
output_dir: Directory to save augmented images.
"""
for image_path in image_paths:
try:
image = load_image(image_path)
except Exception as e:
print(f"Error loading image {image_path}: {e}", file=sys.stderr)
continue
original_filename = os.path.basename(image_path)
filename_wo_ext, ext = os.path.splitext(original_filename)
augmented_image = image.copy()
for augmentation_name in augmentations:
augmentation_func = AUGMENTATIONS[augmentation_name]
try:
augmented_image = augmentation_func(augmented_image)
except Exception as e:
print(f"Error applying {augmentation_name} to {image_path}: {e}", file=sys.stderr)
continue
output_filename = f"{filename_wo_ext}_{'_'.join(augmentations)}{ext}"
output_path = os.path.join(output_dir, output_filename)
try:
save_image(augmented_image, output_path)
print(f"Saved augmented image to: {output_path}")
except Exception as e:
print(f"Error saving image {output_path}: {e}", file=sys.stderr)
def main() -> None:
"""
Main function to run the image augmentation pipeline.
"""
args = parse_arguments()
process_images(args.images, args.augmentations, args.output_dir)
if __name__ == '__main__':
main()
If you need to adjust parameters for specific augmentations (e.g., rotation angle, brightness level), you can modify the default values in the corresponding function definitions.
The code is designed to be easily extensible. You can add more augmentations by defining new functions and adding them to the AUGMENTATIONS dictionary.
Feel free to run the script and experiment with different images and augmentations to suit your needs. If you encounter any issues or have questions about the code, don't hesitate to ask!