FACEDETECT API Endpoint

Version 2.197 (Release Notes ↗)

Description

Detect and output rectangle coordinates for human faces in images or video frames. Integrate with endpoints like crop, drawrectangles, and mogrify for advanced face manipulation. For facial shapes and deep analysis, use facelandmarks and facemotion. Output the rectangle coordinates for each detected human face in a given image or video frame. A plenty of useful endpoints can be mixed with facedetect such as crop for face extraction, drawrectangles for marking faces, mogrify for blurring and so forth.
If you need to extract the facial shapes besides the rectangle coordinates, refer to the docscan endpoint. For further deep facial analysis including age, gender and emotion pattern extraction, facemotion do perform such task.

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. Only JPEG, PNG & BMP format are allowed.
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.

Optional

Fields Type Description
count Boolean Return the total number of detected faces instead of their rectangle coordinates.

POST Request Body

If you plan to use POST 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

The FACEDETECT endpoint accepts and returns application/json.

This endpoint returns a JSON Object containing a faces array with rectangle coordinates and IDs for each detected face. Below are the response fields:

Fields Type Description
status Integer Status code 200 indicates success; any other code indicates failure.
faces Array JSON array of detected face coordinates (see below). Ignored if count parameter is set.
count Integer Total detected faces. Only returned if the count parameter is set.
error String Error message if status != 200.

Each detected face in the faces array contains the following fields:

Fields Type Description
face_id Integer Detected face ID.
left Integer Rectangle left coordinate: X.
top Integer Rectangle top coordinate: Y.
width Integer Rectangle width.
height Integer Rectangle height.

For further processing, pass these values to other endpoints like crop for face extraction, drawrectangles for marking, or mogrify for blurring.

Code Samples


import requests
import sys

def detect_and_crop_faces(image_url: str, api_key: str) -> None:
    """Detect faces in an image and crop each face using PixLab API."""
    
    # Detect faces
    detect_params = {
        'img': image_url,
        'key': api_key
    }
    
    try:
        detect_response = requests.get(
            'https://api.pixlab.io/facedetect',
            params=detect_params,
            timeout=10
        )
        detect_response.raise_for_status()
        faces_data = detect_response.json()
        
        if faces_data['status'] != 200:
            print(f"Error: {faces_data.get('error', 'Unknown error')}")
            sys.exit(1)
            
        total_faces = len(faces_data['faces'])
        print(f"{total_faces} face(s) were detected")
        
        # Crop each face
        for face in faces_data['faces']:
            crop_params = {
                'img': image_url,
                'key': api_key,
                'width': face['width'],
                'height': face['height'],
                'x': face['left'],
                'y': face['top']
            }
            
            try:
                crop_response = requests.get(
                    'https://api.pixlab.io/crop',
                    params=crop_params,
                    timeout=10
                )
                crop_response.raise_for_status()
                crop_data = crop_response.json()
                
                if crop_data['status'] != 200:
                    print(f"Error cropping face {face['face_id']}: {crop_data.get('error', 'Unknown error')}")
                else:
                    print(f"Face #{face['face_id']} location: {crop_data['link']}")
                    
            except requests.exceptions.RequestException as e:
                print(f"Error cropping face {face['face_id']}: {str(e)}")
                
    except requests.exceptions.RequestException as e:
        print(f"Error detecting faces: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    image_url = 'http://cf.broadsheet.ie/wp-content/uploads/2015/03/jeremy-clarkson_3090507b.jpg'
    api_key = 'My_PIXLAB_API_KEY'
    detect_and_crop_faces(image_url, api_key)
← Return to API Endpoint Listing