“Transform” Numpy Arrray: Move Dimension
“Transform” Numpy Arrray: Move Dimension
I'm creating array a:
import numpy as np
a = np.zeros((3, 10, 10), np.uint8)
a[1,5,5] = 255
with a red dot in the center, where the RGB is the first dimension. Then I plot it using matplotlib:
import matplotlib.pyplot as plt
plt.imshow(a)
But of course this doesn't work because imshow expects an array with dimensions (10, 10, 3) and I am feeding it an array with dimensions (3, 10, 10). How could I 'flip' the array so that the RGB is the third dimension, instead of the first?
1 Answer
1
What you need is swapaxes.
swapaxes
import numpy as np
a = np.zeros((3, 10, 10), np.uint8)
print(a.shape) #(3,10,10)
print(np.swapaxes(a,0,2).shape) #(10,10,3)
See documentation.
np.swapaxes(a,0,2) equals to np.transpose(a, (2,1,0)).
np.swapaxes(a,0,2)
np.transpose(a, (2,1,0))
There is another option which is np.transpose(a, (1,2 0)).
np.transpose(a, (1,2 0))
As always, transpose matrix can have two versions which produce similar result but with different 3-dimensional rotational symmetry.
It depends on if the mirror matrix affect your result, you should carefully test if it makes difference.
np.transpose(a, (1,2 0))
np.transpose(a, (2,1,0))
@hpaulj , oops, you are right. There should be another option such that the two result are mirror matrix. I will make an adjustment.
– MatrixTai
Sep 17 '18 at 3:50
You can use
np.moveaxis(a, 0, 2) which is slightly more readable---but slower---than np.transpose(a, (1, 2, 0))– Paul Panzer
Sep 17 '18 at 3:56
np.moveaxis(a, 0, 2)
np.transpose(a, (1, 2, 0))
I make this community post. As it seems like it no longer just the work of mine.
– MatrixTai
Sep 17 '18 at 3:58
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
np.transpose(a, (1,2 0))is another option. Your swap is equal tonp.transpose(a, (2,1,0)), which transposes the (10,10) part. That may, or might not, be what the OP wants.– hpaulj
Sep 17 '18 at 3:15