我正在使用 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 文件中以维护缓存。
在我关注的 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定义,它使用不同的方法进行序列化和反序列化。
我今天在新的 Google Vision Client (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。
我尝试了这个方法,它有效:
from google.cloud.vision_v1 import AnnotateImageResponse
json_str = AnnotateImageResponse.to_json(response)