Why does pytorch rotate a numpy image when converted to tensor

I have a numpy image i tried converting to a tensor

cats

tensor_img = torch.from_numpy(numpy_img).permute(2, 1, 0).unsqueeze(0)

I got a rotated and flipped image. What might the problem

Screen Shot 2022-06-28 at 11.51.19 AM

So I figured it out in case someone falls into same problem. I had earlier splitted the original image into blocks where each block is stored in a list. This list is then converted into numpy and reshaped accordingly, resulting into the first image above.

import torchvision.transforms as T
transform = T.ToTensor()
tensor_img = transform(numpy_img).unsqueeze(0)

solved the problem

While ToTensor should also work, I think the original issue is caused by a wrong permutation as most likely your numpy image has the shape [H, W, C] which you would like to transform to a tensor in [C, H, W]. To do so you would need to call .permute(2, 0, 1).

2 Likes