Sure! Here's how you can split your image into sections of size side_length x side_length and plot them on subplots. I'll assume side_length is a variable you'll define, e.g., side_length = 32.
import matplotlib.pyplot as plt
import numpy as np
def split_and_plot_image(image_array, side_length):
"""
Splits an image into sections of size side_length x side_length and plots them on subplots.
Args:
image_array: Input image as numpy array (H, W, 3)
side_length: Size of each section (height and width)
"""
# Get image dimensions
height, width, _ = image_array.shape
# Calculate the number of sections in each dimension
num_rows = height // side_length
num_cols = width // side_length
# Create subplots
fig, axes = plt.subplots(num_rows, num_cols, figsize=(16, 9))
for i in range(num_rows):
for j in range(num_cols):
# Calculate the start and end indices for the current section
start_row = i * side_length
end_row = start_row + side_length
start_col = j * side_length
end_col = start_col + side_length
# Extract the current section
section = image_array[start_row:end_row, start_col:end_col]
# Plot the section on the corresponding subplot
ax = axes[i, j]
ax.imshow(section)
ax.axis('off')
# Hide any remaining subplots if the image dimensions aren't perfectly divisible by side_length
for i in range(num_rows):
for j in range(num_cols, width // side_length):
axes[i, j].axis('off')
for i in range(num_rows, height // side_length):
for j in range(num_cols):
axes[i, j].axis('off')
plt.tight_layout()
plt.show()
# Example usage
side_length = 32 # Define the size of each section
downsized_array = claude_downscale_nearest_neighbor(img_array, canvas_size)
quantized_array = quantize_to_palette(downsized_array, colors)
split_and_plot_image(quantized_array, side_length)
Explanation
-
Calculate the number of sections:
num_rows and num_cols determine how many sections fit into the image's height and width, respectively.
-
Create subplots:
plt.subplots(num_rows, num_cols, figsize=(16, 9)) creates a grid of subplots.
-
Iterate through sections:
- For each section, calculate its start and end indices.
- Extract the section from the image.
- Plot the section on the corresponding subplot.
-
Hide unused subplots:
- If the image dimensions aren't perfectly divisible by
side_length, some subplots may remain empty. These are hidden using ax.axis('off').
-
Display the plot:
plt.tight_layout() ensures that subplots are neatly arranged.
plt.show() displays the plot.