Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch tensor to change dimension

Tags:

pytorch

I have a RGB image tensor as (3,H,W), but the plt.imshow() can not show RGB image with this shape. I want to change the tensor to (H,W,3). How can I do that, is pytorch function .view() can do that?

like image 928
JudeW Avatar asked Feb 03 '26 23:02

JudeW


2 Answers

Find the method. use pytorch permute() method, see details: https://www.geeksforgeeks.org/python-pytorch-permute-method/

code:

image.permute(1, 2, 0)
like image 116
JudeW Avatar answered Feb 05 '26 12:02

JudeW


An alternative to using torch.Tensor.permute is to apply torch.Tensor.movedim:

image.movedim(0,-1)

Which tends to be more general than image.permute(1,2,0), since it works for any number of dimensions. It has the effect of moving axis=0 to axis=-1 in a sort of insertion operation.

The equivalent in Numpy is np.moveaxis.

like image 30
Ivan Avatar answered Feb 05 '26 14:02

Ivan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!