Used to produce an effect similar to a sliding serial port
1D sliding window
from numpy.lib import stride_tricks
def sliding_window_1d(a, window):
shape = (len(a)-window+1, window)
strides = (a.itemsize, a.itemsize)
ret = stride_tricks.as_strided(Z, shape=shape, strides=strides)
return ret
Z = np.arange(10)
R = sliding_window_1d(Z, 4)
print(R)
[[0 1 2 3]
[1 2 3 4]
[2 3 4 5]
[3 4 5 6]
[4 5 6 7]
[5 6 7 8]
[6 7 8 9]]
Note that the return value is a view, not an entity, you need to use copy()
it to turn it into an entity
print(R.strides)
print(R.copy().strides)
(4, 4)
(16, 4)
2D sliding window
from numpy.lib import stride_tricks
def sliding_window_2d(a, window):
h, w = a.shape
hh, ww = window
i = a.itemsize
shape=(h-hh+1, w-ww+1, hh, ww)
strides=(w*i, i, w*i, i)
ret = stride_tricks.as_strided(a, shape=shape, strides=strides)
return ret
a = np.arange(9).reshape(3, 3)
print(a)
print(sliding_window_2d(a, (2, 2)))
[[0 1 2]
[3 4 5]
[6 7 8]]
[[[[0 1]
[3 4]]
[[1 2]
[4 5]]]
[[[3 4]
[6 7]]
[[4 5]
[7 8]]]]