python - 如何将 Google 客户端视觉库响应转换为 Json

标签 python json google-api protocol-buffers google-cloud-vision

我正在尝试将来自 Google Cloud Vision API 客户端库的响应转换为 json 格式。但是我收到以下错误:

AttributeError: 'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute 'DESCRIPTOR

资源

from flask_restful import Resource
from flask import request
from flask import json
from util.GoogleVision import GoogleVision
from util.Convert import Convert

import base64
import requests

import os


class Vision(Resource):

    def post(self):

        googleVision = GoogleVision()

        req = request.get_json()

        url = req['url']

        result = googleVision.detectLabels(url)

        return result

GoogleVision.py

import os

from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToJson

class GoogleVision():

    def detectLabels(self, uri):

        client = vision.ImageAnnotatorClient()
        image = types.Image()
        image.source.image_uri = uri

        response = client.label_detection(image=image)
        labels = response.label_annotations

        res = MessageToJson(labels)

        return res

labels 变量的类型是 <class'google.protobuf.pyext._message.RepeatedCompositeContainer'>

如您所见,我在标签响应上使用了 message to json 函数。但我收到上述错误。

有没有办法把结果转成json格式?

最佳答案

一种简单的方法是使用 Discovery API。您可以使用 build() 创建服务对象功能。执行请求时,您将获得字典形式的响应。然后您可以使用 json.dumps() 将其转换为 JSON .

Discovery API 示例:

import json
import apiclient.discovery
import base64

class GoogleVision():

    def detectLabels(self, uri):

        # Instantiates a client
        service = apiclient.discovery.build('vision', 'v1')

        # Image file
        file_name=uri

        # Loads the image into memory
        with open(file_name, 'rb') as image:
            image_content = base64.b64encode(image.read())

            # Creates the request
            service_request = service.images().annotate(body={
                'requests': [{
                    'image': {
                        'content': image_content.decode('UTF-8')
                    },
                    'features': [{
                        'type': 'LABEL_DETECTION',
                    }]
                }]
            })

        # Execute the request  
        response = service_request.execute()

        # Convert to Json
        res_json = json.dumps(response)

        return res_json

如果您不想使用 Discovery API,可以使用 MessageToDict() 将响应转换为字典先使用函数,然后使用 json.dumps() 转换为 JSON .

不使用 Discovery API 的示例 MessageToDict() :

import json
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToDict

class GoogleVision():

    def detectLabels(self, uri):

        # Instantiates a client
        client = vision.ImageAnnotatorClient()

        # Image file
        file_name=uri

        # Loads the image into memory
        with open(file_name, 'rb') as image:
            image_content = image.read()

        image = types.Image(content=image_content)

        # Performs label detection on the image file
        response = client.label_detection(image=image)       

        #Convert the response to dictionary
        response = MessageToDict(response)

        # Convert to Json
        res_json = json.dumps(response)

        return res_json

关于python - 如何将 Google 客户端视觉库响应转换为 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50874265/

相关文章:

python - 使用 SciPy 或 NumPy 生成具有指定权重的离散随机变量

JavaScript 无法识别 HTML 数组

node.js - Google Search Console API : How do I Solve "User does not have sufficient permission for site"?(当用户有权限时)

python - Python 中的 For(不是 foreach)循环

python - sql语句中的pyodbc路径不起作用

python - 在 Python 中使用 Regex 获取特定字符串

python - 解析requests.post对象

json - 如何将docker run命令转换为json文件?

java - 使用 Jackson 在 Java 中序列化为 JSON 时出现问题

python - 可以随时间获取 alexa 信息或 google 页面排名吗?