2017-10-06 216 views
0

我知道如何通過讀取文件將磁盤映像轉換爲base64。但是,在這種情況下,我的程序中已經有了一個像陣列一樣的圖像,通過攝像頭捕獲,如image[:,:,3]。如何將其轉換爲base64字符串,以便圖像仍可恢復?我試過這個。如何將numpy數組(實際上是BGR圖像)轉換爲Base64字符串?

from base64 import b64encode  
base64.b64encode(image) 

它確實給了我一個字符串,但是當我https://codebeautify.org/base64-to-image-converter測試,它無法呈現圖像,這意味着有一些錯誤的轉換。請幫助。

我知道一個解決方案是將圖像寫入磁盤作爲jpg圖片,然後將其讀入base64字符串。但顯然,我不想要一個文件I/O時,我可以避免它。

+0

可能與[文件簽名]做(https://en.wikipedia.org/wiki/List_of_file_signatures) – rigsby

+0

這是不清楚「圖像」是什麼類型的對象。如果它是一個'PIL Image',那麼你需要通過使用[BytesIO fp參數]調用'save'將其轉換爲字符串(https://pillow.readthedocs.io/en/3.4.x/reference/ Image.html#PIL.Image.Image.save)。然後你可以像上面顯示的那樣對二進制字符串進行編碼。如果'image'是一個'NumPy'數組,那麼你可以使用'Image.fromarray(..)'創建一個'PIL Image'。 – Eric

+0

圖像是尺寸[:,:3]的numpy.ndarray,通過openCV直接從相機創建的數據int64 – Della

回答

0

下面就來告訴你需要做的一個例子:

from PIL import Image 
import io 
import base64 
import numpy 

# creare a random numpy array of RGB values, 0-255 
arr = 255 * numpy.random.rand(20, 20, 3) 

im = Image.fromarray(arr.astype("uint8")) 
#im.show() # uncomment to look at the image 
rawBytes = io.BytesIO() 
im.save(rawBytes, "PNG") 
rawBytes.seek(0) # return to the start of the file 
print(base64.b64encode(rawBytes.read())) 

我可以粘貼印入base64 image converter字符串,它會類似於im.show(),作爲網站放大圖像。

您可能需要操縱你的陣列或提供適當的PIL mode創建映像時

相關問題