Certainly! Below is an advanced, maintainable Python implementation of an image augmentation and processing pipeline that adheres to the specified requirements. The code is structured to be modular, efficient, and easy to maintain, following PEP-8 standards and incorporating comprehensive error handling.
Overview:
- Supported Image Formats: Handles
.jpg, .png, .bmp, .tiff, .gif, .webp, .jpeg, .svg, .heic, .raw.
- User Inputs: Accepts a list of image paths, selected augmentations, and an output directory.
- Modular Augmentation Functions: Each augmentation is implemented as a separate, composable function.
- Efficiency: Utilizes multiprocessing to handle large datasets efficiently.
- Error Handling: Comprehensive checks and meaningful error messages ensure robustness.
- Dependencies: Uses standard libraries (
os, sys, logging, typing) and third-party libraries (Pillow, numpy, opencv-python, scikit-image, pyheif).
Prerequisites:
Before running the script, ensure you have the necessary libraries installed:
pip install Pillow numpy opencv-python scikit-image pyheif
Implementation:
import os
import sys
import logging
from typing import List, Callable, Dict, Any
from PIL import Image, ImageEnhance, ImageOps
import numpy as np
import cv2
import pyheif
from skimage import util
import concurrent.futures
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='[%(levelname)s] %(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Supported image extensions
SUPPORTED_EXTENSIONS = {
'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.gif', '.webp', '.svg', '.heic', '.raw'
}
def load_image(path: str) -> Image.Image:
"""
Load an image from the given path.
:param path: Path to the image file.
:return: PIL Image object.
"""
try:
ext = os.path.splitext(path)[1].lower()
if ext == '.heic':
heif_file = pyheif.read(path)
image = Image.frombytes(
heif_file.mode,
heif_file.size,
heif_file.data,
"raw",
heif_file.mode,
heif_file.stride,
)
elif ext == '.raw':
# RAW image handling can vary; placeholder for actual implementation
raise NotImplementedError("RAW format not supported in this implementation.")
else:
image = Image.open(path).convert('RGB')
logging.debug(f"Loaded image: {path}")
return image
except Exception as e:
logging.error(f"Failed to load image {path}: {e}")
raise
def save_image(image: Image.Image, path: str) -> None:
"""
Save the PIL Image object to the specified path.
:param image: PIL Image object.
:param path: Path to save the image.
"""
try:
image.save(path)
logging.debug(f"Saved image: {path}")
except Exception as e:
logging.error(f"Failed to save image {path}: {e}")
raise
# Augmentation Functions
def rotate(image: Image.Image, angle: float = 0.0) -> Image.Image:
"""Rotate the image by the given angle."""
if angle == 0.0:
return image
return image.rotate(angle, expand=True)
def scale(image: Image.Image, scale_factor: float = 1.0) -> Image.Image:
"""Scale the image by the given factor."""
if scale_factor == 1.0:
return image
new_size = (int(image.width * scale_factor), int(image.height * scale_factor))
return image.resize(new_size, Image.ANTIALIAS)
def crop(image: Image.Image, left: int, upper: int, right: int, lower: int) -> Image.Image:
"""Crop the image to the specified box."""
return image.crop((left, upper, right, lower))
def flip(image: Image.Image, horizontal: bool = False, vertical: bool = False) -> Image.Image:
"""Flip the image horizontally and/or vertically."""
if horizontal:
image = ImageOps.mirror(image)
if vertical:
image = ImageOps.flip(image)
return image
def adjust_brightness(image: Image.Image, factor: float = 1.0) -> Image.Image:
"""Adjust the brightness of the image."""
enhancer = ImageEnhance.Brightness(image)
return enhancer.enhance(factor)
def adjust_contrast(image: Image.Image, factor: float = 1.0) -> Image.Image:
"""Adjust the contrast of the image."""
enhancer = ImageEnhance.Contrast(image)
return enhancer.enhance(factor)
def gaussian_blur(image: Image.Image, radius: float = 2.0) -> Image.Image:
"""Apply Gaussian blur to the image."""
return image.filter(Image.Filter.GaussianBlur(radius))
def noise_injection(image: Image.Image, mean: float = 0.0, var: float = 0.01) -> Image.Image:
"""Inject Gaussian noise into the image."""
np_image = np.array(image)
noisy = util.random_noise(np_image, mode='gaussian', mean=mean, var=var)
noisy = np.clip(noisy * 255, 0, 255).astype(np.uint8)
return Image.fromarray(noisy)
def sharpen(image: Image.Image) -> Image.Image:
"""Sharpen the image."""
return image.filter(Image.Filter.SHARPEN)
def color_jitter(image: Image.Image, brightness: float = 1.0, contrast: float = 1.0,
saturation: float = 1.0, hue: float = 0.0) -> Image.Image:
"""Apply color jitter to the image."""
enhancer = ImageEnhance.Brightness(image)
image = enhancer.enhance(brightness)
enhancer = ImageEnhance.Contrast(image)
image = enhancer.enhance(contrast)
enhancer = ImageEnhance.Color(image)
image = enhancer.enhance(saturation)
# PIL does not support hue adjustment directly
# Placeholder for hue adjustment implementation
return image
def hue_adjustment(image: Image.Image, delta: float = 0.0) -> Image.Image:
"""Adjust the hue of the image."""
if delta == 0.0:
return image
hsv_image = image.convert('HSV')
np_image = np.array(hsv_image)
np_image[:, :, 0] = (np_image[:, :, 0].astype(int) + delta) % 360
hsv_image = Image.fromarray(np_image, 'HSV')
return hsv_image.convert('RGB')
def saturation_adjustment(image: Image.Image, factor: float = 1.0) -> Image.Image:
"""Adjust the saturation of the image."""
enhancer = ImageEnhance.Color(image)
return enhancer.enhance(factor)
def shear(image: Image.Image, shear_factor: float = 0.0) -> Image.Image:
"""Apply shearing to the image."""
if shear_factor == 0.0:
return image
width, height = image.size
m = shear_factor
xshift = abs(m) * height
new_width = width + int(round(xshift))
return image.transform(
(new_width, height),
Image.AFFINE,
(1, m, -xshift if m > 0 else 0, 0, 1, 0),
Image.BICUBIC
)
def resize(image: Image.Image, size: tuple = (256, 256)) -> Image.Image:
"""Resize the image to the given size."""
return image.resize(size, Image.ANTIALIAS)
def grayscale_conversion(image: Image.Image) -> Image.Image:
"""Convert the image to grayscale."""
return ImageOps.grayscale(image)
def inversion(image: Image.Image) -> Image.Image:
"""Invert the image colors."""
return ImageOps.invert(image)
def random_erasing(image: Image.Image, probability: float = 0.5, rectangle_area: float = 0.02) -> Image.Image:
"""Randomly erase a rectangle region in the image."""
if np.random.rand() > probability:
return image
np_image = np.array(image)
h, w, _ = np_image.shape
area = h * w
target_area = area * rectangle_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:
top = np.random.randint(0, h - h_erase)
left = np.random.randint(0, w - w_erase)
np_image[top:top + h_erase, left:left + w_erase, :] = np.random.randint(0, 256)
return Image.fromarray(np_image)
def perspective_transform(image: Image.Image, scale: float = 0.5) -> Image.Image:
"""Apply a perspective transformation to the image."""
if scale <= 0:
return image
width, height = image.size
src_points = np.float32([
[0, 0],
[width, 0],
[width, height],
[0, height]
])
offset = width * scale
dst_points = np.float32([
[offset, offset],
[width - offset, offset],
[width - offset, height - offset],
[offset, height - offset]
])
matrix = cv2.getPerspectiveTransform(src_points, dst_points)
np_image = np.array(image)
transformed = cv2.warpPerspective(np_image, matrix, (width, height))
return Image.fromarray(transformed)
def zooming(image: Image.Image, zoom_factor: float = 1.0) -> Image.Image:
"""Zoom into the image by the given factor."""
if zoom_factor == 1.0:
return image
width, height = image.size
new_width, new_height = int(width * zoom_factor), int(height * zoom_factor)
image = image.resize((new_width, new_height), Image.ANTIALIAS)
if zoom_factor < 1.0:
pad_width = (width - new_width) // 2
pad_height = (height - new_height) // 2
new_image = Image.new("RGB", (width, height))
new_image.paste(image, (pad_width, pad_height))
return new_image
else:
left = (new_width - width) // 2
top = (new_height - height) // 2
return image.crop((left, top, left + width, top + height))
def gamma_correction(image: Image.Image, gamma: float = 1.0) -> Image.Image:
"""Apply gamma correction to the image."""
if gamma == 1.0:
return image
inv_gamma = 1.0 / gamma
table = [((i / 255.0) ** inv_gamma) * 255 for i in range(256)]
table = np.array(table).astype("uint8")
return image.point(table)
# Mapping augmentation names to functions
AUGMENTATION_FUNCTIONS: Dict[str, Callable[..., Image.Image]] = {
"Rotation": rotate,
"Scaling": scale,
"Cropping": crop,
"Flipping": flip,
"Brightness Adjustment": adjust_brightness,
"Contrast Adjustment": adjust_contrast,
"Gaussian Blur": gaussian_blur,
"Noise Injection": noise_injection,
"Sharpening": sharpen,
"Color Jitter": color_jitter,
"Hue Adjustment": hue_adjustment,
"Saturation Adjustment": saturation_adjustment,
"Shearing": shear,
"Resizing": resize,
"Grayscale Conversion": grayscale_conversion,
"Inversion": inversion,
"Random Erasing": random_erasing,
"Perspective Transformation": perspective_transform,
"Zooming": zooming,
"Gamma Correction": gamma_correction
}
def get_user_input() -> Dict[str, Any]:
"""
Placeholder function to get user inputs.
In a real-world scenario, this could be replaced with command-line arguments or a GUI.
"""
# Example inputs
image_paths = [
"path/to/image1.jpg",
"path/to/image2.png",
# Add more paths as needed
]
selected_augmentations = ["Rotation", "Brightness Adjustment", "Gaussian Blur"]
output_directory = "path/to/output"
augmentation_params = {
"Rotation": {"angle": 45},
"Brightness Adjustment": {"factor": 1.5},
"Gaussian Blur": {"radius": 2}
}
return {
"image_paths": image_paths,
"selected_augmentations": selected_augmentations,
"output_directory": output_directory,
"augmentation_params": augmentation_params
}
def apply_augmentations(image: Image.Image, augmentations: List[str],
params: Dict[str, Any]) -> Image.Image:
"""
Apply a sequence of augmentations to the image.
:param image: PIL Image object.
:param augmentations: List of augmentation names.
:param params: Dictionary of parameters for each augmentation.
:return: Augmented PIL Image object.
"""
for aug in augmentations:
func = AUGMENTATION_FUNCTIONS.get(aug)
if func:
param = params.get(aug, {})
logging.debug(f"Applying {aug} with params {param}")
image = func(image, **param)
return image
def process_image(path: str, output_dir: str, augmentations: List[str],
params: Dict[str, Any]) -> None:
"""
Process a single image: load, augment, and save.
:param path: Path to the input image.
:param output_dir: Directory to save the augmented image.
:param augmentations: List of augmentations to apply.
:param params: Parameters for augmentations.
"""
try:
if not os.path.isfile(path):
logging.warning(f"File does not exist: {path}")
return
ext = os.path.splitext(path)[1].lower()
if ext not in SUPPORTED_EXTENSIONS:
logging.warning(f"Unsupported file extension {ext} for file {path}")
return
image = load_image(path)
augmented_image = apply_augmentations(image, augmentations, params)
base_name = os.path.basename(path)
name, _ = os.path.splitext(base_name)
output_path = os.path.join(output_dir, f"{name}_augmented{ext}")
save_image(augmented_image, output_path)
logging.info(f"Processed and saved: {output_path}")
except Exception as e:
logging.error(f"Failed to process image {path}: {e}")
def main():
"""
Main function to execute the image augmentation pipeline.
"""
user_input = get_user_input()
image_paths = user_input["image_paths"]
selected_augmentations = user_input["selected_augmentations"]
output_directory = user_input["output_directory"]
augmentation_params = user_input["augmentation_params"]
# Create output directory if it doesn't exist
os.makedirs(output_directory, exist_ok=True)
# Use multiprocessing for efficiency
with concurrent.futures.ProcessPoolExecutor() as executor:
futures = [
executor.submit(
process_image,
path,
output_directory,
selected_augmentations,
augmentation_params
)
for path in image_paths
]
for future in concurrent.futures.as_completed(futures):
# Result is None; exceptions are handled within process_image
future.result()
if __name__ == "__main__":
main()
Explanation:
- Logging Configuration: Sets up a logging system to track the pipeline's progress and errors.
- Image Loading and Saving:
load_image handles various image formats, including HEIC using pyheif.
save_image saves the processed images to the specified output directory.
- Augmentation Functions: Each augmentation is implemented as a separate function, allowing for easy composition and scalability. Parameters for each function are provided with default values to ensure flexibility.
- Augmentation Mapping: A dictionary maps augmentation names to their corresponding functions, facilitating dynamic invocation based on user selection.
- User Input Placeholder: The
get_user_input function is a placeholder that provides example inputs. In a real-world scenario, this should be replaced with a method to capture user inputs dynamically, such as command-line arguments or a graphical user interface.
- Applying Augmentations: The
apply_augmentations function sequentially applies the selected augmentations with the provided parameters to each image.
- Image Processing: The
process_image function handles the complete process for a single image, including validation, loading, augmentation, and saving.
- Concurrency: Utilizes the
concurrent.futures.ProcessPoolExecutor to process multiple images in parallel, enhancing performance and scalability for large datasets.
- Error Handling: Comprehensive try-except blocks ensure that errors are logged with meaningful messages without halting the entire pipeline.
- Execution: The
main function orchestrates the entire pipeline, from fetching user inputs to initiating the concurrent processing of images.
Usage:
-
Update get_user_input: Replace the placeholder input in the get_user_input function with actual user inputs, such as reading from command-line arguments or a configuration file.
-
Run the Script: Execute the script using Python:
python image_augmentation_pipeline.py
-
Monitor Logs: The pipeline will log its progress, including any warnings or errors, to the console.
Notes:
- RAW Image Support: The current implementation raises a
NotImplementedError for RAW image formats. To support RAW images, integrate a library that can handle RAW formats and implement the corresponding loading mechanism.
- Hue Adjustment: PIL does not directly support hue adjustments. The provided
hue_adjustment function includes a placeholder for implementing hue changes, which may require more advanced color space manipulation.
- Extensibility: The modular design allows for easy addition of new augmentation techniques by defining new functions and updating the
AUGMENTATION_FUNCTIONS mapping.
This implementation provides a robust, efficient, and flexible pipeline for image augmentation, ready to be integrated and extended based on specific project requirements.