2
votes

I want to send a request to the Google vision API, using an Locally stored Image. Im following the "Python Client for Google Cloud VisionĀ¶" guide, exspecialy the code example under "Annotage an Image". For building my request I follow the example from "Base64 Encoding".

Here is the code I wrote:

from google.cloud.vision import ImageAnnotatorClient
import os
import base64
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'keys/sc_google.json'

def encode_image(image_path):
    with open(image_path, "rb") as f:
        image_content = f.read()
        return base64.b64encode(image_content)

client = ImageAnnotatorClient()
image_path = 'images/happy_baby3.png'
query = {
    "requests": [
        {
            "image": {
                "content": encode_image(image_path)
            },
            "features": [
                {
                    "type": "FACE_DETECTION",
                    "maxResults": 10
                }
            ]
        }
    ]
}
response = client.annotate_image(query)
print(response.annotations)

Stil wenn running the code I get the following error message:

Traceback (most recent call last):
  File "/mnt/c/Users/nomis/PycharmProjects/hello_web_app/emotion_detection.py", line 29, in <module>
    response = client.annotate_image(query)
  File "/usr/local/lib/python3.6/dist-packages/google/cloud/vision_helpers/__init__.py", line 55, in annotate_image
    image = protobuf.get(request, "image")
  File "/usr/local/lib/python3.6/dist-packages/google/api_core/protobuf_helpers.py", line 192, in get
    raise KeyError(key)
KeyError: 'image'

I also tried this Example but got the error "Can not find Reference 'Image' in 'types.py'.

Could you explain what I'm doing wrong, and provide a minimal working example of how to query the Google Vision API using a local Image?

1

1 Answers

2
votes

In the example you linked, there is no array of requests. Try this:

query = {
            "image": {
                "content": encode_image(image_path)
            },
            "features": [
                {
                    "type": "FACE_DETECTION",
                    "maxResults": 10
                }
            ]
}