You can define the function that the generator gives and use it. The window will be half the shape you want to divide by 2, and the trick is to simply index the array along this window when moving along rows and columns.
def window(arr, shape=(3, 3)):
r_win = np.floor(shape[0] / 2).astype(int)
c_win = np.floor(shape[1] / 2).astype(int)
x, y = arr.shape
for i in range(x):
xmin = max(0, i - r_win)
xmax = min(x, i + r_win + 1)
for j in range(y):
ymin = max(0, j - c_win)
ymax = min(y, j + c_win + 1)
yield arr[xmin:xmax, ymin:ymax]
You can use this function as follows:
arr = np.array([[1,2,3,4],
[2,3,4,5],
[3,4,5,6],
[4,5,6,7]])
gen = window(arr)
next(gen)
array([[1, 2],
[2, 3]])
Passing through the generator produces all the windows in your example.
, , , . @PaulPanzer, np.lib.stride_tricks.as_strided
, . - :
def rolling_window(a, shape):
s = (a.shape[0] - shape[0] + 1,) + (a.shape[1] - shape[1] + 1,) + shape
strides = a.strides + a.strides
return np.lib.stride_tricks.as_strided(a, shape=s, strides=strides)
def window2(arr, shape=(3, 3)):
r_extra = np.floor(shape[0] / 2).astype(int)
c_extra = np.floor(shape[1] / 2).astype(int)
out = np.empty((arr.shape[0] + 2 * r_extra, arr.shape[1] + 2 * c_extra))
out[:] = np.nan
out[r_extra:-r_extra, c_extra:-c_extra] = arr
view = rolling_window(out, shape)
return view
window2(arr, (3,3))
array([[[[ nan, nan, nan],
[ nan, 1., 2.],
[ nan, 2., 3.]],
[[ nan, nan, nan],
[ 1., 2., 3.],
[ 2., 3., 4.]],
[[ nan, nan, nan],
[ 2., 3., 4.],
[ 3., 4., 5.]],
[[ nan, nan, nan],
[ 3., 4., nan],
[ 4., 5., nan]]],
[[[ nan, 1., 2.],
[ nan, 2., 3.],
[ nan, 3., 4.]],
[[ 1., 2., 3.],
[ 2., 3., 4.],
[ 3., 4., 5.]],
[[ 2., 3., 4.],
[ 3., 4., 5.],
[ 4., 5., 6.]],
[[ 3., 4., nan],
[ 4., 5., nan],
[ 5., 6., nan]]],
[[[ nan, 2., 3.],
[ nan, 3., 4.],
[ nan, 4., 5.]],
[[ 2., 3., 4.],
[ 3., 4., 5.],
[ 4., 5., 6.]],
[[ 3., 4., 5.],
[ 4., 5., 6.],
[ 5., 6., 7.]],
[[ 4., 5., nan],
[ 5., 6., nan],
[ 6., 7., nan]]],
[[[ nan, 3., 4.],
[ nan, 4., 5.],
[ nan, nan, nan]],
[[ 3., 4., 5.],
[ 4., 5., 6.],
[ nan, nan, nan]],
[[ 4., 5., 6.],
[ 5., 6., 7.],
[ nan, nan, nan]],
[[ 5., 6., nan],
[ 6., 7., nan],
[ nan, nan, nan]]]])
np.nan
, . 3 , , window
, , , .