Approach No. 1
Here's one approach with 2D
convolution -
from scipy.signal import convolve2d as conv2
out = (conv2(grid,np.ones((2,2),dtype=int),'valid')==4).astype(int)
Run Example -
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
-
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