Pytorch tensor changing colors
I would appreciate any help on that.
Why after putting tensor of 3d (image) into 4d tensor, the image colors changed.
p = &quot;path/to/image&quot;
p = Image.open(p)
p = transforms.PILToTensor()(p)

transforms.ToPILImage()(p).show()  # ok  (left pic)
temp = torch.zeros(4, p.size()[0], p.size()[1], p.size()[2])
temp[0] = p
transforms.ToPILImage()(temp[0]).show()  # not ok  (right pic)




The reason is that the first tensor p is an integer tensor and values range between 0 - 255. The second image is a float tensor and the values range between 0.0 - 255.0. imshow function expects integer values between 0 - 255 or float values between 0 - 1, you can read more here.

To fix this problem, you have two options either add the dtype=torch.uint8 when you define a temp tensor or divide the values of the tensor by 255 to scale it between 0 -1.
# cell 1
from PIL import Image
from torchvision import transforms
import torch
from matplotlib import pyplot as plt

p = Image.open(&quot;pi.png&quot;)
p = transforms.PILToTensor()(p).permute(1, 2, 0)
plt.imshow( p )     #ok 

# cell 2
temp = torch.zeros(4, p.size()[0], p.size()[1], p.size()[2], dtype=torch.uint8)
temp[0] = p
plt.imshow(temp[0]) # or you can use plt.imshow(temp[0]/255)

