简体   繁体   中英

How to save grayscale image in Pytorch?

I want to save grayscale image in Pytorch, each image has four gray values, 0 , 60 , 120 and 180 . I try the following way to save images, but the saved image is not I expected.

for i, (inputs) in enumerate(test_generator):
    pred = modelPl(inputs.float()).detach()
    fig,ax = plt.subplots(1,1,figsize = (5,5))
    ax.imshow(pred[0,:,:], cmap = "gray")
    print(pred.shape)
    torchvision.utils.save_image(pred, saveTestPath + 'img_{0}.png'.format(i)) 

Output: torch.Size([400, 400])

Expected image:

在此处输入图片说明

However, the saved picture is not correct as follows:

在此处输入图片说明

It might be that torchvision.utils.save_image requires values to be in range 0 to 1. Your images have values which are greater than 1 and hence the problem.

You can check this by dividing the tensor by 255 (or some appropriate number). You can also try to set normalize=True and see if it can automatically normalize the data for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM