【发布时间】:2014-11-05 09:12:33
【问题描述】:
我有一个二维 numpy 数组 input_array 和两个索引列表(x_coords 和 y_coords)。我想为以 x,y 坐标为中心的每个 x,y 对切片一个 3x3 子数组。最终结果将是一个 3x3 子数组的数组,其中子数组的数量等于我拥有的坐标对的数量。
最好避免 for 循环。目前,我使用 scipy 食谱中的生命跨步游戏修改: http://wiki.scipy.org/Cookbook/GameOfLifeStrides
shape = (input_array.shape[0] - 2, input_array.shape[0] - 2, 3, 3)
strides = input_array.strides + input_array.strides
strided = np.lib.stride_trics.as_strided(input_array, shape=shape, strides=strides).\
reshape(shape[0]*shape[1], shape[2], shape[3])
这会将原始数组的视图创建为所有可能的 3x3 子数组的(展平)数组。然后我转换 x,y 坐标对,以便能够从 strided 中选择我想要的子数组:
coords = x_coords - 1 + (y_coords - 1)*shape[1]
sub_arrays = strided[coords]
虽然这很好用,但我确实觉得它有点麻烦。有没有更直接的方法来做到这一点?另外,将来我想将其扩展到 3D 案例;从 nxmxk 数组中切片 nx3x3 子数组。也可以使用 strides,但到目前为止我还不能让它在 3D 中工作
【问题讨论】: