简体   繁体   English

谷歌的Vision Api protobuf响应Python字典的对象

[英]Google's Vision Api protobuf response object to Python dictionary

I'm working on a project in which I need to analyze an image using Google's Vision API and post the response to a Dynamodb table. 我正在开发一个项目,我需要使用Google的Vision API分析图像并将响应发布到Dynamodb表。

I have successfully implemented the Vision API, but not able to convert its response into Python Dictionary. 我已经成功实现了Vision API,但无法将其响应转换为Python Dictionary。

Here's what I have tried: 这是我尝试过的:

       if form.is_valid():
            obj = form
            obj.imageFile = form.cleaned_data['imageFile']
            obj.textFile = form.cleaned_data['textFile']
            obj.save()
            print(obj.imageFile)
            # Process the image using Google's vision API
            image_path = os.path.join(settings.MEDIA_ROOT, 'images/', obj.imageFile.name)
            print(image_path)
            image = vision_image_manager(image_path)
            text_path = os.path.join(settings.MEDIA_ROOT, 'texts/', obj.textFile.name)
            text = nlp_text_manager(text_path)
            # print(image)
            # print(text)
            results = {
                'imageResponse': image,
                'textResult': text
            }
            print(results.values())
            print(type(results))
            post_to_dynamo_db(image, text)

Here's the Vision api implementation: 这是Vision api的实现:

def vision_image_manager(image_file):
    # Instantiates a client
    client = vision.ImageAnnotatorClient()
    file_name = str(image_file)
    with open(file_name, 'rb') as img_file:
        content = img_file.read()
    image = types.Image(content=content)
    response = client.label_detection(image=image)
    labels = response.label_annotations
    print('Labels:')
    for label in labels:
        print(label.description)
    return labels

And Here's the post_to_dynamo_db Function: 这是post_to_dynamo_db函数:

def post_to_dynamo_db(image, text):
session = boto3.Session(
    aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
    aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY
)
client = session.resource('dynamodb')
table = client.Table('basetbl')
result_dict = {
    'image': image,
    'text': text
}
json_dict = dict_to_item(result_dict)
# item = dict_to_item(result_dict)
table.put_item(
    Item={
        'id': int(generate_pid()),
        'response_obj': json_dict
    }
)

Now, It doesn't return any error but the response_obj is not posted in Database table because it's not the correct form of the object, the problem here is the <class 'google.protobuf.pyext._message.RepeatedCompositeContainer'> type of response returns from Google's API. 现在,它没有返回任何错误,但是response_obj没有在Database表中发布,因为它不是对象的正确形式,这里的问题是<class 'google.protobuf.pyext._message.RepeatedCompositeContainer'>响应类型从Google的API返回。

The best way to get a proper python friendly response from Vision API is to use this API via the Google's Discovery service. 从Vision API获得正确的python友好响应的最佳方法是通过Google的Discovery服务使用此API。

Here's how this will work for you: 以下是这对您有用的方法:

def vision_image_manager(image_file):
    # Instantiates a client
    service = discovery.build('vision', 'v1', credentials=credentials)
    # text.png is the image file.
    file_name = str(image_file)
    with open(file_name, 'rb') as image:
        image_content = base64.b64encode(image.read())
        service_request = service.images().annotate(body={
            'requests': [{
                'image': {
                    'content': image_content.decode('UTF-8')
                },
                'features': [{
                    'type': 'LABEL_DETECTION',
                }]
            }]
        })
    response = service_request.execute()
    print(response['responses'])
    res_dict = dict(response)
    return res_dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python发送rest API(Google Vision的API)请求? - How to send rest API (Google Vision's API) request with python? Google Cloud Vision API - Python - Google Cloud Vision API - Python 尝试使用 python 将 Google 视觉响应转换为字典时出现属性错误 DESCRIPTOR - Attribute error DESCRIPTOR while trying to convert google vision response to dictionary with python 将 Google Vision API 响应转换为 JSON - Convert Google Vision API response to JSON Python3.7 Vision API输出到字典 - Python3.7 Vision API output to dictionary Google的Vision API可以接受来自任何外部服务器的URL并在该图像上返回响应吗? - Can Google's Vision API accept a URL from any external server and return a response on that image? Google Vision API的标签检测功能 - Google Vision API's label detection 尽管已分配了正确的服务帐户,但使用Google AutoML vision Python API仍获得403响应 - getting a 403 response with Google AutoML vision Python API despite having assigned right Service Account 如何在python程序中使用Google Vision API? - How to use Google Vision API in python program? 如何将 Google-Cloud-Vision OCR protobuf 响应保存/加载到磁盘? - How to save/load Google-Cloud-Vision OCR protobuf response to disk?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM