19
votes

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

1
Which bytes do you need? The bytes of the PNG file? The bytes of the decompressed image in RGBA5, RGB8, or RGB16 format depending on what’s in the file? Or specifically in, say, RGB8 no matter how the file was stored? The bytes of the four separate decompressed 16-bit planes in R-G-B-A order? (Little- or big-endian?) Something else? - abarnert
@abarnert I don't know exactly. I just want it to look same as as open('file.png', 'rb') gives me. Is there a way to check it? - wasd
Then use encoded_bytes = cv2.imencode('.png', content) - zindarod
@zindarod Understood... but I'm still confused. If the OP is using cv2.imread where you specify where the image is located... why can't they just simply use open on it instead? - rayryeng
If you’re not actually doing any processing with cv2, decoding a PNG file just to encode that as a PNG again is pretty silly… - abarnert

1 Answers

30
votes

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