python - 如何将 numpy 数组(实际上是 BGR 图像)转换为 Base64 字符串?

标签 python arrays numpy image-processing base64

我知道如何通过读取 文件将磁盘中的图像转换为 base64。但是,在这种情况下,我已经在我的程序中将图像作为 numpy 数组,通过相机捕获,如 image[:,:,3]。如何将其转换为 base64 字符串,以便图像仍然可以恢复?我试过了。

from base64 import b64encode    
base64.b64encode(image)

它确实给了我一个字符串,但是当我用 https://codebeautify.org/base64-to-image-converter 测试时,它无法渲染图像,这意味着转换有问题。请帮助。

我知道一个解决方案是将图像作为jpg图片写入磁盘,然后将其读入base64字符串。但很明显,我不想在可以避免的情况下进行文件输入/输出。

最佳答案

这里有一个例子来说明你需要做什么:

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

关于python - 如何将 numpy 数组(实际上是 BGR 图像)转换为 Base64 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598607/

相关文章:

python - pytest-qt 测试对话框

python - 将日期和时间戳格式的数据插入 PostgreSQL

javascript - 如果出现平局,如何在 javascript 中返回较小的数字?

sql - 查询postgres中的文本数组

c# - 有没有办法在 C# 中向数组添加多个元素?

python - 替换嵌套循环

python - 优化完美平方问题,类似于Python中的硬币找零

python - 在 Numpy 1.6.1 中将 float32 数组转换为 datetime64

python - Keras Convolution2D 输入 : Error when checking model input: expected convolution2d_input_1 to have shape

python - 通过套接字发送图像时遇到问题