Extracting patches of a certain size from the image in python efficiently

后端 未结 2 1743
说谎
说谎 2020-12-18 12:01

I have an image and I want to extract square patches of different sizes from it.

I need dense patches, that is, I need a patch at every pixel in the image.

相关标签:
2条回答
  • 2020-12-18 12:34

    sklearn

    You might want to have a look at sklearn.feature_extraction.image.extract_patches_2d and skimage.util.pad:

    >>> from sklearn.feature_extraction.image import extract_patches_2d
    >>> import numpy as np
    >>> A = np.arange(4*4).reshape(4,4)
    >>> window_shape = (2, 2)
    >>> B = extract_patches_2d(A, window_shape)
    >>> B[0]
    array([[0, 1],
           [4, 5]])
    >>> B
    array([[[ 0,  1],
            [ 4,  5]],
    
           [[ 1,  2],
            [ 5,  6]],
    
           [[ 2,  3],
            [ 6,  7]],
    
           [[ 4,  5],
            [ 8,  9]],
    
           [[ 5,  6],
            [ 9, 10]],
    
           [[ 6,  7],
            [10, 11]],
    
           [[ 8,  9],
            [12, 13]],
    
           [[ 9, 10],
            [13, 14]],
    
           [[10, 11],
            [14, 15]]])
    

    skimage

    Expanding the answer of Stefan van der Walt a bit:

    Install skimage

    On Ubuntu

    $ sudo apt-get install python-skimage
    

    or

    $ pip install scikit-image
    

    Example from the docs

    >>> from skimage.util import view_as_windows
    >>> import numpy as np
    >>> A = np.arange(4*4).reshape(4,4)
    >>> A
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])
    >>> window_shape = (2, 2)
    >>> B = view_as_windows(A, window_shape)
    >>> B[0]
    array([[[0, 1],
            [4, 5]],
    
           [[1, 2],
            [5, 6]],
    
           [[2, 3],
            [6, 7]]])
    
    >>> B
    array([[[[ 0,  1],
             [ 4,  5]],
    
            [[ 1,  2],
             [ 5,  6]],
    
            [[ 2,  3],
             [ 6,  7]]],
    
    
           [[[ 4,  5],
             [ 8,  9]],
    
            [[ 5,  6],
             [ 9, 10]],
    
            [[ 6,  7],
             [10, 11]]],
    
    
           [[[ 8,  9],
             [12, 13]],
    
            [[ 9, 10],
             [13, 14]],
    
            [[10, 11],
             [14, 15]]]])
    
    0 讨论(0)
  • 2020-12-18 12:39

    I think you are looking for something like this:

    http://scikit-image.org/docs/0.9.x/api/skimage.util.html#view-as-windows

    0 讨论(0)
提交回复
热议问题