首页 > 解决方案 > 如何将 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)

标签: pythongoogle-cloud-platformprotocol-buffersgoogle-cloud-vision

解决方案


翻阅代码,答案如下:

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

推荐阅读