如何将numpy数组映像转换为字节?

2024-04-26 14:42:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用Google Vision API识别图像。在这些示例中,它们使用以下结构:

with io.open('test.png', 'rb') as image_file:
    content = image_file.read()
image = vision.types.Image(content=content)

我也需要这样做,但我的形象来自:

content = cv2.imread()

返回numpy数组,而不是字节。我试过:

content = content.tobytes()

它将数组转换为字节,但返回的字节显然不同,因为它给出的结果不同。
那么如何使我的图像数组与通过open()函数得到的图像数组相似


Tags: iotest图像imageapi示例字节with
1条回答
网友
1楼 · 发布于 2024-04-26 14:42:39

您只需将数组编码为与图像相同的格式,如果您希望使用相同的格式,则使用tobytes()

>>> import cv2
>>> with open('image.png', 'rb') as image_file:
...     content1 = image_file.read()
...
>>> image = cv2.imread('image.png')
>>> success, encoded_image = cv2.imencode('.png', image)
>>> content2 = encoded_image.tobytes()
>>> content1 == content2
True

相关问题 更多 >