启用 Cloud Vision API 以访问云存储上的文件

Enable Cloud Vision API to access a file on Cloud Storage

我已经看到有一些 similar questions 但其中 none 实际上提供了完整的答案。 由于我无法在该线程中发表评论,因此我将打开一个新线程。

如何处理下面 Brandon 的评论?

"... In order to use the Cloud Vision API with a non-public GCS object, you'll need to send OAuth authentication information along with your request for a user or service account which has permission to read the GCS object."?

我有 json 创建服务帐户时系统提供给我的 here 文件。 我正在尝试从 python 脚本 运行 api。

不清楚怎么用

我建议通过 运行 执行以下命令来使用 Vision API Client Library for python to perform the call. You can install it on your machine (ideally in a 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 环境变量和 运行。如果您授予它访问该文件的权限,它将 运行 成功。