How to split a numpy array in fixed size chunks with and without overlap?

后端 未结 1 1206
慢半拍i
慢半拍i 2020-11-27 07:47

Lets say I have an array:

>>> arr = np.array(range(9)).reshape(3, 3)
>>> arr
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
         


        
相关标签:
1条回答
  • 2020-11-27 08:27

    There's a builtin in scikit-image as view_as_windows for doing exactly that -

    from skimage.util.shape import view_as_windows
    
    view_as_windows(arr, (2,2))
    

    Sample run -

    In [40]: arr
    Out[40]: 
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])
    
    In [41]: view_as_windows(arr, (2,2))
    Out[41]: 
    array([[[[0, 1],
             [3, 4]],
    
            [[1, 2],
             [4, 5]]],
    
    
           [[[3, 4],
             [6, 7]],
    
            [[4, 5],
             [7, 8]]]])
    

    For the second part, use its cousin from the same family/module view_as_blocks -

    from skimage.util.shape import view_as_blocks
    
    view_as_blocks(arr, (2,2))
    
    0 讨论(0)
提交回复
热议问题