Moving window along latter 2 dimensions of a 3D NumPy array to obtain 3D chunks

Viewed 211

I have a 3D NumPy array a of shape (2, 9, 9) like this one:

a = np.array([
       [[4, 5, 1, 3, 8, 8, 0, 6, 6],
        [9, 2, 2, 1, 8, 2, 2, 4, 5],
        [2, 3, 2, 2, 5, 3, 1, 2, 4],
        [9, 6, 2, 9, 1, 0, 6, 2, 3],
        [4, 2, 7, 7, 9, 1, 3, 7, 2],
        [5, 8, 9, 4, 6, 3, 1, 6, 7],
        [3, 6, 4, 7, 2, 9, 8, 3, 4],
        [0, 4, 1, 2, 3, 7, 3, 7, 5],
        [6, 9, 2, 6, 0, 0, 5, 1, 4]],

       [[4, 2, 0, 1, 6, 7, 1, 0, 8],
        [1, 5, 3, 6, 4, 2, 4, 8, 3],
        [7, 4, 9, 9, 1, 9, 7, 3, 1],
        [3, 6, 1, 2, 5, 4, 1, 3, 0],
        [3, 3, 6, 6, 9, 8, 4, 2, 8],
        [7, 9, 1, 3, 0, 2, 0, 7, 4],
        [6, 7, 9, 3, 0, 2, 1, 9, 2],
        [1, 0, 3, 4, 7, 8, 1, 6, 5],
        [4, 4, 7, 8, 3, 7, 0, 4, 7]]])

I would like to get 3D chunks of shape 2 × 3 × 3 using a moving window along latter two dimensions (in this case 9 × 9). The size of the first dimension (I'd call it "depth") is arbitrary. The example of the first chunk would be:

>>> array([
       [[np.nan, np.nan, np.nan],
        [np.nan, 4, 5],
        [np.nan, 9, 2]],

        [[np.nan, np.nan, np.nan],
        [np.nan, 4, 2],
        [np.nan, 1, 5]]])

The second would be:

>>> array([
       [[np.nan, np.nan, np.nan],
        [4, 5, 1],
        [9, 2, 2]],

        [[np.nan, np.nan, np.nan],
        [4, 2, 0],
        [1, 5, 3]]])

And so on...

I later need to apply a more complicated function to these chunks, not a simple average or such, so I would appreciate a new array with them (I guess that is quite memory intensive, is there a different approach? Possibly vectorized? But it's not necessary)

I tried applying np.lib.stride_tricks.as_strided to my case as in #44305987 and played around with fancy indexing as in #15722324, but did not achieve the desired result.

Thanks!

1 Answers

You could use skimage.util.view_as_windows for this. Since it appears that you want a minimum size of 2 elements for those windowed views, you could assign the array to a larger array of np.nan, and take the strided view of the resulting array:

from skimage.util import view_as_windows

i,j,k= a.shape
a_exp = np.full((i,j+2,k+2), np.nan)
a_exp[:,1:j+1,1:k+1] = a

Or you could also do the same with np.pad:

a_exp = np.pad(a.astype('float'), 
               pad_width=((0,0),(1,1),(1,1)), 
               constant_values=np.nan)

And view as strided with:

out = view_as_windows(a_exp, (a.shape[0],3,3))

out
array([[[[[[nan, nan, nan],
           [nan,  4.,  5.],
           [nan,  9.,  2.]],

          [[nan, nan, nan],
           [nan,  4.,  2.],
           [nan,  1.,  5.]]],


         [[[nan, nan, nan],
           [ 4.,  5.,  1.],
           [ 9.,  2.,  2.]],

          [[nan, nan, nan],
           [ 4.,  2.,  0.],
           [ 1.,  5.,  3.]]],
         ...
Related