1

Using the answer from this question, I am able to obtain the windowed version of a matrix along the rows with stride = 1 (each window is the same except for a row):

def strided_axis0(a, L): 
   nd0 = a.shape[0] - L + 1
   m,n = a.shape
   s0,s1 = a.strides
   return np.lib.stride_tricks.as_strided(a, shape=(nd0,L,n), strides=(s0,s0,s1))

I'd like to have a parameter in the function to obtain different overlapping.

For example:

In [49]: X
Out[49]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39]])

In [50]: strided_axis0(X, L=4, ov = 2)

Out[50]: 
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29]],


       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39]]])
Francesco Pegoraro
  • 778
  • 13
  • 33

2 Answers2

2

You may try:

def get_strides(a, L, ov):
    out = []
    for i in range(0, a.shape[0]-L+1, L-ov):
        out.append(a[i:i+L, :])

    return np.array(out)

Basically, it generates all the array starting from the row 0 and moving downward by L-ov rows. It stops when it is L rows away from the end of the array. Giving your array as input, it produces:

> print(get_strides(a, 4, 2))
> [[[ 0  1  2  3  4]
    [ 5  6  7  8  9]
    [10 11 12 13 14]
    [15 16 17 18 19]]

  [[10 11 12 13 14]
    [15 16 17 18 19]
    [20 21 22 23 24]
    [25 26 27 28 29]]

  [[20 21 22 23 24]
    [25 26 27 28 29]
    [30 31 32 33 34]
    [35 36 37 38 39]]]
Neb
  • 2,270
  • 1
  • 12
  • 22
1

Here's a version with np.lib.stride_tricks.as_strided -

import warnings

def strided_axis0(a, L, overlap=1):
    if L==overlap:
        raise Exception("Overlap arg must be smaller than length of windows")
    S = L - overlap
    nd0 = ((len(a)-L)//S)+1
    if nd0*S-S!=len(a)-L:
        warnings.warn("Not all elements were covered")
    m,n = a.shape
    s0,s1 = a.strides
    return np.lib.stride_tricks.as_strided(a, shape=(nd0,L,n), strides=(S*s0,s0,s1))

We can also leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows. More info on use of as_strided based view_as_windows.

from skimage.util.shape import view_as_windows

def strided_axis0(a, L, overlap=1):
    if L==overlap:
        raise Exception("Overlap arg must be smaller than length of windows")
    S = L - overlap
    nd0 = ((len(a)-L)//S)+1
    if nd0*S-S!=len(a)-L:
        warnings.warn("Not all elements were covered")
    return view_as_windows(a, (L,a.shape[1]), step=S)[:,0,:,:]
Divakar
  • 218,885
  • 19
  • 262
  • 358