mto*_*rne 5 python numpy image-processing scipy
我正在尝试实现一个函数,该函数将给定矩阵的每个3x3窗口求和(或最终平均),并使用每个窗口的结果创建一个小9x的矩阵.
我无法找到一个有效和简洁的方法来做numpy.
有任何想法吗 ?
谢谢!
最简单的numpy方法,在卷积方面做得少得多,因此可能比基于fileter的方法更快,是将原始数组调整为具有额外维度的数组,然后通过对新维度求和将其减少回正常:
>>> arr = np.arange(108).reshape(9, 12)
>>> rows, cols = arr.shape
>>> arr.reshape(rows//3, 3, cols//3, 3).sum(axis=(1, 3))
array([[117, 144, 171, 198],
[441, 468, 495, 522],
[765, 792, 819, 846]])
Run Code Online (Sandbox Code Playgroud)
如果你想要均值,你只需将得到的数组除以元素数:
>>> arr.reshape(rows//3, 3, cols//3, 3).sum(axis=(1, 3)) / 9
array([[ 13., 16., 19., 22.],
[ 49., 52., 55., 58.],
[ 85., 88., 91., 94.]])
Run Code Online (Sandbox Code Playgroud)
此方法仅在您的数组的形状本身是3的倍数时才有效.