Home > Blockchain >  Numpy. How to split 2D array to multiple arrays by grid?
Numpy. How to split 2D array to multiple arrays by grid?

Time:01-10

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)

CodePudding user response:

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]]]
  • Related