import os
import glob
from pathlib import Path
from typing import Callable, List, Optional, Tuple, Union
import numpy as np
import torch
import torchvision
from PIL import Image
import torchvision.transforms as T
import albumentations as A
def get_image_paths(
directory: Union[str, Path],
method: str = 'os',
file_extensions: Optional[List[str]] = None
) -> List[Path]:
"""
Retrieve a list of image file paths from a specified directory.
Args:
directory (Union[str, Path]): Directory to search for images.
method (str): Method for listing files ('os', 'glob', 'pathlib').
file_extensions (Optional[List[str]]): List of file extensions to include.
Returns:
List[Path]: List of image file paths.
Raises:
ValueError: If an invalid method is specified.
FileNotFoundError: If the directory does not exist.
RuntimeError: If an error occurs during file listing.
"""
if file_extensions is None:
file_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif']
if not isinstance(directory, Path):
directory = Path(directory)
if not directory.exists():
raise FileNotFoundError(f"The directory '{directory}' does not exist.")
image_paths = []
if method == 'os':
try:
for filename in os.listdir(directory):
file_path = directory / filename
if file_path.suffix.lower() in file_extensions and file_path.is_file():
image_paths.append(file_path)
except Exception as e:
raise RuntimeError(f"Error using os.listdir: {e}")
elif method == 'glob':
try:
for ext in file_extensions:
image_paths.extend(directory.glob(f'*{ext}'))
except Exception as e:
raise RuntimeError(f"Error using glob.glob: {e}")
elif method == 'pathlib':
try:
for file_path in directory.iterdir():
if file_path.suffix.lower() in file_extensions and file_path.is_file():
image_paths.append(file_path)
except Exception as e:
raise RuntimeError(f"Error using pathlib.Path.iterdir: {e}")
else:
raise ValueError(f"Invalid method '{method}'. Valid options are 'os', 'glob', 'pathlib'.")
return image_paths
def load_image(
image_path: Union[str, Path],
loader: str = 'PIL'
) -> Tuple[Union[Image.Image, torch.Tensor], Tuple[int, int, int]]:
"""
Load an image and obtain its size.
Args:
image_path (Union[str, Path]): Path to the image file.
loader (str): Image loading library to use ('PIL', 'torchvision').
Returns:
Tuple[Union[Image.Image, torch.Tensor], Tuple[int, int, int]]: Loaded image and its size (H, W, C).
Raises:
FileNotFoundError: If the image file does not exist.
ValueError: If an invalid loader is specified.
RuntimeError: If an error occurs during image loading.
"""
if not isinstance(image_path, Path):
image_path = Path(image_path)
if not image_path.exists():
raise FileNotFoundError(f"The image file '{image_path}' does not exist.")
if loader == 'PIL':
try:
image = Image.open(image_path)
width, height = image.size
if image.mode == 'RGB':
channels = 3
elif image.mode == 'L':
channels = 1
else:
channels = len(image.getbands())
size = (height, width, channels)
return image, size
except Exception as e:
raise RuntimeError(f"Error loading image with PIL: {e}")
elif loader == 'torchvision':
try:
image = torchvision.io.read_image(str(image_path)) # (C, H, W)
channels, height, width = image.shape
size = (height, width, channels)
return image, size
except Exception as e:
raise RuntimeError(f"Error loading image with torchvision: {e}")
else:
raise ValueError(f"Invalid loader '{loader}'. Valid options are 'PIL', 'torchvision'.")
class ImageProcessor:
"""
A class for processing images with resizing, normalization, and augmentations.
"""
def __init__(
self,
resize: Optional[Tuple[int, int]] = None,
normalize: Optional[Tuple[List[float], List[float]]] = None,
augmentations: Optional[List[Callable]] = None,
library: str = 'torchvision'
):
"""
Initialize the ImageProcessor.
Args:
resize (Optional[Tuple[int, int]]): Desired output size (width, height).
normalize (Optional[Tuple[List[float], List[float]]]): Means and stds for normalization.
augmentations (Optional[List[Callable]]): List of augmentation functions.
library (str): Transformation library ('torchvision', 'albumentations').
Raises:
ValueError: If an invalid library is specified.
"""
if library not in ['torchvision', 'albumentations']:
raise ValueError(f"Invalid library '{library}'. Valid options are 'torchvision', 'albumentations'.")
self.library = library
self.resize = resize
self.normalize = normalize
self.augmentations = augmentations
self.transform_pipeline = self._build_transform_pipeline()
def _build_transform_pipeline(self):
"""
Build the transformation pipeline based on specified parameters.
Returns:
Callable: The composed transformation pipeline.
"""
if self.library == 'torchvision':
transforms_list = []
if self.resize is not None:
transforms_list.append(T.Resize(self.resize))
if self.augmentations:
transforms_list.extend(self.augmentations)
transforms_list.append(T.ToTensor())
if self.normalize is not None:
mean, std = self.normalize
transforms_list.append(T.Normalize(mean=mean, std=std))
transform = T.Compose(transforms_list)
elif self.library == 'albumentations':
transforms_list = []
if self.resize is not None:
transforms_list.append(A.Resize(height=self.resize[1], width=self.resize[0]))
if self.augmentations:
transforms_list.extend(self.augmentations)
if self.normalize is not None:
mean, std = self.normalize
transforms_list.append(A.Normalize(mean=mean, std=std))
transform = A.Compose(transforms_list)
else:
raise ValueError(f"Invalid library '{self.library}'. Valid options are 'torchvision', 'albumentations'.")
return transform
def process_image(self, image: Union[Image.Image, np.ndarray]) -> Union[torch.Tensor, np.ndarray]:
"""
Apply the transformation pipeline to an image.
Args:
image (Union[Image.Image, np.ndarray]): Image to process.
Returns:
Union[torch.Tensor, np.ndarray]: Processed image.
Raises:
RuntimeError: If an error occurs during processing.
"""
try:
if self.library == 'torchvision':
transformed_image = self.transform_pipeline(image)
elif self.library == 'albumentations':
if isinstance(image, Image.Image):
image = np.array(image)
transformed = self.transform_pipeline(image=image)
transformed_image = transformed['image']
else:
raise ValueError(f"Invalid library '{self.library}'. Valid options are 'torchvision', 'albumentations'.")
return transformed_image
except Exception as e:
raise RuntimeError(f"Error processing image: {e}")
def process_images(
image_paths: List[Path],
image_loader: str = 'PIL',
processor: Optional[ImageProcessor] = None
) -> List[Union[torch.Tensor, np.ndarray]]:
"""
Load and process a list of images.
Args:
image_paths (List[Path]): List of image file paths.
image_loader (str): Image loading library to use ('PIL', 'torchvision').
processor (Optional[ImageProcessor]): ImageProcessor instance to apply transformations.
Returns:
List[Union[torch.Tensor, np.ndarray]]: List of processed images.
Raises:
RuntimeError: If an error occurs during image processing.
"""
processed_images = []
for image_path in image_paths:
try:
image, size = load_image(image_path, loader=image_loader)
if processor is not None:
processed_image = processor.process_image(image)
else:
processed_image = image
processed_images.append(processed_image)
except Exception as e:
print(f"Error processing image '{image_path}': {e}")
continue
return processed_images
This code provides a robust and scalable solution for loading and processing images with user-controlled resizing, normalization, and augmentations. It adheres to PEP-8 standards, includes comprehensive error handling with meaningful messages, and leverages Python's typing module for clarity and maintainability. The ImageProcessor class allows for flexible integration of either torchvision or albumentations libraries, enabling advanced image transformations suitable for large datasets and scalable applications.