9

Using Google Client Library interacting with the vision library.

I have a function to detect labels from an image.

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

        return labels

I have an api to call this function.

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

import os


class Vision(Resource):

    def get(self):

        return {"message": "API Working"}

    def post(self):

        googleVision = GoogleVision()

        req = request.get_json()

        url = req['url']

        result = googleVision.detectLabels(url)

        return result

However, it does not return the result and errors with the following

TypeError: Object of type 'RepeatedCompositeContainer' is not JSON serializable

Kay
  • 17,906
  • 63
  • 162
  • 270
  • 1
    "RepeatedCompositeContainer" comes from "protobuf" and as far as I can see, you are not using `MessageToJson`. Here you can see a [question](https://github.com/GoogleCloudPlatform/google-cloud-python/issues/3485#issuecomment-307797562) where it was recommended to use it or use dictionaries. Also, I saw this [SO question](https://stackoverflow.com/questions/20001229/how-to-get-posted-json-in-flask) to get json from Flask. – Iñigo Jul 16 '18 at 11:30
  • MessageToJson did not work either, there are questions about this that already exist. – Kay Jul 16 '18 at 12:44
  • @AkashJobanputra i ended up doing a for loop over the result and creating my own object – Kay Jul 24 '18 at 11:46
  • Would be nice if @Iñigo if you could provide a working solution. – Kay Jul 24 '18 at 11:47
  • 2
    @Kay I found the solution here, https://github.com/GoogleCloudPlatform/google-cloud-python/issues/3485#issuecomment-406194079 – Akash Jobanputra Jul 24 '18 at 11:47
  • @Kay do you still face this problem? – rmesteves Nov 03 '20 at 11:41

1 Answers1

5

This question was answered in this GitHub link, which might help to resolve your issue.

The error you encountered is

TypeError: Object of type 'RepeatedCompositeContainer' is not JSON serializable

Below is the solution provided in the GitHub thread

  • The Vision library returns plain protobuf objects, which can be serialized to JSON using:
from google.protobuf.json_format import MessageToJson
serialized = MessageToJson(original)
Vishal K
  • 1,368
  • 1
  • 7
  • 15