Aka*_*mar 6 python json python-3.x google-vision
我正在使用 Google Visiondocument_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)
Run Code Online (Sandbox Code Playgroud)
现在它抛出这个错误AttributeError: 'DESCRIPTOR'
我尝试了其他答案中的所有回复,但没有一个起作用。我也尝试过protobuf3-to-dict,但它也抛出错误
from protobuf_to_dict import protobuf_to_dict
text_json = protobuf_to_dict(response)
Run Code Online (Sandbox Code Playgroud)
它抛出:
AttributeError: 'ListFields'
Run Code Online (Sandbox Code Playgroud)
我知道我可以迭代它的对象,但我需要将其转储到 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)
Run Code Online (Sandbox Code Playgroud)
如果需要将响应作为字典,请执行以下操作而不是 json.dumps:
mydict = json.loads(texts)
Run Code Online (Sandbox Code Playgroud)
所有消息类型现在都使用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)
Run Code Online (Sandbox Code Playgroud)
请注意使用response._pb 而不是response。
| 归档时间: |
|
| 查看次数: |
1636 次 |
| 最近记录: |