Okay, let's add four more downscaling functions, focusing on methods that can give a distinct pixel-art feel, especially ones that might emphasize specific colors or sharp transitions.
We'll add:
- Mode Pooling (Most Frequent Color): Instead of averaging, this method selects the color that appears most frequently within each block. This can result in more vibrant and distinct pixels, as it picks an actual color from the original image rather than a blended average.
- Median Pooling: Similar to averaging, but it takes the median color value for each channel within the block. The median is less sensitive to outliers (noise) than the mean and can sometimes preserve edges better.
- OpenCV's
INTER_NEAREST: This is OpenCV's optimized implementation of nearest neighbor interpolation. It will be much faster than our custom loop-based downscale_nearest_neighbor and is good for comparison.
- Pre-Sharpened Nearest Neighbor: Applies a sharpening filter to the high-resolution image before downscaling with the nearest neighbor method. This can make the resulting pixel art appear crisper and define edges more clearly.
Let's include the necessary imports and then the new functions.
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2 # For convolution and other image processing functions
from collections import Counter # For mode pooling
# from scipy.stats import mode # Alternative for mode, but Counter is more direct for colors
# --- Original Functions (just to ensure they are available for context if you run this in a new cell) ---
def downscale_nearest_neighbor(img, canvas_size):
height, width, _ = img.shape
canvas_width, canvas_height = canvas_size
scale_h = height / canvas_height
scale_w = width / canvas_width
downscaled = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)
for i in range(canvas_height):
for j in range(canvas_width):
x = int(i * scale_h)
y = int(j * scale_w)
downscaled[i, j] = img[x, y]
return downscaled
def downscale_averaging(img, canvas_size):
height, width, _ = img.shape
canvas_width, canvas_height = canvas_size
scale_h = height / canvas_height
scale_w = width / canvas_width
downscaled = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)
for i in range(canvas_height):
for j in range(canvas_width):
x_start = int(i * scale_h)
y_start = int(j * scale_w)
x_end = int((i + 1) * scale_h)
y_end = int((j + 1) * scale_w)
downscaled[i, j] = np.mean(img[x_start:x_end, y_start:y_end], axis=(0, 1))
return downscaled.astype(np.uint8)
def downscale_mean(img, canvas_size):
# This is effectively the same as downscale_averaging for color images
return downscale_averaging(img, canvas_size)
def downscale_convolution(img, canvas_size, kernel_size=3):
height, width, _ = img.shape
canvas_width, canvas_height = canvas_size
scale_h = height / canvas_height
scale_w = width / canvas_width
downscaled = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)
for i in range(canvas_height):
for j in range(canvas_width):
x_start = int(i * scale_h)
y_start = int(j * scale_w)
x_end = int((i + 1) * scale_h)
y_end = int((j + 1) * scale_w)
region = img[x_start:x_end, y_start:y_end]
if region.size > 0:
blurred = cv2.blur(region, (kernel_size, kernel_size))
downscaled[i, j] = np.mean(blurred, axis=(0, 1)).astype(np.uint8)
return downscaled
# --- New Downscaling Functions ---
def downscale_mode_pooling(img, canvas_size):
height, width, _ = img.shape
canvas_width, canvas_height = canvas_size
scale_h = height / canvas_height
scale_w = width / canvas_width
downscaled = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)
for i in range(canvas_height):
for j in range(canvas_width):
x_start = int(i * scale_h)
y_start = int(j * scale_w)
x_end = int((i + 1) * scale_h)
y_end = int((j + 1) * scale_w)
region = img[x_start:x_end, y_start:y_end].reshape(-1, 3) # Flatten pixels to (N, 3)
if region.size > 0:
# Convert RGB tuples to hashable string/tuple for Counter
pixel_colors = [tuple(p) for p in region]
# Find the most common color
most_common = Counter(pixel_colors).most_common(1)
if most_common:
downscaled[i, j] = np.array(most_common[0][0])
else:
downscaled[i, j] = [0, 0, 0] # Default to black if no pixels (shouldn't happen with proper scaling)
else:
downscaled[i, j] = [0, 0, 0] # Default to black
return downscaled
def downscale_median_pooling(img, canvas_size):
height, width, _ = img.shape
canvas_width, canvas_height = canvas_size
scale_h = height / canvas_height
scale_w = width / canvas_width
downscaled = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)
for i in range(canvas_height):
for j in range(canvas_width):
x_start = int(i * scale_h)
y_start = int(j * scale_w)
x_end = int((i + 1) * scale_h)
y_end = int((j + 1) * scale_w)
region = img[x_start:x_end, y_start:y_end]
if region.size > 0:
downscaled[i, j] = np.median(region, axis=(0, 1)).astype(np.uint8)
else:
downscaled[i, j] = [0, 0, 0] # Default to black
return downscaled
def downscale_opencv_nearest(img, canvas_size):
# OpenCV expects (width, height) for size argument
canvas_width, canvas_height = canvas_size
# cv2.resize automatically handles the interpolation
downscaled = cv2.resize(img, (canvas_width, canvas_height), interpolation=cv2.INTER_NEAREST)
return downscaled
def downscale_pre_sharpened_nearest(img, canvas_size, sharpen_kernel=None):
# Define a common sharpening kernel
if sharpen_kernel is None:
sharpen_kernel = np.array([
[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]
], dtype=np.float32)
# Apply sharpening
# Use cv2.filter2D for convolution, result can have values outside 0-255
sharpened_img = cv2.filter2D(img, -1, sharpen_kernel) # -1 means output depth same as input
# Clip values to 0-255 range and convert to uint8
sharpened_img = np.clip(sharpened_img, 0, 255).astype(np.uint8)
# Then downscale using nearest neighbor (using our custom function for consistency, or OpenCV's)
return downscale_nearest_neighbor(sharpened_img, canvas_size)
# Alternatively, using OpenCV's built-in for final downscaling:
# return downscale_opencv_nearest(sharpened_img, canvas_size)
How to Use and Compare
Now, let's load an image and run all the downscaling methods, then plot them for comparison.
# --- Setup and Load Image ---
image_path = "your_image.jpg" # !!! IMPORTANT: Replace with the actual path to your image !!!
img = Image.open(image_path).convert("RGB") # Ensure RGB mode
img_array = np.array(img)
# Define target pixel art canvas size (width, height)
# Make sure the aspect ratio is something you'd expect for pixel art
canvas_size_w = 64
canvas_size_h = 48
canvas_size = (canvas_size_w, canvas_size_h) # Example: 64x48 pixels
# --- Apply All Downscaling Methods ---
nn_downscaled = downscale_nearest_neighbor(img_array, canvas_size)
avg_downscaled = downscale_averaging(img_array, canvas_size)
mean_downscaled = downscale_mean(img_array, canvas_size) # Same as averaging
conv_downscaled = downscale_convolution(img_array, canvas_size)
mode_downscaled = downscale_mode_pooling(img_array, canvas_size)
median_downscaled = downscale_median_pooling(img_array, canvas_size)
opencv_nn_downscaled = downscale_opencv_nearest(img_array, canvas_size)
sharpened_nn_downscaled = downscale_pre_sharpened_nearest(img_array, canvas_size)
# --- Plotting the Results ---
# Prepare for plotting (7 subplots: original + 6 methods)
fig, axes = plt.subplots(3, 3, figsize=(15, 12)) # Adjust layout as needed
axes = axes.flatten()
# Plot the original image (downsampled by PIL for context, not pixelated)
axes[0].imshow(img.resize(canvas_size, Image.NEAREST)) # Resize to canvas_size for visual comparison of scale
axes[0].set_title("Original (Resized for Scale)")
# Plot all processed images
axes[1].imshow(nn_downscaled)
axes[1].set_title("Nearest Neighbor (Custom)")
axes[2].imshow(avg_downscaled)
axes[2].set_title("Averaging")
axes[3].imshow(mode_downscaled)
axes[3].set_title("Mode Pooling")
axes[4].imshow(median_downscaled)
axes[4].set_title("Median Pooling")
axes[5].imshow(opencv_nn_downscaled)
axes[5].set_title("OpenCV Nearest Neighbor")
axes[6].imshow(sharpened_nn_downscaled)
axes[6].set_title("Pre-Sharpened Nearest Neighbor")
axes[7].imshow(conv_downscaled)
axes[7].set_title("Convolution (Box Blur)")
# Hide unused subplot if any (e.g., if you have an odd number of plots)
if len(axes) > 8:
for i in range(8, len(axes)):
fig.delaxes(axes[i])
for ax in axes:
ax.axis('off') # Hide axes ticks and labels for cleaner image display
plt.tight_layout() # Adjust subplot params for a tight layout
plt.show()
Explanation of New Methods:
- Mode Pooling: This is great for a more "hard-edged" pixel art look where each block's color is directly represented by the most common color found in the original high-resolution pixels that map to that block. It avoids the blurring that averaging introduces.
- Median Pooling: Offers a compromise between nearest neighbor (sharp) and averaging (blurry). It's robust to outliers and can preserve edges better than the mean, resulting in a cleaner block without too much blurring.
- OpenCV Nearest Neighbor: Included to show that optimized libraries often provide the fastest and sometimes most robust implementations. For a simple
nearest_neighbor effect, cv2.resize with cv2.INTER_NEAREST is highly recommended for production code.
- Pre-Sharpened Nearest Neighbor: This technique recognizes that pixel art often benefits from clearly defined boundaries. By sharpening the image first, you emphasize edges, and then the subsequent nearest-neighbor downscaling translates those emphasized edges into clearer pixel boundaries. You can experiment with different sharpening kernels for varied effects.
Experiment with different canvas_size values and image inputs to see which method gives you the "pixel art" aesthetic you're looking for!