将numpy图像数组切成块

blu*_*fer 4 python numpy image-processing computer-vision

我正在使用python进行对象检测的图像处理.我需要将我的图像分成所有可能的块.例如给出这个玩具图像:

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]]
Run Code Online (Sandbox Code Playgroud)

我想检索给定大小的所有可能块,例如2x2块是:

[[0 1]
 [5 6]]
[[1 2]
 [6 7]]
Run Code Online (Sandbox Code Playgroud)

.. 等等.我怎样才能做到这一点?

Gui*_*tas 11

scikit图像extract_patches_2d就是这么做的

>>> 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]])
Run Code Online (Sandbox Code Playgroud)