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

时间:2021-11-03 21:21:44

I need to recognize image with Google Vision API. Among the examples, they use following construction:

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

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

I need to do similar, but my image comes from:

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

content = cv2.imread()

Which returns numpy array, not bytes. I tried:

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

content = content.tobytes()

Which converts array to bytes, but returns different bytes apparently, since it gives different result.
So how to make my image array similar to one which I get by open() function

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

1 个解决方案

#1


3  

You simply need to encode the array in the same format as the image, and then use tobytes() if you want it in the same format.

您只需要以与图像相同的格式对数组进行编码,然后使用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

#1


3  

You simply need to encode the array in the same format as the image, and then use tobytes() if you want it in the same format.

您只需要以与图像相同的格式对数组进行编码,然后使用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