简体   繁体   English

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

[英]How to convert a numpy array (which is actually a BGR image) to Base64 string?

I know how to convert an image in the disk to base64 via reading the file.我知道如何通过读取文件将磁盘中的图像转换为 base64。 However, in this instance, I already have the image as a numpy array in my program, captured via a camera, like image[:,:,3] .但是,在这种情况下,我的程序中已经将图像作为一个 numpy 数组,通过相机捕获,例如image[:,:,3] How do I convert it to base64 string such that the image can still be recovered?如何将其转换为 base64 字符串,以便仍然可以恢复图像? I tried this.我试过这个。

from base64 import b64encode    
base64.b64encode(image)

It does indeed gives me a string, but when I tested with https://codebeautify.org/base64-to-image-converter , it could not render the image, which means there is something wrong in the conversion.它确实给了我一个字符串,但是当我使用https://codebeautify.org/base64-to-image-converter进行测试时,它无法渲染图像,这意味着转换中有问题。 Help please.请帮忙。

I know a solution is to write the image into the disk as a jpg picture and then read it into a base64 string.我知道一个解决方案是将图像作为 jpg 图片写入磁盘,然后将其读入 base64 字符串。 But obviously, I don't want a file i/o when I can avoid it.但显然,当我可以避免它时,我不想要文件 i/o。

Here's an example to show what you need to do: 这是显示您需要做什么的示例:

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()))

I can paste the string printed into the base64 image converter and it'll look similar to im.show() , as the site enlarges the image. 我可以将打印的字符串粘贴到base64图像转换器中 ,当站点放大图像时,它看起来类似于im.show()

You may need to manipulate your array or provide an appropriate PIL mode when creating your image 创建映像时,您可能需要操纵阵列或提供适当的PIL模式

This is a bit more round-about from the other answers, but in case someone else lands here trying to show an image as a Qt base-64 tooltip, the other methods won't work.这与其他答案相比更为迂回,但如果其他人试图将图像显示为 Qt base-64 工具提示,则其他方法将不起作用。 I had more luck using a QBuffer and QImage:我使用 QBuffer 和 QImage 有更多的运气:

# Adapted from https://stackoverflow.com/a/34836998/9463643
import qimage2ndarray as q2n

buffer = QtCore.QBuffer()
buffer.open(buffer.WriteOnly)
buffer.seek(0)

img = (np.random.random((100,100))*255).astype('uint8')
img = q2n.array2qimage(img)

img.save(buffer, "PNG", quality=100)
encoded = bytes(buffer.data().toBase64()).decode() # <-- Here's the base 64 image
html = f'<img src="data:image/png;base64,{encoded}">'
element.setToolTip(html)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM