【问题标题】:Enable Cloud Vision API to access a file on Cloud Storage启用 Cloud Vision API 以访问 Cloud Storage 上的文件
【发布时间】:2018-05-13 00:25:39
【问题描述】:
我已经看到有一些similar questions,但它们实际上都没有提供完整的答案。
由于我无法在该线程中发表评论,因此我正在打开一个新线程。
如何解决Brandon下面的评论?
"...
要将 Cloud Vision API 与非公共 GCS 对象一起使用,
您需要将 OAuth 身份验证信息与您的
请求具有读取权限的用户或服务帐户
GCS 对象。”?
当我创建服务帐户时,我有系统提供给我的 json 文件,如 here 所述。
我正在尝试从 python 脚本运行 api。
不清楚如何使用。
【问题讨论】:
标签:
authentication
google-cloud-storage
google-oauth
google-cloud-vision
【解决方案1】:
我建议使用Vision API Client Library for python 来执行调用。您可以通过运行以下命令将它安装在您的机器上(最好是在virtualenv):
pip install --upgrade google-cloud-vision
接下来,您需要将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含您的服务帐户密钥的 JSON 文件的文件路径。例如,在 Linux 机器上,你会这样做:
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
最后,您只需像这样调用 Vision API 客户端的方法(例如这里的 label_detection 方法):
def detect_labels():
"""Detects labels in the file located in Google Cloud Storage."""
client = vision.ImageAnnotatorClient()
image = types.Image()
image.source.image_uri = "gs://bucket_name/path_to_image_object"
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description)
通过不带参数初始化客户端,库将自动查找您之前设置的GOOGLE_APPLICATION_CREDENTIALS 环境变量,并代表此服务帐户运行。如果您授予它访问文件的权限,它将成功运行。