首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将Google-Cloud-Vision OCR协议响应保存/加载到磁盘?

如何将Google-Cloud-Vision OCR协议响应保存/加载到磁盘?
EN

Stack Overflow用户
提问于 2019-04-11 01:00:06
回答 1查看 619关注 0票数 4

我正在尝试将来自Google-Cloud-Vision OCR的响应保存到磁盘上,发现disk并存储实际的协议是最节省空间的选项,以便以后处理。这部分很简单!现在,我如何从磁盘检索并解析回它的原始格式?

我的问题是:在哪里/如何重新构建message_pb2文件,以便将文件解析回protobuf

下面是我到目前为止的documentation代码:

代码语言:javascript
复制
#!/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)
EN

回答 1

Stack Overflow用户

发布于 2019-04-12 14:14:29

看一看代码,答案如下:

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55617828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档