I'm having a problem with base64 encoded images sent to Google Cloud Vision. Funny thing is that if I send the image via URI, it works fine, so I suspect there is something wrong the way I'm encoding.
Here's the deal:
from google.cloud import vision
import base64
client = vision.ImageAnnotatorClient()
image_path ='8720911950_91828a2aeb_b.jpg'
with open(image_path, 'rb') as image:
image_content = image.read()
content = base64.b64encode(image_content)
response = client.annotate_image({'image': {'content': content}, 'features': [{'type': vision.enums.Feature.Type.LABEL_DETECTION}],})
print(response)
The response I get always is:
error {
code: 3
message: "Bad image data."
}
If I try using URI instead:
response = client.annotate_image({'image': {'source': {'image_uri': 'https://farm8.staticflickr.com/7408/8720911950_91828a2aeb_b.jpg'}}, 'features': [{'type': vision.enums.Feature.Type.LABEL_DETECTION}],})
Response is ok...
label_annotations {
mid: "/m/0168g6"
description: "factory"
score: 0.7942917943000793
}
label_annotations {
mid: "/m/03rnh"
description: "industry"
score: 0.7761002779006958
}
I've followed the recommended way to encode from Google
Any idea what is wrong here?
content = base64.b64encode(image_content).decode()
– Glenntypes.Image()
constructor. – Glennvision.ImageAnnotatorClient.annotate_image()
automatically. Their documentation on base64 encoding is only for the case when you create and send the HTTP request on your own. So try eliminating base64 encoding:content = image.read()
– Glenn