用Python将google.cloud.vision_v1.types.image_annotator.AnnotateImageResponse转换为Json

6

我正在使用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文件中以维护缓存。

3个回答

5

在我关注的 GitHub 线程中找到了更好的答案,昨天发布。这里是翻译:

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进行定义,它使用不同的序列化和反序列化方法。


1
今天我在使用新的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 而不是 response。此与编程有关,保留 HTML 格式,不做解释。

0
我试过这种方法,它有效。
from google.cloud.vision_v1 import AnnotateImageResponse
json_str = AnnotateImageResponse.to_json(response)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接