简体   繁体   English

将Base64编码的图像转换为numpy数组

[英]Convert Base64 encoded image to a numpy array

I'm receiving an image via an http POST that is base64 encoded. 我正在通过base64编码的http POST接收图像。 It can be a JPG or a BMP. 它可以是JPG或BMP。 Now that I have the image, I can get it in memory. 现在,我有了图像,可以将其保存在内存中。 I found how to write it to disk and re-read it into a numpy array (Which I need to actually put into a torch.tensor but numpy will suffice for now). 我发现了如何将其写入磁盘并将其重新读取为numpy数组(实际上需要将其放入torch.tensor中,但numpy现在就足够了)。

HEre's what works for me but appears HIGHLY inefficient : 这是对我有用的东西,但是效率很低:

import torch
import numpy as np
from PIL import Image
import base64

base64_decoded = base64.b64decode(test_image_base64_encoded)

with open("out.jpg", "wb") as out_file:
    out_file.write(base64_decoded)

image = Image.open("out.jpg")
image_np = np.array(image)
image_torch = torch.tensor(np.array(image))

It feels extremely useless to have to write the array to out.jpg to reread it right after into an array. 不得不将数组写入out.jpg并在数组之后立即重读,这感觉非常无用。 There must be a better way. 一定会有更好的办法。 I've tried some things where it ends up in a 1D array... and my image is a 2D array in my case (BW image). 我尝试了一些以1D数组结尾的事情...而我的图像在我的情况下是2D数组(BW图像)。

nparr = np.fromstring(base64.b64decode(test_image), np.uint8)

would yield when nparr.shape = (694463,) when image_np.shape = (2048, 3072) 当image_np.shape =(2048,3072)时,nparr.shape =(694463,)时会产生

Any idea how I could represent to np.array something like Image.frombase64 :) ? 任何想法我怎么能代表像Image.frombase64 :)的np.array吗? I know it doesn't exists per say but that would be great if it could somehow interpret the "file" without having to save it to disk first. 我知道它不存在,但是如果它能够以某种方式解释“文件”而不必先将其保存到磁盘,那将是很棒的。

Assuming you're using PIL, but you don't know the image type or dimensions: 假设您使用的是PIL,但您不知道图像类型或尺寸:

from PIL import Image
import base64
import io
import numpy as np
import torch

base64_decoded = base64.b64decode(test_image_base64_encoded)

image = Image.open(io.BytesIO(base64_decoded))
image_np = np.array(image)
image_torch = torch.tensor(np.array(image))

io.BytesIO is the key thing you're missing, I think. 我认为io.BytesIO是您缺少的关键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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