How to use Google Vision API in python program?
我正在尝试在python中运行最基本的文本检测和OCR(光学字符识别)程序。我的源代码取自此API的Google Cloud教程,其内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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(' "{}"'.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) |
但是,我得到以下错误:
1 2 3 4 | 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)我在我的.bash配置文件中添加了
如何修复此错误并使程序运行?
顺便说一下,如果我简单地加上
1 2 | import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"] ="/Users/User/PycharmProjects/GCP-OCR/Trial-e046e4bc6ce1.json" |
到我的源代码。
如果在python代码中设置变量时这样做有效,那么凭证就可以了。我自己测试了它,它也使用了您的初始方法。别忘了更新你的.bash_配置文件:
1 | source ~/.bash_profile |
如如何从命令行重新加载.bash_配置文件中所述?
验证环境变量是否正确设置为:
1 | echo $GOOGLE_APPLICATION_CREDENTIALS |
它应该输出到您的凭证的正确路径