import os
from pathlib import Path
from typing import List, Callable, Union, Optional, Tuple
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import albumentations as A
def get_image_paths(directory: Union[str, Path], patterns: Optional[List[str]] = None) -> List[Path]:
"""
Retrieve a list of image file paths from the specified directory matching given patterns.
Args:
directory (Union[str, Path]): The directory containing images.
patterns (Optional[List[str]], optional): List of filename patterns to match.
Defaults to common image file extensions.
Returns:
List[Path]: A list of Paths to image files.
Raises:
RuntimeError: If the directory is invalid or an error occurs while accessing files.
"""
try:
directory_path = Path(directory)
if not directory_path.is_dir():
raise ValueError(f"{directory} is not a valid directory.")
if patterns is None:
patterns = ['*.jpg', '*.jpeg', '*.png', '*.bmp']
image_paths = []
for pattern in patterns:
image_paths.extend(directory_path.glob(pattern))
return image_paths
except Exception as e:
raise RuntimeError(f"Error getting image paths from {directory}: {e}") from e
def get_torchvision_transforms(
resize: Optional[Tuple[int, int]] = None,
normalize: bool = False,
augmentations: Optional[List[str]] = None
) -> Callable:
"""
Create a torchvision transformation pipeline.
Args:
resize (Optional[Tuple[int, int]], optional): Resize dimensions (Height, Width).
normalize (bool, optional): Whether to normalize the images.
augmentations (Optional[List[str]], optional): List of augmentation names to apply.
Returns:
Callable: A torchvision transformation pipeline.
"""
transform_list = []
if resize is not None:
transform_list.append(transforms.Resize(resize))
if augmentations:
for aug in augmentations:
if aug == 'RandomHorizontalFlip':
transform_list.append(transforms.RandomHorizontalFlip())
elif aug == 'RandomRotation':
transform_list.append(transforms.RandomRotation(degrees=15))
elif aug == 'ColorJitter':
transform_list.append(transforms.ColorJitter())
# Add more augmentations as needed
transform_list.append(transforms.ToTensor())
if normalize:
transform_list.append(transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]))
transform = transforms.Compose(transform_list)
return transform
def get_albumentations_transforms(
resize: Optional[Tuple[int, int]] = None,
normalize: bool = False,
augmentations: Optional[List[str]] = None
) -> Callable:
"""
Create an albumentations transformation pipeline.
Args:
resize (Optional[Tuple[int, int]], optional): Resize dimensions (Height, Width).
normalize (bool, optional): Whether to normalize the images.
augmentations (Optional[List[str]], optional): List of augmentation names to apply.
Returns:
Callable: An albumentations transformation pipeline.
"""
transform_list = []
if resize is not None:
transform_list.append(A.Resize(height=resize[0], width=resize[1]))
if augmentations:
for aug in augmentations:
if aug == 'HorizontalFlip':
transform_list.append(A.HorizontalFlip(p=0.5))
elif aug == 'Rotate':
transform_list.append(A.Rotate(limit=15))
elif aug == 'ColorJitter':
transform_list.append(A.ColorJitter())
# Add more augmentations as needed
if normalize:
transform_list.append(A.Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225)))
transform = A.Compose(transform_list)
return transform
class CustomImageDataset(Dataset):
"""
A custom dataset for loading images with optional transformations.
Attributes:
image_paths (List[Path]): List of image file paths.
transform (Optional[Callable]): Transformation function to apply.
use_albumentations (bool): Flag indicating usage of albumentations transformations.
"""
def __init__(
self,
image_paths: List[Union[str, Path]],
transform: Optional[Callable] = None,
use_albumentations: bool = False
):
"""
Initialize the dataset with image paths and transformations.
Args:
image_paths (List[Union[str, Path]]): List of image file paths.
transform (Optional[Callable], optional): Transformation function to apply.
use_albumentations (bool, optional): Whether to use albumentations for transformations.
"""
self.image_paths = [Path(p) for p in image_paths]
self.transform = transform
self.use_albumentations = use_albumentations
def __len__(self) -> int:
"""Return the total number of images."""
return len(self.image_paths)
def __getitem__(self, idx: int) -> torch.Tensor:
"""
Load an image and apply transformations.
Args:
idx (int): Index of the image to load.
Returns:
torch.Tensor: Transformed image tensor.
Raises:
RuntimeError: If an error occurs while processing the image.
"""
try:
image_path = self.image_paths[idx]
image = Image.open(image_path).convert("RGB") # Ensure RGB format
if self.use_albumentations and self.transform:
image_np = np.array(image)
augmented = self.transform(image=image_np)
image_np = augmented['image']
image = torch.from_numpy(image_np).permute(2, 0, 1).float()
else:
if self.transform:
image = self.transform(image)
else:
image = transforms.ToTensor()(image)
return image
except Exception as e:
raise RuntimeError(f"Error processing image {self.image_paths[idx]}: {e}") from e
def main():
"""
Main function to demonstrate loading images, applying transformations, and creating a DataLoader.
"""
# Define the image directory (replace with your actual path)
image_directory = '/path/to/your/images'
# Get list of image paths
image_paths = get_image_paths(image_directory)
# Define transformation parameters
resize_dims = (224, 224)
normalize_imgs = True
augmentations_list = ['RandomHorizontalFlip', 'RandomRotation'] # For torchvision
# augmentations_list = ['HorizontalFlip', 'Rotate'] # For albumentations
use_albumentations = False # Set True to use albumentations
# Get transformations
if use_albumentations:
transform = get_albumentations_transforms(
resize=resize_dims,
normalize=normalize_imgs,
augmentations=augmentations_list
)
else:
transform = get_torchvision_transforms(
resize=resize_dims,
normalize=normalize_imgs,
augmentations=augmentations_list
)
# Create dataset
dataset = CustomImageDataset(
image_paths=image_paths,
transform=transform,
use_albumentations=use_albumentations
)
# Create DataLoader
dataloader = DataLoader(dataset, batch_size=32, shuffle=True, num_workers=4)
# Iterate over DataLoader
for batch_idx, images in enumerate(dataloader):
print(f"Batch {batch_idx} - Image batch shape: {images.shape}")
# Perform further processing
# For demonstration, we break after the first batch
break
if __name__ == '__main__':
main()
This script provides a comprehensive solution for loading images, applying transformations with user control, and using either albumentations or torchvision for augmentations. Here's a summary of the key components:
-
Image Paths Loading: The get_image_paths function retrieves image file paths from a specified directory.
-
Transformations with User Control:
get_torchvision_transforms: Constructs a torchvision transformation pipeline based on user-specified parameters.
get_albumentations_transforms: Constructs an albumentations transformation pipeline based on user-specified parameters.
-
Custom Dataset: CustomImageDataset inherits from torch.utils.data.Dataset and handles image loading and transformation application, supporting both torchvision and albumentations.
-
Error Handling: Comprehensive error handling is implemented throughout the code, ensuring meaningful messages are provided and exceptions are raised appropriately.
-
Type Hints and PEP-8 Compliance: The code strictly adheres to PEP-8 standards, and type hints are used extensively for clarity and maintainability.
-
Main Execution Block: The main function demonstrates how to use the components:
- Configures parameters such as image directory, resize dimensions, normalization flag, and augmentations.
- Loads the image paths and creates the dataset and dataloader.
- Iterates over the dataloader and processes images.
Note: Replace '/path/to/your/images' with the actual path to your image directory.
This implementation ensures that the code is scalable, efficient, and robust, capable of handling large datasets while providing flexibility in transformations and augmentations.
Feel free to customize the augmentation lists, resize dimensions, and other parameters as needed for your specific use case.