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

was*_*asd 11 python opencv numpy python-3.x google-cloud-platform

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

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

我需要做类似的事,但我的形象来自:

content = cv2.imread()
Run Code Online (Sandbox Code Playgroud)

哪个返回numpy数组,而不是字节.我试过了:

content = content.tobytes()
Run Code Online (Sandbox Code Playgroud)

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

alk*_*asm 14

你只需要在相同的格式图像阵列编码,并使用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
Run Code Online (Sandbox Code Playgroud)

  • 是的它会起作用,但这是一种非常低效的做事方式.您只使用OpenCV对视频进行解码,然后再以字节形式为云视觉API重新编码. (3认同)