这是(我认为)您的问题的可能解决方案:
def pixelate(img, wx, wy=None):
wy = wy or wx
y, x = img.shape
if x % wx != 0 or y % wy != 0:
raise ValueError("Invalid window size.")
ny = y // wy
nx = x // wx
windowed = img.reshape((ny, wy, nx, wx))
means = windowed.mean(axis=(1, 3), keepdims=True)
means = np.tile(means, (1, wy, 1, wx))
result = means.reshape((y, x))
return result
其中img 是表示图像的 2D NumPy 数组,wx 是窗口的水平尺寸,wy 是垂直尺寸(默认与 wy 相同)。图像必须能被窗口大小整除。基本上,它将图像数组重塑为其窗口,计算均值,平铺结果并重新整形。
这是一个带有圆周的示例:
import numpy as np
import matplotlib.pyplot as plt
def pixelate(img, wx, wy=None):
wy = wy or wx
y, x = img.shape
if x % wx != 0 or y % wy != 0:
raise ValueError("Invalid window size.")
ny = y // wy
nx = x // wx
windowed = img.reshape((ny, wy, nx, wx))
means = windowed.mean(axis=(1, 3), keepdims=True)
means = np.tile(means, (1, wy, 1, wx))
result = means.reshape((y, x))
return result
# Build a circumference
WIDTH = 400
HEIGHT = 300
RADIUS = 100
THICKNESS = 10
xx, yy = np.meshgrid(np.arange(WIDTH) - WIDTH / 2, np.arange(HEIGHT) - HEIGHT / 2)
r = np.sqrt(np.square(xx) + np.square(yy))
circ = (r > (RADIUS - THICKNESS / 2)) & (r < (RADIUS + THICKNESS / 2))
circ = circ.astype(np.float32)
# Pixelate
WINDOW_SIZE = 20
circ_pix = pixelate(circ, WINDOW_SIZE)
# Show
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.imshow(circ, "binary")
ax2 = fig.add_subplot(122)
ax2.imshow(circ_pix, "binary")
输出: