To Tensor transform is messing my images?

# create image dataset
f_ds = torchvision.datasets.ImageFolder(data_path)
# transform image to tensor.
to_tensor = torchvision.transforms.ToTensor()


for idx, (img, label) in enumerate(f_ds):
    if idx == 23:
        # random pil image 
        plt.imshow(img)
        plt.show()
 
        # image to np array
        n_arr = np.asarray(img)
        print("np array shape :", n_arr.shape)

        h, w, c = n_arr.shape
         
        # reshaping the numpy array has no problem
        re_n_arr = n_arr.reshape(c, h, w)
        plt.imshow(re_n_arr.reshape(h, w, c))
        plt.show()

        # torch tensor
        torch_ten = to_tensor(img)
        print("torch_tensor shape:", torch_ten.shape)
        print(torch_ten.numpy().shape)
        plt.imshow(torch_ten.numpy().reshape(h, w, c))

        break

Please help me with this. Iā€™m stuck here.

Thank you :slight_smile:

ToTensor permutes the array and returns a tensor in the shape [C, H, W]. Using reshape to swap the order of dimensions is wrong and will interleave the image as is seen in your last output:

        # torch tensor
        torch_ten = to_tensor(img)
        print("torch_tensor shape:", torch_ten.shape)
        print(torch_ten.numpy().shape)
        plt.imshow(torch_ten.numpy().reshape(h, w, c))

use plt.imshow(torch_ten.permute(1, 2, 0).numpy()) and it should work.

2 Likes