arr = np.random.rand(256, 256)
mask = np.random.rand(3, 3)
arr_view = as_strided(arr, shape=(254, 254, 3, 3), strides=arr.strides * 2)
arr[1:-1, 1:-1] = np.einsum('ijkl,kl->ij', arr_view, mask)
How to perform iterative 2D operation on 4D numpy array