[英]How to convert Python numpy array to base64 output
I basically need to do this but in Python instead of Javascript. 基本上,我需要做这个 ,但是在Python而非JavaScript。 I receive a base64 encoded string from a socketio connection, convert it to uint8 and work on it, then need to convert it to base64 string so I can send it back.
我从socketio连接接收到base64编码的字符串,将其转换为uint8并对其进行处理,然后需要将其转换为base64字符串,这样我才能将其发送回去。
So, up to this point I've got this (I'm getting the data
dictionary from the socketio server): 因此,到目前为止,我已经了解了这一点(我正在从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)
How do I reverse this process to get from img
back to base64_image_string
? 我该如何逆转此过程,以便将
img
从img
返回到base64_image_string
?
UPDATE: 更新:
I have solved this in the following manner (continuing from the code snippet above): 我已经通过以下方式解决了这个问题(从上面的代码片段继续):
pil_img = Image.fromarray(img)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
Somewhat confusingly, new_image_string
is not identical to base64_image_string
but the image rendered from new_image_string
looks the same so I'm satisfied! 令人困惑的是,
new_image_string
与base64_image_string
但是从new_image_string
渲染的图像看起来相同,所以我很满意!
I believe since numpy.array
s support the buffer protocol, you just need the following: 我相信,由于
numpy.array
支持缓冲区协议,因此您只需要以下内容:
processed_string = base64.b64encode(img)
So, for example: 因此,例如:
>>> 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'
>>>
from http://www.programcreek.com/2013/09/convert-image-to-string-in-python/ : 来自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
is binary read 是二进制读取
https://docs.python.org/2/library/base64.html https://docs.python.org/2/library/base64.html
I have the same problem. 我也有同样的问题。 After some search and try, my final solution is almost the same as yours.
经过一番搜索和尝试后,我最终的解决方案与您的最终解决方案几乎相同。
The only difference is that the base64 encoded string is png
format data, so I need to change it from RGBA
to RGB
channels before converted to np.array: 唯一的区别是base64编码的字符串是
png
格式的数据,因此在转换为np.array之前,我需要将其从RGBA
更改为RGB
通道:
image = image.convert ("RGB")
img = np.array(image)
In the reverse process, you treate the data as JPEG
format, maybe this is the reason why new_image_string
is not identical to base64_image_string
? 在相反的过程中,您将数据视为
JPEG
格式,也许这就是new_image_string
与base64_image_string
不同的原因?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.