简体   繁体   中英

Split numpy 3-d array into 2-d array of smaller 3-d arrays

I currently have images as numpy array with 3 channels (RGB). I would like to split this efficiently into a 2-d array of smaller 3-d sub arrays. For example if my image is of shape (100, 100, 3), I want to convert it into 10 x 10 array where the elements are (10, 10, 3) images (sub images), while maintaining the spatial orientation. The image height and width will always be equal.

I also wish to reverse the whole operation.

If this is a tough thing to do, is there a way to convert it into a 4-d array in either row or column order, while the element are still the same?

Is there an efficient way to do this using numpy methods?

You can use strides to split your array:

image = np.arange(30000).reshape(100,100,3)

sub_shape = (10,10,3)

#divide the matrix into sub_matrices of subshape
view_shape = tuple(np.subtract(image.shape, sub_shape) + 1) + sub_shape
strides = image.strides + image.strides
sub_matrices = np.squeeze(np.lib.stride_tricks.as_strided(image,view_shape,strides)[::sub_shape[0],::sub_shape[1],:])

sub_matrices shape:

(10, 10, 10, 10, 3)

sub_matrices[i,j,:,:,:] is the [i,j] -th sub-array.

Alternatively you can reshape your image:

sub_shape = (10,10,3)
sub_matrices = np.swapaxes(image.reshape(image.shape[0]/sub_shape[0],sub_shape[0],image.shape[1]/sub_shape[1],sub_shape[1],image.shape[3]), 1, 2)

And again sub_matrices[i,j,:,:,:] is the [i,j] -th sub-array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM