
有如下代码,请问该如何去掉两重 for 循环,使用 numpy 的数组操作来实现呢?谢谢各位了
import numpy as np a = np.zeros((100, 100)) b = np.zeros((100, 100)) ds = [] for i in range(5, 95): for j in range(5, 95): pa = a[i-5:i+5, j-5:j+5] pb = b[i-5:i+5, j-5:j+5] d = pa - pb ds.append(d) return ds 1 necomancer 2019 年 6 月 6 日 from skimage.util.shape import view_as_windows a = np.random.random((100,100)) b = np.random.random((100,100)) ret = view_as_windows(a-b, (10,10)) In [1]: np.allclose(ret[:-1,:-1,:], ds.reshape(90,90,10,10)) Out[1]: True 顺带一提,view_as_windows 有 step 函数,你这个情况 step=1,是默认参数。 |
2 necomancer 2019 年 6 月 6 日 step=10 在你的例子里应该相当于刚好无重叠,可以用 view_as_blocks 函数。 |
3 necomancer 2019 年 6 月 6 日 这个函数基本上是在用 np.lib.stride_tricks.as_strided,所以如果你没有 skimage,去 skimage 找到那个函数拷过来就行。麻烦的地方只在怎么根据 window_size 和 step 算 stride |
4 going2think OP @necomancer 感谢帮助,我去试试~ |
5 xgdgsc 2019 年 6 月 7 日 这种直接改 numba |