如何将 2D 矩阵分成小块并将每个小块乘以其中心元素?

How to divide a 2D matrix into patches and multiply each patch by its center element?

我需要将一个二维矩阵分成一组具有一定步长的二维补丁,然后将每个补丁乘以它的中心元素并对每个补丁的元素求和。

这感觉不像卷积,其中单独的内核用于矩阵的每个元素。

下面是一个直观的插图。 结果矩阵的元素是这样计算的:

结果应如下所示:

这是我想出的解决方案:

window_shape = (2, 2)
stride = 1

# Matrix
m = np.arange(1, 17).reshape((4, 4))

# Pad it once per axis to make sure the number of views
# equals the number of elements
m_padded = np.pad(m, (0, 1))

# This function divides the array into `windows`, from:
# 
w = window_nd(m_padded, window_shape, stride)
ww, wh, *_ = w.shape
w = w.reshape((ww * wh, 4))  # Two first dimensions multiplied is the number of rows

# Tile each center element for element-wise multiplication
m_tiled = np.tile(m.ravel(), (4, 1)).transpose()

result = (w * m_tiled).sum(axis = 1).reshape(m.shape)

我认为它不是很有效,因为在中间步骤中分配了一些数组。

完成此任务的更好或更有效的方法是什么?

尝试scipy.signal.convolve

from scipy.signal import convolve

window_shape = (2, 2)
stride = 1

# Matrix
m = np.arange(1, 17).reshape((4, 4))

# Pad it once per axis to make sure the number of views
# equals the number of elements
m_padded = np.pad(m, (0, 1))

output = convolve(m_padded, np.ones(window_shape), 'valid') * m
print(output)

输出:

array([[ 14.,  36.,  66.,  48.],
       [150., 204., 266., 160.],
       [414., 500., 594., 336.],
       [351., 406., 465., 256.]])