gpt4 book ai didi

python - 将 Google Vision API 响应转换为 JSON

转载 作者:太空狗 更新时间:2023-10-30 00:58:47 25 4
gpt4 key购买 nike

任务:

  • 将 Google Vision API 响应转换为 JSON

问题:

  • API 调用的返回值不是 JSON 格式

Python 函数

def detect_logos(path):
"""Detects logos in the file."""
client = vision.ImageAnnotatorClient()

# [START migration_logo_detection]
with io.open(path, 'rb') as image_file:
content = image_file.read()

image = types.Image(content=content)

response = client.logo_detection(image=image)
logos = response.logo_annotations

print('Logos:')
print(logos)
print(type(logos))

Google 在线 JSON

"logoAnnotations": [
{
"mid": "/m/02wwnh",
"description": "Maxwell House",
"score": 0.41142157,
"boundingPoly": {
"vertices": [
{
"x": 74,
"y": 129
},
{
"x": 161,
"y": 129
},
{
"x": 161,
"y": 180
},
{
"x": 74,
"y": 180
}
]
}
}

Google 回复(列表)

 [mid: "/m/02wwnh"
description: "Maxwell House"
score: 0.4114215672016144
bounding_poly {
vertices {
x: 74
y: 129
}
vertices {
x: 161
y: 129
}
vertices {
x: 161
y: 180
}
vertices {
x: 74
y: 180
}
}
]

类型:

google.protobuf.internal.containers.RepeatedCompositeFieldContainer

尝试过:

Protobuf to json in python

最佳答案

Google vision 2.0 需要不同的代码,如果不更改代码将抛出以下错误:

object has no attribute 'DESCRIPTOR'

这是一个如何使用 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。在使用 MessageToJson() 的 python vision 1.0.0 中,这些 x 值未包含在 json 中,但现在使用 python vision 2.0.0 和 .To_Json(),这些值包含为 x:0

关于python - 将 Google Vision API 响应转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623615/

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