How to get only "sorrow_likelihood" attribute from face_annotations in Google Vision API

Viewed 84

I want to get only "sorrow_likelihood" attribute from face_annotations in Google Vision API.

**Error**
Face detected

Traceback (most recent call last):
  File "e:\Repo\Mytrapture\web_project\web_project\test.py", line 26, in <module>
    print(response.face_annotations.sorrow_likelihood)
AttributeError: 'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute 'sorrow_likelihood'

Code snippet-

client = vision.ImageAnnotatorClient()
response = client.annotate_image({
                        'image': {
                            'source': {
                                'image_uri': url
                            }
                        }
                        })

f = "face_annotations"
if f in str(response):
    print("Face detected")
    print(response.face_annotations.sorrow_likelihood)
else:
    print("Face not detected")
1 Answers

There's a syntax error in this line:

print(response.face_annotations.sorrow_likelihood)

If you want to get the sorrow_likelihood value, you have to parse the face_annotations object because the Vision API responses are json format. You may try the code below:

print(response.face_annotations[0].sorrow_likelihood)

You can also try this below code for checking if a face is detected or not:

if response.face_annotations:
    print("Face Detected")
    for data in response.face_annotations:
        print(data.sorrow_likelihood)
else:
    print("Face not detected")

Output if Face Detected

Face Detected
Likelihood.VERY_LIKELY
Related