JudeW
JudeW

Reputation: 580

Pytorch tensor to change dimension

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?

Upvotes: 13

Views: 29110

Answers (3)

Ivan
Ivan

Reputation: 40618

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.

Upvotes: 9

YScharf
YScharf

Reputation: 2012

Please refer to this question

img_plot = img.numpy().transpose(1, 2, 0)
plt.imshow(img_plot)

Upvotes: 2

JudeW
JudeW

Reputation: 580

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

code:

image.permute(1, 2, 0)

Upvotes: 17

Related Questions