“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)) is another option. Your swap is equal to np.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


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

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ