问题描述
我正在使用Google Vision document_text_detection
函数,并且试图将AnnotateImageResponse转储到json
此代码以前用于单词
client = vision.ImageAnnotatorClient()
image = vision.Image(content=image)
response = client.document_text_detection(image=image)
texts = MessagetoDict(response)
text_json = json.dumps(texts)
现在它引发此错误AttributeError: 'DESCRIPTOR'
我尝试了其他答案中的所有答案,但没有一个起作用。我也尝试过protobuf3-to-dict
,但它也会引发错误
from protobuf_to_dict import protobuf_to_dict
text_json = protobuf_to_dict(response)
它抛出:
AttributeError: 'ListFields'
我知道我可以对其进行迭代,但是我需要将其转储到json文件中以保持缓存。
解决方法
今天,我在使用新的Google Vision客户端(2.0.0)时遇到了类似的问题,并解决了该问题,它拆开了AnnotateImageResponse对象。我不认为这是新API的工作方式,但目前文档中未提出解决方案。试试这个:
client = vision.ImageAnnotatorClient()
image = vision.Image(content=image)
response = client.document_text_detection(image=image)
texts = MessageToDict(response._pb)
text_json = json.dumps(texts)
请注意使用response._pb代替了响应。
,在我关注的GitHub线程posted yesterday上找到了一个更好的答案。对此问题进行了翻译:
import proto
client = vision.ImageAnnotatorClient()
image = vision.Image(content=image)
response = client.document_text_detection(image=image)
texts = proto.Message.to_json(response)
text_json = json.dumps(texts)
如果需要响应作为字典,请执行以下操作,而不要执行json.dumps:
mydict = json.loads(texts)
所有消息类型现在都使用proto-plus定义,它使用不同的方法进行序列化和反序列化。