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

时间:2019-04-10 17:00:06

标签: python google-cloud-platform protocol-buffers google-cloud-vision

我正在尝试将来自Google-Cloud-Vision OCR的响应保存到磁盘,发现gzip压缩并存储实际的protobuf是用于以后处理的最节省空间的选项。那部分很简单!现在如何从磁盘取回并将其解析为原始格式?

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

documentation之后,这是到目前为止的代码:

#!/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)

1 个答案:

答案 0 :(得分:0)

浏览代码,这是答案:

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))