Certainly! Below is a Python function that bins an image into N x N blocks, correctly handling border issues and accommodating arbitrary image dimensions where the image dimensions may not be perfectly divisible by N. This function supports both grayscale and multi-channel (e.g., RGB) images.
Function Overview
-
Input Parameters:
image: A NumPy array representing the input image. It can be a 2D array for grayscale images or a 3D array for color images.
N: The bin size, indicating the number of pixels to combine along each dimension.
-
Output:
- A binned (downsampled) version of the input image as a NumPy array.
Key Features
-
Handles Arbitrary Dimensions: The function calculates the number of bins needed along each dimension using the ceiling of the division, ensuring all pixels are included without padding.
-
Border Handling: For bins at the borders where the remaining pixels are fewer than N, the function correctly computes the mean of the available pixels without raising errors.
-
Supports Multi-channel Images: Whether the input image is grayscale or has multiple channels (like RGB), the function processes each channel appropriately.
-
Efficient Computation: While the function uses loops for clarity, it's optimized to handle large images reasonably well. For even better performance, especially on very large images, vectorization or specialized libraries can be considered.
Implementation
import numpy as np
import math
def bin_image(image: np.ndarray, N: int) -> np.ndarray:
"""
Bins the input image into non-overlapping N x N blocks.
Parameters:
- image (np.ndarray): Input image array. Can be 2D (grayscale) or 3D (e.g., RGB).
- N (int): Bin size. The image will be downsampled by averaging over N x N blocks.
Returns:
- binned_image (np.ndarray): The binned (downsampled) image.
"""
if N <= 0:
raise ValueError("Bin size N must be a positive integer.")
# Determine if image is grayscale or multi-channel
if image.ndim == 2:
H, W = image.shape
C = 1
image = image[:, :, np.newaxis] # Add channel axis for uniform processing
elif image.ndim == 3:
H, W, C = image.shape
else:
raise ValueError("Input image must be a 2D (grayscale) or 3D (color) array.")
# Calculate the number of bins along each dimension
H_bins = math.ceil(H / N)
W_bins = math.ceil(W / N)
# Initialize the binned image
if C == 1:
binned_image = np.zeros((H_bins, W_bins), dtype=image.dtype)
else:
binned_image = np.zeros((H_bins, W_bins, C), dtype=image.dtype)
for i in range(H_bins):
for j in range(W_bins):
# Define the start and end indices for the current bin
h_start = i * N
h_end = min((i + 1) * N, H)
w_start = j * N
w_end = min((j + 1) * N, W)
# Extract the block
block = image[h_start:h_end, w_start:w_end, :] # Shape: (block_H, block_W, C)
# Compute the mean along the first two axes (height and width)
block_mean = block.mean(axis=(0, 1))
if C == 1:
binned_image[i, j] = block_mean[0]
else:
binned_image[i, j, :] = block_mean
# If the original image was grayscale, remove the singleton channel dimension
if C == 1:
binned_image = binned_image.squeeze(axis=2)
return binned_image
Usage Example
import numpy as np
import matplotlib.pyplot as plt
# Create a sample grayscale image (e.g., 103x97)
H, W = 103, 97
grayscale_image = np.random.rand(H, W)
# Bin size
N = 10
# Bin the image
binned_grayscale = bin_image(grayscale_image, N)
print("Original shape:", grayscale_image.shape)
print("Binned shape:", binned_grayscale.shape)
# Display the original and binned images
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.title("Original Grayscale Image")
plt.imshow(grayscale_image, cmap='gray')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title(f"Binned Image ({N}x{N})")
plt.imshow(binned_grayscale, cmap='gray')
plt.axis('off')
plt.show()
# Example with a color image (e.g., RGB)
H_color, W_color = 150, 200
color_image = np.random.rand(H_color, W_color, 3) # Random RGB image
# Bin the color image
binned_color = bin_image(color_image, N)
print("Original color shape:", color_image.shape)
print("Binned color shape:", binned_color.shape)
# Display the original and binned color images
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.title("Original Color Image")
plt.imshow(color_image)
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title(f"Binned Color Image ({N}x{N})")
plt.imshow(binned_color)
plt.axis('off')
plt.show()
Explanation
-
Input Validation: The function first checks if the bin size N is a positive integer. It also verifies if the input image is either 2D (grayscale) or 3D (color).
-
Dimension Handling: For uniform processing, grayscale images are reshaped to have a third channel dimension. This allows the same logic to apply to both grayscale and color images.
-
Binning Logic:
- The number of bins along each dimension is calculated using the ceiling function to ensure all pixels are covered.
- The function iterates over each bin position, calculates the appropriate slice indices, and extracts the corresponding block from the image.
- The mean of each block is computed to represent the binned pixel value. For color images, the mean is computed for each channel separately.
-
Output Formatting: After binning, if the original image was grayscale, the singleton channel dimension is removed to return a 2D array.
-
Visualization: The usage example demonstrates how to apply the function to both grayscale and color images, including how to visualize the results using matplotlib.
Notes
-
Performance Considerations: For very large images or real-time applications, consider using more optimized libraries or vectorized operations to improve performance.
-
Alternate Binning Strategies: While this function uses the mean to bin pixels, other strategies (e.g., median, max) can be implemented by modifying the block aggregation step.
-
Edge Cases: The function gracefully handles cases where the image dimensions are not perfectly divisible by N, ensuring that no data is lost.