Get emotions of images using Microsoft emotion API in Python

Get emotions of images using Microsoft emotion API in Python

The Microsoft Emotion API is a part of Azure's Cognitive Services. It allows developers to analyze faces in images to understand human emotions. The API can detect a range of emotions, such as happiness, sadness, anger, surprise, fear, etc.

Here's a tutorial on how to use the Microsoft Emotion API with Python:

Prerequisites:

  • An Azure account and a subscription to the Face API (previously known as the Emotion API).
  • Python installed on your machine.
  • The requests library. You can install it via pip:
pip install requests 

Steps:

  • Setting up Azure Face API:

    • Go to the https://portal.azure.com/.
    • Create a new Face API resource. Note down the key and the endpoint as you'll need them for the Python script.
  • Python Script:

import requests import json # Replace with your Face API key and endpoint subscription_key = 'YOUR_KEY_HERE' face_api_url = 'YOUR_ENDPOINT_HERE/face/v1.0/detect' # Set image_url to the URL of the image you want to analyze image_url = 'URL_OF_IMAGE_HERE' headers = { 'Ocp-Apim-Subscription-Key': subscription_key, 'Content-Type': 'application/json' } params = { 'returnFaceId': 'true', 'returnFaceLandmarks': 'false', 'returnFaceAttributes': 'emotion' } data = { 'url': image_url } response = requests.post(face_api_url, headers=headers, params=params, json=data) result = response.json() # Parse and print the emotions for face in result: emotions = face['faceAttributes']['emotion'] for emotion, score in emotions.items(): print(f"{emotion}: {score}") 

Replace 'YOUR_KEY_HERE' with your subscription key and 'YOUR_ENDPOINT_HERE' with the endpoint URL you got from the Azure portal. Also, replace 'URL_OF_IMAGE_HERE' with the URL of the image you want to analyze.

  • Run the Script:
    • Execute the script. The emotions detected in the image will be printed with their corresponding scores.

Notes:

  • Ensure that the image is accessible from the internet because the API processes the image through the URL.
  • The API will provide a score (between 0 and 1) for each emotion, indicating the likelihood of that emotion being present in the image.

Remember, as with all cloud-based services, there might be costs associated with using the Azure Face API, so always monitor your usage to avoid unexpected charges.


More Tags

qcheckbox clojurescript ms-access-2016 c11 r import python-packaging innodb drawer jitpack

More Programming Guides

Other Guides

More Programming Examples