Skip to content
Advertisement

fastest way to reshape 2D numpy array (gray image) into a 3D stacked array

I have a 2D image with the shape (M, N), and would like to reshape it into (M//m * N//n, m, n). That is, to stack small patches of images into a 3D array.

Currently, I used two for-loop to achieve that

JavaScript

Is there any other faster way to do this? Thanks a lot!

Advertisement

Answer

Use skimage.util.view_as_blocks:

JavaScript

Output:

JavaScript

NB. Be aware that you have a view of the original object. If you want a copy, use view_as_blocks(a, (2,2)).copy()

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement