Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a numpy image array into blocks

I'm doing image processing for object detection using python. I need to divide my image into all possible blocks. For example given this toy image:

x = np.arange(25)
x = x.reshape((5, 5))

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

I want to retrieve all possible blocks of a given size, for example the 2x2 blocks are:

[[0 1]
 [5 6]]
[[1 2]
 [6 7]]

.. and so on. How can I do this?

like image 1000
blueSurfer Avatar asked Dec 03 '22 01:12

blueSurfer


1 Answers

The scikit image extract_patches_2d does that

>>> 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]])
like image 161
Guilherme Defreitas Avatar answered Dec 25 '22 09:12

Guilherme Defreitas