提问人:AlwaysJunior 提问时间:1/26/2023 更新时间:1/26/2023 访问量:595
如何把torch.tensor转换成base64图片?
How to convert torch.tensor to base64 image?
问:
这是我的张量:
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]]]])
我想转换这个火炬。张量到 base64。我已经尝试过了,但我也无法将 PILImage 转换为 base64。
img = transforms.ToPILImage(content)
我该怎么做?
答:
1赞
Hamzah
1/26/2023
#1
您应该首先将图像转换为字节进行编码,然后将图像转换为 base64 图像
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)
输出:
00Hbhc4yZEZnw/VlIyHF6OH2VRAXeRdYiH82tBgSBoocDAB+cycknk3c5G9ZmdbHNu90whgDK49cjELZ6uJCzqYxVclXbJRc0Nb2AgN9XWULFOK+ubWJAyNbAgNZRvmwocwJN4603
评论
0赞
AlwaysJunior
1/26/2023
我尝试过这样的事情,但我无法得到任何结果:pil_image = 转换。ToPILImage(内容) image_bytes = pil_image.tobytes() base64_string = base64.b64encode(image_bytes).decode()
0赞
AlwaysJunior
1/26/2023
此外,我们还有不同大小的数组。我的张量有四个维度,而你的张量是三个维度。
0赞
Hamzah
1/26/2023
@AlwaysJunior,你没有得到任何结果是什么意思,问题是什么?
0赞
AlwaysJunior
1/26/2023
我理解这个问题。我需要压缩张量,你的解决方案对我有帮助。谢谢!
上一个:如何抓取水平条形图?
评论