试图使用python将google vision响应转换为dictionary时出现属性错误描述符

2024-07-03 06:13:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows上,使用Python 3.8.6rc1protobuf version 3.13.0google-cloud-vision version 2.0.0

我的代码是:

from google.protobuf.json_format import MessageToDict
from google.cloud import vision
    
client = vision.ImageAnnotatorClient()
response = client.annotate_image({
            'image': {'source': {'image_uri': 'https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60'}},
        })
MessageToDict(response)

它在MessageToDict(response)失败,我有一个attribute error: "DESCRIPTOR"。看起来response不是有效的protobuf对象。有人能帮我吗?多谢各位


Tags: 代码fromimageimportclientjsonformatcloud
3条回答

这并没有真正回答我的问题,但我发现解决它并访问protobuf对象的一种方法是使用response._pb,因此代码变成:

response = client.annotate_image({
            'image': {'source': {'image_uri': 'https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60'}},
        })
MessageToDict(response._pb)

看第三步

步骤1:导入此库

from google.ads.googleads.errors import GoogleAdsException

步骤2:发送请求

keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(
    request=request
)

步骤3:将响应转换为json[Look here]

keyword_ideas_json = MessageToDict(keyword_ideas._pb) // add ._pb at the end of object

第四步:用这个json

做任何你想做的事
print(keyword_ideas_json)

同一问题的Github:here

也许看看this post

json_string = type(response).to_json(response)
# Alternatively
import proto
json_string = proto.Message.to_json(response)

相关问题 更多 >