Skip to content Skip to sidebar Skip to footer

Extracting Patches Of A Certain Size From The Image In Python Efficiently

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. For example if the imag

Solution 1:

I think you are looking for something like this:

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

Solution 2:

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]]]])

Post a Comment for "Extracting Patches Of A Certain Size From The Image In Python Efficiently"