将numpy数组拆分成块

时间:2013-06-29 22:08:51

标签: python numpy block

我有一个900 x 650 2D numpy数组,我想分成10 x 10个块,将检查非零元素。是否有一种Pythonic方式,我可以用numpy来实现这个目标?

我正在寻找类似于以下内容的功能:

blocks_that_have_stuff = []
my_array = getArray()
my_array.cut_into_blocks((10, 10))
for block_no, block in enumerate(my_array):
    if numpy.count_nonzero(block) > 5:
        blocks_that_have_stuff.append(block_no)

1 个答案:

答案 0 :(得分:7)

我写了一个例程,用块切割矩阵。这个例子很容易理解。我以简单的形式编写它来显示结果(仅用于检查目的)。如果您对它感兴趣,可以在输出中包含块数或任何内容。

import matplotlib.pyplot as plt
import numpy as np

def cut_array2d(array, shape):
    arr_shape = np.shape(array)
    xcut = np.linspace(0,arr_shape[0],shape[0]+1).astype(np.int)
    ycut = np.linspace(0,arr_shape[1],shape[1]+1).astype(np.int)
    blocks = [];    xextent = [];    yextent = []
    for i in range(shape[0]):
        for j in range(shape[1]):
            blocks.append(array[xcut[i]:xcut[i+1],ycut[j]:ycut[j+1]])
            xextent.append([xcut[i],xcut[i+1]])
            yextent.append([ycut[j],ycut[j+1]])
    return xextent,yextent,blocks

nx = 900; ny = 650
X, Y = np.meshgrid(np.linspace(-5,5,nx), np.linspace(-5,5,ny))
arr = X**2+Y**2

x,y,blocks = cut_array2d(arr,(10,10))

n = 0

for x,y,block in zip(x,y,blocks):
    n += 1
    plt.imshow(block,extent=[y[0],y[1],x[0],x[1]],
               interpolation='nearest',origin='lower',
               vmin = arr.min(), vmax=arr.max(),
               cmap=plt.cm.Blues_r)
    plt.text(0.5*(y[0]+y[1]),0.5*(x[0]+x[1]),str(n),
             horizontalalignment='center',
             verticalalignment='center')

plt.xlim([0,900])
plt.ylim([0,650])
plt.savefig("blocks.png",dpi=72)
plt.show()

输出结果为:

enter image description here

此致

注意:我认为您可以使用np.meshgrid优化此例程,而不是使用xextent& yextent。