API Endpoint Access URL
https://api.pixlab.io/facemotion
Get Your API Key & Try FACEMOTION Now ↗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'
)
// Target image: Feel free to change to whatever image holding as many human faces as you want
const img = 'http://www.scienceforums.com/uploads/1282315190/gallery_1625_35_9165.jpg';
fetch(`http://api.pixlab.io/facemotion?img=${encodeURIComponent(img)}&key=PixLab_API_Key`)
.then(response => response.json())
.then(reply => {
if (reply.status !== 200) {
console.log(reply.error);
return;
}
const total = reply.faces.length; // Total detected faces
console.log(`${total} faces were detected`);
// Extract each face now
reply.faces.forEach(face => {
const cord = face.rectangle;
console.log(`Face coordinate: width: ${cord.width} height: ${cord.height} x: ${cord.left} y: ${cord.top}`);
// Guess emotion
face.emotion.forEach(emotion => {
if (emotion.score > 0.5) {
console.log(`Emotion - ${emotion.state}: ${emotion.score}`);
}
});
// Grab the age and gender
console.log(`Age ~: ${face.age}`);
console.log(`Gender: ${face.gender}`);
});
})
.catch(error => console.error('Error:', error));
php
<?php
// Detect all human faces present in a given image and try to guess their age, gender and emotion state via their facial shapes
// Target image: Feel free to change to whatever image holding as many human faces as you want
$img = 'http://www.scienceforums.com/uploads/1282315190/gallery_1625_35_9165.jpg';
$apiKey = 'PixLab_API_Key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.pixlab.io/facemotion?img=' . urlencode($img) . '&key=' . urlencode($apiKey));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$reply = json_decode($response, true);
if ($reply['status'] != 200) {
die($reply['error']);
}
$total = count($reply['faces']); // Total detected faces
echo $total . " faces were detected\n";
// Extract each face now
foreach ($reply['faces'] as $face) {
$cord = $face['rectangle'];
echo 'Face coordinate: width: ' . $cord['width'] . ' height: ' . $cord['height'] . ' x: ' . $cord['left'] . ' y: ' . $cord['top'] . "\n";
// Guess emotion
foreach ($face['emotion'] as $emotion) {
if ($emotion['score'] > 0.5) {
echo "Emotion - " . $emotion['state'] . ': ' . $emotion['score'] . "\n";
}
}
// Grab the age and gender
echo "Age ~: " . $face['age'] . "\n";
echo "Gender: " . $face['gender'] . "\n";
}
require 'net/http'
require 'uri'
require 'json'
# Target image: Feel free to change to whatever image holding as many human faces as you want
img = 'http://www.scienceforums.com/uploads/1282315190/gallery_1625_35_9165.jpg'
uri = URI.parse('http://api.pixlab.io/facemotion')
params = {
'img' => img,
'key' => 'PixLab_API_Key'
}
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)
reply = JSON.parse(response.body)
if reply['status'] != 200
puts reply['error']
exit
end
total = reply['faces'].length # Total detected faces
puts "#{total} faces were detected"
# Extract each face now
reply['faces'].each do |face|
cord = face['rectangle']
puts "Face coordinate: width: #{cord['width']} height: #{cord['height']} x: #{cord['left']} y: #{cord['top']}"
# Guess emotion
face['emotion'].each do |emotion|
if emotion['score'] > 0.5
puts "Emotion - #{emotion['state']}: #{emotion['score']}"
end
end
# Grab the age and gender
puts "Age ~: #{face['age']}"
puts "Gender: #{face['gender']}"
end
Similar API Endpoints
bg-remove, nsfw, sfw, ocr, facedetect, docscan, crop, mogrify, facelookup ↗, faceverify ↗, screencapture