Akash Kumar
Akash Kumar

Reputation: 1406

google.cloud.vision_v1.types.image_annotator.AnnotateImageResponse to Json in python

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.

Upvotes: 7

Views: 1901

Answers (3)

Allen Wu
Allen Wu

Reputation: 1

I tried this way and it works:

from google.cloud.vision_v1 import AnnotateImageResponse
json_str = AnnotateImageResponse.to_json(response)

Upvotes: 0

CSquare
CSquare

Reputation: 642

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.

Upvotes: 5

CSquare
CSquare

Reputation: 642

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.

Upvotes: 1

Related Questions