我正在实现一种算法,它要求我在(严格二维)numpy数组中查看非重叠的连续子矩阵.例如,对于12乘12

>>> a = np.random.randint(20, size=(12, 12)); a

array([[ 4, 0, 12, 14, 3, 8, 14, 12, 11, 18, 6, 6],

[15, 13, 2, 18, 15, 15, 16, 2, 9, 16, 6, 4],

[18, 18, 3, 8, 1, 15, 14, 13, 13, 13, 7, 0],

[ 1, 9, 3, 6, 0, 4, 3, 15, 0, 9, 11, 12],

[ 5, 15, 5, 6, 4, 4, 18, 13, 10, 17, 11, 8],

[13, 17, 8, 15, 17, 12, 7, 1, 13, 15, 0, 18],

[ 2, 1, 11, 12, 3, 16, 11, 9, 10, 15, 4, 16],

[19, 11, 10, 7, 10, 19, 7, 13, 11, 9, 17, 8],

[14, 14, 17, 0, 0, 0, 11, 1, 10, 14, 2, 7],

[ 6, 15, 6, 7, 15, 19, 2, 4, 6, 16, 0, 3],

[ 5, 10, 7, 5, 0, 8, 5, 8, 9, 14, 4, 3],

[17, 2, 0, 3, 15, 10, 14, 1, 0, 7, 16, 2]])

看看3×3子矩阵,我希望第一个3×3子矩阵来自左上角:

>>> a[0:3, 0:3]

array([[ 4, 0, 12],

[15, 13, 2],

[18, 18, 3]])

接下来将由[0:3,3:6]等给出.如果每行或每列中的最后一组这样的索引在数组的末尾之外运行也没关系 – numpy只是在切片中给出存在的部分的行为就足够了.

我想要一种以编程方式为任意大小的矩阵和子矩阵生成这些切片索引的方法.我目前有这个:

size = 3

x_max = a.shape[0]

xcoords = range(0, x_max, size)

xcoords = zip(xcoords, xcoords[1:])

并且类似地生成y_coords,因此一系列索引由itertools.product(xcoords,ycoords)给出.

我的问题是:有没有更直接的方法来做到这一点,也许使用numpy.mgrid或其他一些numpy技术?

Logo

GitCode AI社区是一款由 GitCode 团队打造的智能助手,AI大模型社区、提供国内外头部大模型及数据集服务。

更多推荐