Search code examples
pytorchbase64

How to convert torch.tensor to base64 image?


Here is my tensor:

import torch
from torchvision import transforms

content:
tensor([[[[0.8939, 0.8700, 0.8458,  ..., 0.7610, 0.7093, 0.6909],
                                     .
                                     .
                                     .
          [0.4880, 0.5192, 0.5957,  ..., 0.8569, 0.9148, 0.9186]]]])

I want to convert this torch.Tensor to base64. I've tried this but I can not convert PILImage to base64 too.

img = transforms.ToPILImage(content)

How can I do this?


Solution

  • You should first convert your image to bytes to encode afterward your image to base64 image

    import torch
    from torchvision import transforms
    import base64
    
    tensor = torch.randn(3, 512, 512)
    transform = transforms.ToPILImage()
    pil_image = transform(tensor)
    
    # Convert the PIL image to bytes
    image_bytes = pil_image.tobytes()
    
    # Encode the bytes to base64
    base64_string = base64.b64encode(image_bytes).decode()
    print(base64_string)
    

    Output:

    00Hbhc4yZEZnw/VlIyHF6OH2VRAXeRdYiH82tBgSBoocDAB+cycknk3c5G9ZmdbHNu90whgDK49cjELZ6uJCzqYxVclXbJRc0Nb2AgN9XWULFOK+ubWJAyNbAgNZRvmwocwJN4603