如何将numpy数组图像转换为字节? [英] How to turn numpy array image to bytes?

查看:502
本文介绍了如何将numpy数组图像转换为字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

Which returns numpy array, not bytes. I tried:

content = content.tobytes()

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

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

推荐答案

您只需要使用与图像相同的格式对数组进行编码,并且然后如果需要,可以使用tobytes()相同的格式.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆