Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn numpy array image to bytes?

Tags:

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

like image 972
wasd Avatar asked May 31 '18 17:05

wasd


People also ask

Can an image could be converted into a NumPy array?

Using OpenCV Library imread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. Then we need to convert the image color from BGR to RGB. imwrite() is used to save the image in the file.

Why do we convert image to NumPy array?

Converting an image to an array is an important task to train a machine learning model based on the features of an image. We mainly use the NumPy library in Python to work with arrays so we can also use it to convert images to an array.


1 Answers

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
like image 83
alkasm Avatar answered Oct 01 '22 05:10

alkasm