如何将Google Client Vision库响应转换为Json

时间:2018-06-15 11:03:16

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

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

  

AttributeError:' google.protobuf.pyext._message.RepeatedCompositeCo'   对象没有属性' 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

标签变量的类型为<class'google.protobuf.pyext._message.RepeatedCompositeContainer'>

正如你所看到我在标签响应中使用消息到json函数。但我得到了上述错误。

有没有办法将结果转换为json格式?

1 个答案:

答案 0 :(得分:3)

一种简单的方法是使用发现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。

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

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