Conversion from a tensor to a PIL Image not working well. What is going wrong?

I load the dataset with the following transformations:

normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])

transform = transforms.Compose([
        transforms.Resize((240, 240), interpolation=0),
        transforms.ToTensor(),
        normalize
    ]),

Then when I try to convert the resulting tensor back to a PIL Image I get the following:

trans = transforms.ToPILImage(mode='RGB')
plt.imshow(trans(img.squeeze()))
plt.show()

Clearly, the image is not as it should be. Can anyone let me know what’s going on?
Thanks.

1 Like

These artifacts are caused by the normalization.
If you want to get the original image back, you would need to “denormalize” your tensor again:

img = Image.open('PATH')
x = transform(img)

z = x * torch.tensor(std).view(3, 1, 1)
z = z + torch.tensor(mean).view(3, 1, 1)

img2 = transforms.ToPILImage(mode='RGB')(z)
plt.imshow(img2)
2 Likes