使用 Google Client Library 与视觉库交互。
我有一个从图像中检测标签的功能。
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
我有一个api来调用这个函数。
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
但是,它不会返回结果并出现以下错误
类型错误:“RepeatedCompositeContainer”类型的对象不是 JSON
可序列化
这个问题在此得到了回答GitHub 链接,这可能有助于解决您的问题。
您遇到的错误是
TypeError: Object of type 'RepeatedCompositeContainer' is not JSON serializable
以下是 GitHub 线程中提供的解决方案
- Vision 库返回普通的 protobuf 对象,可以使用以下方法将其序列化为 JSON:
from google.protobuf.json_format import MessageToJson
serialized = MessageToJson(original)
- 您还可以使用类似的方法去字典protobuf3 到 dict.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)