Save one channel normalized tensor to image

When training, I torchvision.normalize image to [-1,1]. The output of network like this [16,1,256,256].
So I want to save output tensor to image, but torchvision.utils.save_image() will make one channel to three channel. Could you help me? Thank you!

1 Like
    score = model(input)
    score.clamp_(min=-1, max=1)
    score.add_(-(-1)).div_(1 - (-1) + 1e-5)
    image = score.cpu().squeeze(0) 
    image = torchvision.ToPILImage()(image)
    image.save('output.png')

Is this right?

You can use openCV

image = output.numpy()
cv2.imwrite('image_name', image)

# And when loading the image tell cv2 that it is grayscale
cv2.imread('image_name', cv2.COLOR_BGR2GRAY)
2 Likes

Also another simple trick would be to convert tensor to numpy and save numpy array as .npz file

2 Likes

Thank you for your reply!
I wonder if OpenCV will automatically convert [-1,1] to [0,255] ?

A quick and easy way to check is to save and load the image and see the results.

Ok, I will try. Thanks!