![](/img/trans.png)
[英]Google's Vision Api protobuf response object to Python dictionary
[英]Attribute error DESCRIPTOR while trying to convert google vision response to dictionary with python
我在 Windows 上,使用Python 3.8.6rc1
, protobuf version 3.13.0
和google-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 object。 有人能幫我嗎? 謝謝
這並沒有真正回答我的問題,但我發現解決它並訪問 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)
也許看看這個帖子
json_string = type(response).to_json(response)
# Alternatively
import proto
json_string = proto.Message.to_json(response)
看第3步,
from google.ads.googleads.errors import GoogleAdsException
keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(
request=request
)
keyword_ideas_json = MessageToDict(keyword_ideas._pb) // add ._pb at the end of object
json
做任何你想做的事print(keyword_ideas_json)
Github 上同樣的問題: 這里
從發布的 github 問題@FriedrichSal 中, 您可以看到如今(2022 年) proto
完成了這項工作(庫 proto-plus):
現在所有消息類型都使用 proto-plus 定義,它使用不同的方法進行序列化和反序列化。
import proto
objects = client.object_localization(image=image)
json_obs = proto.Message.to_json(objects)
dict_obs = proto.Message.to_dict(objects)
MessageToJson(objects._pb)
仍然有效,但我不希望依賴“隱藏”屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.