Image Color is not proper when converted to PIL

Viewed 224

I am converting tensor to pil image, but color is distorted. I have tried converting it to BGR but result is still same.

trsn = transforms.ToPILImage()
temp = (target + torch.mean(target)) *torch.std(target)
res = trsn(temp.to('cpu').detach().squeeze())
np_img=np.array(res)
bgr = cv2.cvtColor(np_img,cv2.COLOR_RGB2BGR)
pil_im = Image.fromarray(bgr)
print(res)
# plt.imshow(res)
plt.imshow(res,label="Epoch "+str(i))
plt.show()
# im=Image.fromarray(np.uint8(target.to('cpu').detach().numpy()*255))
pil_im.save('f.jpeg')

I have a function that converts tensor to numpy and can show image on matplotlib.

Here is the function

def imcnvt(image):
    x = image.to("cpu").clone().detach().numpy().squeeze()
    x = x.transpose(1,2,0)
    x = x*np.array((0.5,0.5,0.5)) + np.array((0.5,0.5,0.5))
    return torch.Tensor(x)

Here is the pic I get enter image description here

and here is the pic I want with PIL

enter image description here

0 Answers
Related