如何将 numpy 数组图像转换为字节? [英] How to turn numpy array image to bytes?
问题描述
我需要使用 Google Vision API 识别图像.在示例中,它们使用以下结构:
with io.open('test.png', 'rb') 作为 image_file:内容 = image_file.read()图像 = vision.types.Image(content=content)
我需要做类似的,但我的图片来自:
content = cv2.imread()
返回 numpy 数组,而不是字节.我试过了:
content = content.tobytes()
将数组转换为字节,但显然返回不同的字节,因为它给出了不同的结果.
那么如何使我的图像数组类似于我通过 open()
函数获得的图像数组
你只需要将数组编码成与图像相同的格式,然后然后使用 tobytes()代码>,如果你想要相同的格式.
I need to recognize image with Google Vision API. Among the examples, they use following construction:
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:
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
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.
>>> 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
这篇关于如何将 numpy 数组图像转换为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!