如何在python程序中使用Google Vision API?

问题描述 投票:2回答:1

我正在尝试在python中运行最基本的文本检测和Google Vision API的OCR(光学字符识别)程序。我的源代码来自此API的Google Cloud教程,其内容如下:

import  io
from google.cloud import vision
from google.cloud.vision import types

def detect_text(file):
    """Detects text in the file."""
    client = vision.ImageAnnotatorClient()

    with io.open(file, 'rb') as image_file:
        content = image_file.read()

    image = types.Image(content=content)

    response = client.text_detection(image=image)
    texts = response.text_annotations
    print('Texts:')

    for text in texts:
        print('\n"{}"'.format(text.description))

        vertices = (['({},{})'.format(vertex.x, vertex.y)
                    for vertex in text.bounding_poly.vertices])

        print('bounds: {}'.format(','.join(vertices)))

file_name = "prescription.jpg"
detect_text(file_name)

但是我收到以下错误:

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application. For more
information, please see
https://developers.google.com/accounts/docs/application-default-credentials.

这很奇怪,因为:

1)我创建了一个新的服务帐户

2)我将export GOOGLE_APPLICATION_CREDENTIALS="/Users/User/PycharmProjects/GCP-OCR/Trial-e046e4bc6ce1.json"添加到我的.bash_profile(我把json文件放在这个项目的Pycharm文件中)也许唯一奇怪的是json文件中的私钥大约是20行,而我希望大约是1行。

如何修复此错误并使程序运行?

顺便说一句,如果我简单地添加问题就解决了

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/User/PycharmProjects/GCP-OCR/Trial-e046e4bc6ce1.json"

到我的源代码。

python google-cloud-platform google-cloud-vision
1个回答
2
投票

如果在Python代码中设置变量时,凭据可以正常工作。我自己测试了它,它也可以使用你的初始方法。不要忘记使用以下命令更新.bash_profile:

source ~/.bash_profile

正如How to reload .bash_profile from the command line?所解释的那样

验证环境变量是否已正确设置:

echo $GOOGLE_APPLICATION_CREDENTIALS

应该输出您的凭据的正确路径

© www.soinside.com 2019 - 2024. All rights reserved.