问题
I'm working on an array shaped as follows
(64, 1, 64, 64)
This is in fact one grayscale image that was split into 64 patches, each patch with 64*64px.
Now I need to rebuild it into a 512*512px image.
I've tried using
np.reshape(arr, (512, 512))
but of course the resulting image is not as expected.
How do I resolve this?
回答1:
It depends on how your patches are arranged. But the first thing you could try is
image.reshape(8, 8, 64, 64).swapaxes(1, 2).reshape(512, 512)
This is assuming that the original zeroth dimension lists the patches row by row, i.e. 0-7 are the first row of patches from left to right, 8-15 the second row and so on.
The first reshape reestablishes that arrangement, after it choosing index i, j for axes 0 and 1 addresses the j+1st patch in the i+1st row.
Now comes the interesting bit: When merging axes by reshape:
- only adjacent dimensions can be combined
- all but the rightmost axis in each block will be dispersed
Since we want to keep each patch together we have to rearrange in such a way that the current axes 2 and 3 become the rightmost members of blocks. That is what the swapaxes
does.
By now the shape is (8, 64, 8, 64) and axes 1 and 3 are the within-patch coordinates. Combining two pairs ( 8, 64 -> 512 8, 64 -> 512 )
is all that's left to do.
来源:https://stackoverflow.com/questions/43441230/how-to-reshape-a-multidimensional-array-to-a-2d-image