簡體   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