用于产生类似滑动串口的效果
1D滑动窗口
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]]
注意返回值是一个视图,而不是一个实体,需要用copy()
将其变成实体
print(R.strides)
print(R.copy().strides)
(4, 4)
(16, 4)
2D滑动窗口
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]]]]