Here are the four down‐scaling functions rewritten so that canvas_size is a 2-tuple (target_w, target_h). They’ll handle arbitrary input/output aspect ratios by computing float scale factors and slicing accordingly.
import numpy as np
import cv2
def downscale_nearest_neighbor(img: np.ndarray,
canvas_size: tuple[int,int]) -> np.ndarray:
"""
Nearest‐neighbor downscale.
canvas_size = (target_width, target_height).
"""
target_w, target_h = canvas_size
h, w = img.shape[:2]
scale_x = w / target_w
scale_y = h / target_h
out = np.zeros((target_h, target_w, 3), dtype=img.dtype)
for i in range(target_h):
for j in range(target_w):
src_x = min(int(j * scale_x), w-1)
src_y = min(int(i * scale_y), h-1)
out[i, j] = img[src_y, src_x]
return out
def downscale_averaging(img: np.ndarray,
canvas_size: tuple[int,int]) -> np.ndarray:
"""
Averaging downscale: for each output pixel, take the mean over the block
of source pixels that map onto it.
"""
target_w, target_h = canvas_size
h, w = img.shape[:2]
scale_x = w / target_w
scale_y = h / target_h
out = np.zeros((target_h, target_w, 3), dtype=np.float32)
for i in range(target_h):
y0 = int(round(i * scale_y))
y1 = int(round((i+1) * scale_y))
for j in range(target_w):
x0 = int(round(j * scale_x))
x1 = int(round((j+1) * scale_x))
block = img[y0:y1, x0:x1]
if block.size == 0:
continue
out[i, j] = block.mean(axis=(0,1))
return out.astype(img.dtype)
def downscale_mean(img: np.ndarray,
canvas_size: tuple[int,int]) -> np.ndarray:
"""
Identical to averaging (here for demonstration).
"""
# We can just call downscale_averaging:
return downscale_averaging(img, canvas_size)
def downscale_convolution(img: np.ndarray,
canvas_size: tuple[int,int],
kernel_size: int=3) -> np.ndarray:
"""
For each target pixel:
1) crop the corresponding source block
2) apply a box‐blur (cv2.blur) of `kernel_size`
3) average the blurred block
"""
target_w, target_h = canvas_size
h, w = img.shape[:2]
scale_x = w / target_w
scale_y = h / target_h
out = np.zeros((target_h, target_w, 3), dtype=np.float32)
for i in range(target_h):
y0 = int(round(i * scale_y))
y1 = int(round((i+1) * scale_y))
for j in range(target_w):
x0 = int(round(j * scale_x))
x1 = int(round((j+1) * scale_x))
block = img[y0:y1, x0:x1]
if block.size == 0:
continue
blurred = cv2.blur(block, (kernel_size, kernel_size))
out[i, j] = blurred.mean(axis=(0,1))
return out.astype(img.dtype)
Example of calling them in a notebook:
from PIL import Image
import matplotlib.pyplot as plt
# load image
img = np.array(Image.open("your_image.jpg"))
canvas_size = (80, 60) # e.g. 80px wide, 60px tall
nn = downscale_nearest_neighbor(img, canvas_size)
avg = downscale_averaging(img, canvas_size)
mean = downscale_mean(img, canvas_size)
conv = downscale_convolution(img, canvas_size, kernel_size=5)
fig, ax = plt.subplots(2, 2, figsize=(8,6))
for a, pic, title in zip(ax.flatten(),
[nn, avg, mean, conv],
["Nearest", "Averaging", "Mean", "Convolution"]):
a.imshow(pic)
a.set_title(title)
a.axis("off")
plt.tight_layout()
plt.show()
Now each function takes (width, height), handles non‐integer scale factors gracefully, and returns an RGB array you can plot with Matplotlib.