gpt4 book ai didi

google-api - 视觉 API : How to get JSON-output

转载 作者:行者123 更新时间:2023-12-03 19:46:22 25 4
gpt4 key购买 nike

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

TypeError: [mid:...] + is not JSON serializable

我执行的代码:
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)

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

最佳答案

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

object has no attribute 'DESCRIPTOR'
使用google-cloud-vision 2.0.0, protobuf 3.13.0,这里是一个如何序列化和反序列化的例子(例子包括json和protobuf)
import io, json
from google.cloud import vision_v1
from google.cloud.vision_v1 import AnnotateImageResponse

with io.open('000048.jpg', 'rb') as image_file:
content = image_file.read()

image = vision_v1.Image(content=content)
client = vision_v1.ImageAnnotatorClient()
response = client.document_text_detection(image=image)

# serialize / deserialize proto (binary)
serialized_proto_plus = AnnotateImageResponse.serialize(response)
response = AnnotateImageResponse.deserialize(serialized_proto_plus)
print(response.full_text_annotation.text)

# serialize / deserialize json
response_json = AnnotateImageResponse.to_json(response)
response = json.loads(response_json)
print(response['fullTextAnnotation']['text'])
注1:proto-plus 不支持转换为snake_case 名称,protobuf 支持使用 preserving_proto_field_name=True .因此,目前无法绕过从 response['full_text_annotation'] 转换的字段名称。至 response['fullTextAnnotation']对此有一个开放关闭的功能请求: googleapis/proto-plus-python#109
注 2:如果 x=0,google vision api 不会返回 x 坐标。如果 x 不存在,protobuf 将默认 x=0。在 python 视觉 1.0.0 中使用 MessageToJson() ,这些 x 值未包含在 json 中,但现在使用 python vision 2.0.0 和 .To_Json()这些值包括为 x:0

关于google-api - 视觉 API : How to get JSON-output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52169264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com