python - 如何将 Google-Cloud-Vision OCR protobuf 响应保存/加载到磁盘?
问题描述
我正在尝试将来自 Google-Cloud-Vision OCR 的响应保存到磁盘,并发现 gzip 压缩和存储实际的 protobuf 是以后处理中最节省空间的选项。那部分很容易!现在如何从磁盘检索并将其解析回其原始格式?
我的问题是:我在哪里/如何重建 message_pb2 文件以将文件解析回 protobuf
以下文档到目前为止,这是我的代码:
#!/usr/bin/python3
# coding: utf-8
from google.cloud import vision
import gzip, os, io
def ocr_document(path):
"""
Detects document features in an image.
Returns response protobuf from API.
"""
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
response = client.document_text_detection(image=image)
return(response)
response = ocr_document('handwritten-scan.jpg')
serialized = response.SerializeToString()
with gzip.open('response.pb.gz', 'wb') as f:
f.write(serialized)
print(os.path.getsize('response.pb.gz'), 'bytes') # Output: 11032 bytes
# Figure this part out!
with gzip.open('response.pb.gz', 'rb') as f:
serialized=f.read()
### parsed = message_pb2.Message() # < - Protobuf message I'm missing
parsed.ParseFromString(serialized)
print(parsed)
解决方案
翻阅代码,答案如下:
from google.cloud.vision_v1.proto import image_annotator_pb2
from google.protobuf.json_format import MessageToDict
with gzip.open('response.pb.gz', 'rb') as lf:
Loaded=lf.read()
parsed = image_annotator_pb2.AnnotateImageResponse()
parsed.ParseFromString(Loaded)
print(MessageToDict(parsed))
推荐阅读
- flowable - FLOWABLE:如何更改异步作业的 5 分钟默认间隔
- python - 按另一个列表的顺序对齐三列 DataFrame
- javascript - ReactJS - 获得调度结果的正确方法
- php - 如何让 Laravel Nova 像 Fields
- python - 需要帮助从动态网站检索网站密钥
- electron - 带有 C++ 后端的电子 - 安全吗?
- windows - 有没有办法将卷设备映射到 USB 设备?
- node.js - 如何使用 nodejs 和 dynamoDB 扫描表过滤多个值?
- html - 为什么该位置在该部分中无法正常工作
- terraform - 如何跨工作区/模块共享 Terraform 变量?