sklearn.feature_extraction.image.extract_patches_2d(image, patch_size, max_patches=None, random_state=None)[source]

Reshape a 2D image into a collection of patches

The resulting patches are allocated in a dedicated array.

Read more in the User Guide.


image : array, shape = (image_height, image_width) or

(image_height, image_width, n_channels) The original image data. For color images, the last dimension specifies the channel: a RGB image would have n_channels=3.

patch_size : tuple of ints (patch_height, patch_width)

the dimensions of one patch

max_patches : integer or float, optional default is None

The maximum number of patches to extract. If max_patches is a float between 0 and 1, it is taken to be a proportion of the total number of patches.

random_state : int, RandomState instance or None, optional (default=None)

Pseudo number generator state used for random sampling to use if max_patches is not None. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.


patches : array, shape = (n_patches, patch_height, patch_width) or

(n_patches, patch_height, patch_width, n_channels) The collection of patches extracted from the image, where n_patches is either max_patches or the total number of patches that can be extracted.


>>> from sklearn.feature_extraction import image
>>> one_image = np.arange(16).reshape((4, 4))
>>> one_image
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> patches = image.extract_patches_2d(one_image, (2, 2))
>>> print(patches.shape)
(9, 2, 2)
>>> patches[0]
array([[0, 1],
       [4, 5]])
>>> patches[1]
array([[1, 2],
       [5, 6]])
>>> patches[8]
array([[10, 11],
       [14, 15]])

Examples using sklearn.feature_extraction.image.extract_patches_2d