Vision API:如何获取 JSON 输出

Bru*_*a B 7 google-api google-cloud-platform google-vision

我在保存 Google Vision API 提供的输出时遇到问题。我正在使用 Python 并使用演示图像进行测试。我收到以下错误:

TypeError: [mid:...] + is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

我执行的代码:

import io
import os
import json
# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

# Instantiates a client
vision_client = vision.ImageAnnotatorClient()


# The name of the image file to annotate
file_name = os.path.join(
    os.path.dirname(__file__),
    'demo-image.jpg') # Your image path from current directory

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = types.Image(content=content)

# Performs label detection on the image file
response = vision_client.label_detection(image=image)
labels = response.label_annotations


print('Labels:')
for label in labels:
    print(label.description, label.score, label.mid)

with open('labels.json', 'w') as fp:
   json.dump(labels, fp)
Run Code Online (Sandbox Code Playgroud)

输出出现在屏幕上,但我不知道如何保存它。有人有什么建议吗?

小智 5

仅供将来看到这一点的任何人使用,google-cloud-vision 2.0.0 已改用 proto-plus,它使用不同的序列化/反序列化代码。如果在不更改代码的情况下升级到 2.0.0,您可能会遇到的错误是:

object has no attribute 'DESCRIPTOR'
Run Code Online (Sandbox Code Playgroud)

使用google-cloud-vision 2.0.0, protobuf 3.13.0,这里是一个如何序列化和反序列化的例子(例子包括json和protobuf)

object has no attribute 'DESCRIPTOR'
Run Code Online (Sandbox Code Playgroud)

注1:proto-plus 不支持转换为snake_case 名称,在protobuf 中支持preserving_proto_field_name=True。所以目前有周围的字段名没有办法被转换response['full_text_annotation']response['fullTextAnnotation'] 有一个开放的这个封闭的功能要求:googleapis /原加蟒蛇#109

注 2:如果 x=0,google vision api 不会返回 x 坐标。如果 x 不存在,protobuf 将默认 x=0。在 python vision 1.0.0 using 中MessageToJson(),这些 x 值未包含在 json 中,但现在在 python vision 2.0.0 中,.To_Json()这些值包含为 x:0