5

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 image is 100x100 and the patch size is 64.

The result will be 10000 patches of size 64x64

These are the same patches which we use for filtering operations for example.

In case there is a boundary I would like to mirror the image.

What is the most efficient way of extracting patches using python?

Thanks

Shan
  • 18,563
  • 39
  • 97
  • 132

2 Answers2

13

I think you are looking for something like this:

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

Stefan van der Walt
  • 7,165
  • 1
  • 32
  • 41
  • Although, it is very nice, but it still does not solve the problem of the boundary pixels, where the mirroring is required. It just rolls over the image with in the image – Shan Mar 01 '14 at 00:12
  • 2
    You may use ``skimage.util.pad`` to add preferred boundaries beforehand. – Stefan van der Walt Mar 01 '14 at 10:16
12

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]]]])
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • 1
    +1 for `skimage.util.pad`, I need to take patches at arbitrary locations, sometimes near the edge, and I want zeros when I'm off the image proper. – jonchar Jun 29 '16 at 18:05