3

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)

1

1 Answer 1

3

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]]]
Sign up to request clarification or add additional context in comments.

1 Comment

tnx. this is exactly what i need!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.