我正在尝试使用Google Vision API来读取图片的标签。
我正在Google Compute Engine实例上执行此操作,可以访问所有Cloud API。我正在使用服务帐户进行身份验证
这是我正在执行的代码
import io
#from google.cloud import storage
#from google.cloud.vision_v1 import ImageAnnotatorClient
from google.oauth2 import service_account
# using old version of API
from google.cloud import vision
from google.cloud.vision import types
image_client = vision.ImageAnnotatorClient(credentials='credentials.json')
with io.open('/home/username/instagram-ml/userbucket/images/test_image.jpg','rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
#
image_response = image_client.label_detection(image =image)
labels = image_response.label_annotations
直到行
image_response = image_client.label_detection(image =image)
一切正常,我没有认证问题。但是当我执行上面的行时,我突然得到了这个错误。
非常遵循此page
上的说明不太确定出了什么问题
答案 0 :(得分:2)
您为客户端提供了一个字符串(文件名?)作为凭据,但是如docs中所指定的,凭证参数(如果通过)应该是Credentials的实例或其子类之一
答案 1 :(得分:0)
要确定错误,请在设置凭据之前将以下行添加到您的代码中:
print('Credendtials from environ: {}'.format(os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')))
如果输出为Credendtials from environ: None
,则说明该脚本未在设置了GOOGLE_APPLICATION_CREDENTIALS环境变量的上下文中运行。
要解决此问题,请首先确保您创建了服务帐户私钥。可以在链接https://google-auth.readthedocs.io/en/latest/user-guide.html#service-account-private-key-files和Guideline on Setup
中找到创建服务帐户的步骤。创建服务帐户和密钥时,将自动下载json文件。复制此文件的位置,例如:'C:/awesome-credentials.json'。
接下来安装以下库:
然后,使用以下代码在脚本中设置凭据:
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file('C:/awesome-credentials.json')
client = vision.ImageAnnotatorClient(credentials=credentials)
这是整个代码的示例:
from google.cloud import vision
import io
import os
from google.oauth2 import service_account
def detect_text(path):
"""Detects text in the file."""
credentials = service_account.Credentials.from_service_account_file('C:/awesome-credential.json')
print('Credendtials from environ: {}'.format(os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')))
client = vision.ImageAnnotatorClient(credentials=credentials)
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.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)))