google.cloud.vision_v1.types.image_annotator.AnnotateImageResponse to Json in python
Asked Answered
S

3

7

I am using Google Vision document_text_detection function and I am trying to dump the AnnotateImageResponse to json

Earlier this code used to word

client = vision.ImageAnnotatorClient()
image = vision.Image(content=image)

response = client.document_text_detection(image=image)
texts = MessageToDict(response)
text_json = json.dumps(texts)

Now it throws this error AttributeError: 'DESCRIPTOR'

I tried all the responses in other answers but none of them worked. I also tried protobuf3-to-dict but it also throws error

from protobuf_to_dict import protobuf_to_dict
text_json = protobuf_to_dict(response)

It throws:

AttributeError: 'ListFields'

I know I can iterate it the object but I need to dump it in json file to maintain cache.

Sludge answered 12/10, 2020 at 14:50 Comment(0)
I
5

Found a better answer on the GitHub thread I was following, posted yesterday. Translated for this question:

import proto
client = vision.ImageAnnotatorClient()
image = vision.Image(content=image)

response = client.document_text_detection(image=image)
texts = proto.Message.to_json(response)
text_json = json.dumps(texts)

If response needed as a dict, do the following instead of json.dumps:

mydict = json.loads(texts)

All message types are now defined using proto-plus, which uses different methods for serialization and deserialization.

Indoeuropean answered 21/10, 2020 at 7:46 Comment(1)
crazy stuff.. this is so slow!Gastronomy
I
1

I ran into a similar problem today with the new Google Vision Client (2.0.0) and solved it unpacking the AnnotateImageResponse object. I Don't think this is how the new API should work but at the moment no solution is proposed in the documentation. Try this:

client = vision.ImageAnnotatorClient()
image = vision.Image(content=image)

response = client.document_text_detection(image=image)
texts = MessageToDict(response._pb)
text_json = json.dumps(texts)

Note the use of response._pb instead of response.

Indoeuropean answered 18/10, 2020 at 18:7 Comment(0)
M
0

I tried this way and it works:

from google.cloud.vision_v1 import AnnotateImageResponse
json_str = AnnotateImageResponse.to_json(response)
Metanephros answered 13/9, 2023 at 2:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.