FACEMOTION API Endpoint

Version 2.197 (Release Notes ↗)

Description

FACEMOTION API detects human faces, providing rectangle coordinates and estimating gender, age, and emotion through facial shapes. Output the rectangle coordinates for each detected human face and try to guess their gender, age and emotion pattern via their facial shapes.

HTTP Methods

GET, POST

HTTP Parameters

Required

Fields Type Description
img URL Input media URL. If you want to upload your image directly from your app, then submit a multipart/form-data POST request.
key String Your PixLab API Key ↗. You can also embed your key in the WWW-Authenticate: HTTP header and omit this parameter if you want to.

POST Request Body

This section details the requirements for using a POST request instead of a simple GET request.

Allowed Content-Types:

multipart/form-data
application/json

Use multipart/form-data if you want to upload your media file directly (refer to the REST API code samples or The PixLab Github Repository↗ for a working example). If you are using JSON, then the media file must be already uploaded somewhere. Call store if you want to upload an image before invoking this endpoint.

HTTP Response

application/json

The API returns a JSON response containing facial emotion analysis. Key fields are emotion and rectangle. Response structure:
Fields Type Description
status Integer HTTP status code (200 indicates success)
faces Array Array of detected faces with coordinates, age, gender and emotion data
error String Error description if status ≠ 200

Each object in the faces array contains:
Fields Type Description
rectangle Object Face coordinates: top, left, width, height
age Integer Approximate age in years
gender String Detected gender (male/female)
emotion Object Emotion analysis with state and score. Possible states: anger, contempt, disgust, fear, happiness, neutral, sadness, surprise

Code Samples


import requests
from typing import Dict, Any, List


def analyze_faces(image_url: str, api_key: str) -> None:
    """Analyze faces in an image to detect age, gender, and emotions.
    
    Args:
        image_url: URL of the image to analyze.
        api_key: PixLab API key for authentication.
    """
    try:
        response = requests.get(
            'http://api.pixlab.io/facemotion',
            params={
                'img': image_url,
                'key': api_key,
            },
            timeout=10
        )
        response.raise_for_status()
        data = response.json()

        if data['status'] != 200:
            print(f"Error: {data.get('error', 'Unknown error')}")
            return

        faces: List[Dict[str, Any]] = data.get('faces', [])
        print(f"{len(faces)} faces were detected")

        for face in faces:
            rect = face.get('rectangle', {})
            print(
                f"Face coordinate: width: {rect.get('width')} "
                f"height: {rect.get('height')} "
                f"x: {rect.get('left')} "
                f"y: {rect.get('top')}"
            )

            for emotion in face.get('emotion', []):
                if emotion.get('score', 0) > 0.5:
                    print(
                        f"Emotion - {emotion.get('state')}: "
                        f"{emotion.get('score')}"
                    )

            print(f"Age ~: {face.get('age')}")
            print(f"Gender: {face.get('gender')}")

    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
    except ValueError as e:
        print(f"Failed to parse response: {e}")


if __name__ == "__main__":
    analyze_faces(
        image_url='http://www.scienceforums.com/uploads/1282315190/gallery_1625_35_9165.jpg',
        api_key='PixLab_API_Key'
    )
← Return to API Endpoint Listing