2

I have a numpy 2D-array:

c = np.arange(36).reshape(6, 6)

[[ 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, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35]]

I want to split it to multiple 2D-arrays by grid 3x3. (It's like a split big image to 9 small images by grid 3x3):

[[ 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, 25,| 26, 27,| 28, 29],
 [30, 31,| 32, 33,| 34, 35]]

At final i need array with 9 2D-arrays. Like this:

[[[0, 1], [6, 7]], 
 [[2, 3], [8, 9]],
 [[4, 5], [10, 11]],
 [[12, 13], [18, 19]],
 [[14, 15], [20, 21]],
 [[16, 17], [22, 23]],
 [[24, 25], [30, 31]],
 [[26, 27], [32, 33]],
 [[28, 29], [34, 35]]]

It's just a sample what i need. I want to know how to make small 2D arrays from big 2D array by grid (N,M)

Massimo
  • 836
  • 3
  • 17
  • 38
  • 1
    Does this answer your question? [How to split a matrix into 4 blocks using numpy?](https://stackoverflow.com/questions/11105375/how-to-split-a-matrix-into-4-blocks-using-numpy) – Ahmed AEK Jan 09 '23 at 10:50

1 Answers1

2

You can use something like:

from numpy.lib.stride_tricks import sliding_window_view

out = np.vstack(sliding_window_view(c, (2, 2))[::2, ::2])

Output:

>>> out.tolist()
[[[0, 1], [6, 7]],
 [[2, 3], [8, 9]],
 [[4, 5], [10, 11]],
 [[12, 13], [18, 19]],
 [[14, 15], [20, 21]],
 [[16, 17], [22, 23]],
 [[24, 25], [30, 31]],
 [[26, 27], [32, 33]],
 [[28, 29], [34, 35]]]
Corralien
  • 109,409
  • 8
  • 28
  • 52