我想使用本地存储的图像向Google视觉API发送请求。我遵循“ Python Client for Google Cloud Vision¶”指南,特别是“注释图像”下的代码示例。为了建立我的请求,我遵循“ Base64 Encoding”中的示例。
这是我写的代码:
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运行代码后,我收到以下错误消息:
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'
我也尝试过this Example,但收到错误消息“在'types.py'中找不到参考'图像'。
您能解释我做错了什么,并提供一个使用本地图像查询Google Vision API的基本示例吗?
在您链接的示例中,没有请求的数组。试试这个:
query = {
"image": {
"content": encode_image(image_path)
},
"features": [
{
"type": "FACE_DETECTION",
"maxResults": 10
}
]
}