RetinaFace Deep Face Detection

0.0.17 · active · verified Thu Apr 16

RetinaFace is a deep learning-based, cutting-edge facial detector for Python, providing high-precision face localization and facial landmarks. It's built on a TensorFlow re-implementation of the original RetinaFace model from the InsightFace project. The library simplifies the underlying C dependencies and handles pre-trained weight downloads automatically, making it pip-compatible and easy to use. The current version is 0.0.17, with a moderately active release cadence addressing compatibility and performance improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import `RetinaFace` and use its `detect_faces` function to find faces and facial landmarks in an image. It includes a placeholder to create a dummy image if one isn't present, making the code immediately runnable. The output includes confidence scores, bounding box coordinates (`facial_area`), and five key facial landmarks (eyes, nose, mouth corners).

import cv2
import os
from retinaface import RetinaFace

# Create a dummy image for demonstration if it doesn't exist
image_path = "test_image.jpg"
if not os.path.exists(image_path):
    # Create a blank white image
    dummy_image = 255 * (1 + 0 * range(100)).reshape(100, 100, 1) # White image
    dummy_image = cv2.cvtColor(dummy_image, cv2.COLOR_GRAY2BGR)
    cv2.imwrite(image_path, dummy_image)
    print(f"Created a dummy image at {image_path}")

try:
    # Detect faces in an image
    # The detect_faces function can accept an image path or a NumPy array.
    faces = RetinaFace.detect_faces(image_path)

    if isinstance(faces, dict):
        for face_name, face_data in faces.items():
            print(f"--- {face_name} ---")
            print(f"  Score: {face_data['score']}")
            print(f"  Facial Area: {face_data['facial_area']}")
            print(f"  Landmarks: {face_data['landmarks']}")
    elif faces is None:
        print(f"No faces detected in {image_path}")
    else:
        print("Unexpected output format from RetinaFace.detect_faces")

    # Optional: Draw detections on the image and display (requires opencv-python-headless or opencv-python)
    # img = cv2.imread(image_path)
    # if img is not None:
    #     result_img = RetinaFace.draw_landmarks(img, faces)
    #     cv2.imshow("Detected Faces", result_img)
    #     cv2.waitKey(0)
    #     cv2.destroyAllWindows()

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →