Save_image not working: RuntimeError: result type Float can't be cast to the desired output type Byte

I have an output tensor called output of shape [12000, 12000, 3] and of type uint8. It is a tensor of RGB values ranging in [0, 255]. I am trying to save it using the following line

torchvision.utils.save_image(output, "stitched_output.jpg")

But I get the following error:

----> 7 torchvision.utils.save_image(output, "stitched_output.jpg")

~/.local/lib/python3.6/site-packages/torchvision/utils.py in save_image(tensor, fp, nrow, padding, normalize, range, scale_each, pad_value, format)
    126                      normalize=normalize, range=range, scale_each=scale_each)
    127     # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer
--> 128     ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()
    129     im = Image.fromarray(ndarr)
    130     im.save(fp, format=format)

RuntimeError: result type Float can't be cast to the desired output type Byte

Any idea why this is happening? I never had issues before when it came to saving tensors as images. Thank you.

1 Like

Hi @eqy @ptrblck, any ideas? I just tagged you both because you both have been great help for me on this forum. I’ve been scratching my head at this for a bit but I can’t seem to find any solutions online. Thank you!

Does it work if you try to save an image in tensor format (e.g., channels first, in range (0, 1.0), dtype float)?

You can call the to tensor transformation to do this if you do not have it readily available in that format:
https://pytorch.org/vision/stable/_modules/torchvision/transforms/functional.html#to_tensor

Alternatively, you might be able to use a PIL image saving utility as well if you already have a PIL image on-hand:
https://pillow.readthedocs.io/en/stable/_modules/PIL/Image.html#Image.save

1 Like

Thank you very much! By permuting the dimensions into image tensor format and normalizing the tensor in float range [0.0, 1.0], we got it to work!

Hi @hanoody I also have similar problem. Can you please share your code ?