繁体   English   中英

如何将python numpy数组转换为base64输出

[英]How to convert Python numpy array to base64 output

基本上,我需要做这个 ,但是在Python而非JavaScript。 我从socketio连接接收到base64编码的字符串,将其转换为uint8并对其进行处理,然后需要将其转换为base64字符串,这样我才能将其发送回去。

因此,到目前为止,我已经了解了这一点(我正在从socketio服务器获取data字典):

import pickle
import base64
from io import BytesIO
from PIL import Image

base64_image_string = data["image"]
image = Image.open(BytesIO(base64.b64decode(base64_image_string)))
img = np.array(image)

我该如何逆转此过程,以便将imgimg返回到base64_image_string

更新:
我已经通过以下方式解决了这个问题(从上面的代码片段继续):

pil_img = Image.fromarray(img)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")

令人困惑的是, new_image_stringbase64_image_string但是从new_image_string渲染的图像看起来相同,所以我很满意!

我相信,由于numpy.array支持缓冲区协议,因此您只需要以下内容:

processed_string = base64.b64encode(img)

因此,例如:

>>> encoded = b"aGVsbG8sIHdvcmxk"
>>> img = np.frombuffer(base64.b64decode(encoded), np.uint8)
>>> img
array([104, 101, 108, 108, 111,  44,  32, 119, 111, 114, 108, 100], dtype=uint8)
>>> img.tobytes()
b'hello, world'
>>> base64.b64encode(img)
b'aGVsbG8sIHdvcmxk'
>>>

来自http://www.programcreek.com/2013/09/convert-image-to-string-in-python/

import base64

with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str

是二进制读取

https://docs.python.org/2/library/base64.html

我也有同样的问题。 经过一番搜索和尝试后,我最终的解决方案与您的最终解决方案几乎相同。

唯一的区别是base64编码的字符串是png格式的数据,因此在转换为np.array之前,我需要将其从RGBA更改为RGB通道:

image = image.convert ("RGB")
img = np.array(image)

在相反的过程中,您将数据视为JPEG格式,也许这就是new_image_stringbase64_image_string不同的原因?

暂无
暂无

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

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