如何将numpy数组(实际上是BGR图像)转换为Base64字符串?
问题描述:
我知道如何通过读取文件将磁盘映像转换为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时,我可以避免它。
答
下面就来告诉你需要做的一个例子:
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创建映像时
可能与[文件签名]做(https://en.wikipedia.org/wiki/List_of_file_signatures) – rigsby
这是不清楚“图像”是什么类型的对象。如果它是一个'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
图像是尺寸[:,:3]的numpy.ndarray,通过openCV直接从相机创建的数据int64 – Della