检查2D数组中滑动窗口中的所有元素是否为True - Python

时间:2017-04-18 07:48:41

标签: python numpy multidimensional-array vectorization

我有一个多维的numpy数组,其元素是True或False值:

import numpy as np 
#just making a toy array grid to show what I want to do 
grid = np.ones((4,4),dtype = 'bool')
grid[0,0]=False 
grid[-1,-1]=False 
#now grid has a few false values but is a 4x4 filled with mostly true values

现在我需要生成另一个数组M,其中每个站点M [i,j]的值取决于grid [i:i + 2,j:j + 2],如

M = np.empty((4x4)) #elements to be filled

#here is the part I want to clean up 
for ii in range(4): 
    for jj in range(4): 

        #details here are unimportant. It's just that M[ii,jj] depends on 
        #multiple elements of grid in some way
        if ii+2<=4 and jj+2<=4:     
            M[ii,jj] = np.all(grid[ii:ii+2,jj:jj+2]==True)
        else: 
            M[ii,jj] = False 

有没有办法用网格中的元素填充数组M而没有双循环?

1 个答案:

答案 0 :(得分:3)

方法#1

这是2D convolution -

的一种方法
from scipy.signal import convolve2d as conv2

out = (conv2(grid,np.ones((2,2),dtype=int),'valid')==4).astype(int)

示例运行 -

In [118]: grid
Out[118]: 
array([[False,  True,  True,  True],
       [ True,  True,  True,  True],
       [ True,  True,  True,  True],
       [ True,  True,  True, False]], dtype=bool)

In [119]: (conv2(grid,np.ones((2,2),dtype=int),'valid')==4).astype(int)
Out[119]: 
array([[0, 1, 1],
       [1, 1, 1],
       [1, 1, 0]])

请注意,预期输出的最后一行和最后一列将全部为零,并带有初始化的输出数组。这是因为代码的滑动特性,因为它不会在行和列中具有那么大的范围。

方法#2

这是另一个2D统一过滤器 -

from scipy.ndimage.filters import uniform_filter as unif2d

out = unif2d(grid,size=2).astype(int)[1:,1:]

方法#3

这是另一个4D slided windowed view -

from skimage.util import view_as_windows as viewW

out = viewW(grid,(2,2)).all(axis=(2,3)).astype(int)

使用all(axis=(2,3)),我们只是检查每个窗口的维度,所有元素都是True个元素。

运行时测试

In [122]: grid = np.random.rand(5000,5000)>0.1

In [123]: %timeit (conv2(grid,np.ones((2,2),dtype=int),'valid')==4).astype(int)
1 loops, best of 3: 520 ms per loop

In [124]: %timeit unif2d(grid,size=2).astype(int)[1:,1:]
1 loops, best of 3: 210 ms per loop

In [125]: %timeit viewW(grid,(2,2)).all(axis=(2,3)).astype(int)
1 loops, best of 3: 614 ms per loop