from PIL import Image
import torch
import numpy as np
from torchvision import transforms
file_img = r"C:\Users\heman\Desktop\Coding\buliding.jpg"
load_image = Image.open(file_img)
transform = transforms.Compose([
transforms.Resize((244, 244)), # Resize the image to (244, 244)
transforms.ToTensor(), # Convert the image to a tensor and normalize to [0, 1]
])
image_tensor = transform(load_image)
batch = torch.stack([image_tensor, image_tensor]) # Stack along a new batch dimension
print(f"Image Tensor Shape (C, H, W): {image_tensor.shape}") # (3, 244, 244)
print(f"Batch Shape: {batch.shape}") # (2, 3, 244, 244)
Certainly! Below is a comprehensive guide on how to apply all the image_manipulation API functions to an image and visualize the results using Plotly. This guide will:
Load and preprocess the image.
Apply all image manipulation functions.
Convert the processed tensors back to images.
Plot the original and manipulated images using Plotly.
Prerequisites
Ensure you have the following libraries installed:
bash
pip install torch torchvision Pillow plotly
Step-by-Step Implementation
python
import torch
from image_manipulation import (
anisotropic_diffusion_patch_filtering,
autoregressive_patch_prediction,
covariance_patch_whitening,
cross_domain_random_permutation,
entropy_based_patch_swap,
directional_patch_gradient_swapping,
fourier_patch_mixing,
frequency_aware_patch_scaling,
frequency_selective_patch_masking,
gabor_filter_patch_augmentation,
kurtosis_based_patch_selection,
laplacian_pyramid_blending,
apply_lbp_patch_encoding,
mrf_patch_stitching,
add_random_gaussian_noise_to_patches,
stochastic_patch_replacement,
temporal_patch_mixing,
texture_based_patch_reorganization,
wavelet_patch_fusion
)
from PIL import Image
import numpy as np
from torchvision import transforms
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Function to convert a tensor to a NumPy array suitable for Plotly
def tensor_to_image(tensor):
"""
Convert a torch tensor to a NumPy array for Plotly.
Assumes tensor shape is (C, H, W) and values are in [0, 1].
"""
tensor = tensor.detach().cpu()
if tensor.ndimension() == 4:
tensor = tensor[0] # Take the first image in the batch
tensor = tensor.clamp(0, 1) # Ensure values are within [0,1]
np_image = tensor.permute(1, 2, 0).numpy() # (H, W, C)
return np_image
# Load and preprocess the image
file_img = r"C:\Users\heman\Desktop\Coding\buliding.jpg"
load_image = Image.open(file_img).convert("RGB") # Ensure image is in RGB
transform = transforms.Compose([
transforms.Resize((244, 244)), # Resize the image to (244, 244)
transforms.ToTensor(), # Convert the image to a tensor and normalize to [0, 1]
])
image_tensor = transform(load_image)
# Create a batch with two identical images
batch = torch.stack([image_tensor, image_tensor]) # Shape: (2, 3, 244, 244)
print(f"Image Tensor Shape (C, H, W): {image_tensor.shape}") # (3, 244, 244)
print(f"Batch Shape: {batch.shape}") # (2, 3, 244, 244)
# Dictionary to hold the function names and their corresponding functions
manipulation_functions = {
"Anisotropic Diffusion": anisotropic_diffusion_patch_filtering,
"Autoregressive Prediction": autoregressive_patch_prediction,
"Covariance Whitening": covariance_patch_whitening,
"Cross-Domain Permutation": cross_domain_random_permutation,
"Entropy-Based Patch Swap": entropy_based_patch_swap,
"Directional Gradient Swap": directional_patch_gradient_swapping,
"Fourier Patch Mixing": fourier_patch_mixing,
"Frequency Aware Scaling": frequency_aware_patch_scaling,
"Frequency Selective Masking": frequency_selective_patch_masking,
"Gabor Filter Augmentation": gabor_filter_patch_augmentation,
"Kurtosis-Based Selection": kurtosis_based_patch_selection,
"Laplacian Pyramid Blending": laplacian_pyramid_blending,
"LBP Patch Encoding": apply_lbp_patch_encoding,
"MRF Patch Stitching": mrf_patch_stitching,
"Add Gaussian Noise": add_random_gaussian_noise_to_patches,
"Stochastic Patch Replacement": stochastic_patch_replacement,
"Temporal Patch Mixing": temporal_patch_mixing,
"Texture Patch Reorganization": texture_based_patch_reorganization,
"Wavelet Patch Fusion": wavelet_patch_fusion
}
# Apply all manipulation functions
processed_tensors = {}
for name, func in manipulation_functions.items():
try:
# Assuming all functions take 'tensor' and 'patch_size' as arguments
# Adjust arguments as per your actual API
processed = func(tensor=batch, patch_size=(16, 16))
processed_tensors[name] = processed
print(f"Applied: {name}")
except Exception as e:
print(f"Failed to apply {name}: {e}")
# Prepare images for plotting
images = {}
# Original Images
images["Original Image 1"] = tensor_to_image(batch[0])
images["Original Image 2"] = tensor_to_image(batch[1])
# Processed Images
for name, tensor in processed_tensors.items():
images[name + " (Image 1)"] = tensor_to_image(tensor[0])
images[name + " (Image 2)"] = tensor_to_image(tensor[1])
# Determine the number of images to plot
num_images = len(images)
cols = 3 # Number of columns in the plot grid
rows = num_images // cols + int(num_images % cols != 0)
# Create subplots
fig = make_subplots(
rows=rows,
cols=cols,
subplot_titles=list(images.keys()),
horizontal_spacing=0.02,
vertical_spacing=0.05
)
# Add images to the subplots
for idx, (title, img) in enumerate(images.items()):
row = idx // cols + 1
col = idx % cols + 1
fig.add_trace(
go.Image(z=img),
row=row,
col=col
)
# Update layout
fig.update_layout(
height=300 * rows, # Adjust height based on number of rows
width=300 * cols, # Adjust width based on number of columns
title_text="Original and Manipulated Images",
showlegend=False
)
# Hide axis lines and labels for all subplots
fig.update_xaxes(showticklabels=False).update_yaxes(showticklabels=False)
# Display the plot
fig.show()
Explanation of the Code
Conversion Function (tensor_to_image):
Purpose: Converts a PyTorch tensor to a NumPy array suitable for Plotly.
Process:
Moves the tensor to CPU and detaches it from the computation graph.
Clamps the tensor values to ensure they are within [0, 1].
Permutes the tensor dimensions from (C, H, W) to (H, W, C) which is the format expected by Plotly.
Converts the tensor to a NumPy array.
Loading and Preprocessing:
Image Loading: The image is loaded using PIL and converted to RGB to ensure consistency.
Transformation: The image is resized to (244, 244) and converted to a tensor with values normalized between [0, 1].
Batch Creation: A batch of two identical images is created for demonstration purposes.
Applying Image Manipulation Functions:
All functions from the image_manipulation module are stored in a dictionary with descriptive names.
Each function is applied to the batch with a specified patch_size. Adjust patch_size or other parameters if necessary based on your specific API requirements.
The results are stored in the processed_tensors dictionary. Error handling is included to catch and report any issues during function application.
Preparing Images for Plotting:
Both original images and their manipulated versions are converted to NumPy arrays using the tensor_to_image function.
Each manipulated image is labeled with its corresponding manipulation function name for clarity.
Plotting with Plotly:
Subplot Configuration: The number of rows and columns is determined based on the total number of images. Adjust cols as needed for your display preferences.
Adding Images: Each image is added to the subplot grid with its title.
Layout Adjustments: The overall figure size is adjusted based on the number of rows and columns. Axis lines and labels are hidden for a cleaner look.
Display: The final figure is displayed in an interactive window, allowing for zooming and panning.
Notes
Performance: Plotting a large number of images can be resource-intensive. Adjust the grid size (cols) and consider processing a subset of functions if performance becomes an issue.
Function Parameters: Ensure that each function from the image_manipulation module is compatible with the provided arguments. Modify the argument list (patch_size, etc.) as necessary based on each function's signature.
Batch Size: The current implementation plots both images in the batch. If you prefer to plot only one image, adjust the tensor_to_image calls accordingly.
Example Output
The resulting Plotly figure will display the original images alongside each manipulated version in an interactive grid. Each subplot will have a title indicating the type of manipulation applied, allowing for easy comparison and analysis.
Feel free to adjust the grid size, image selection, and other parameters to best fit your specific requirements. This template provides a robust starting point for visualizing the effects of various image manipulation techniques using Plotly.