DeepFace

0.0.99 · active · verified Sun Apr 12

DeepFace is an open-source Python library for lightweight face recognition and facial attribute analysis (age, gender, emotion, and race). It acts as a hybrid framework, wrapping 11 state-of-the-art models into a single, easy-to-use interface. The library is actively maintained with frequent releases, often on a weekly or bi-weekly basis, and supports Python 3.7+.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core functionalities of DeepFace: face verification, facial attribute analysis (age, gender, emotion, race), and generating face embeddings. It uses dummy image files for immediate execution, but in a real application, you would provide paths to actual face images. Note that DeepFace will automatically download necessary deep learning models on its first execution, which requires an active internet connection and may take some time.

import os
import cv2
import numpy as np
from deepface import DeepFace

# Create dummy image files for demonstration
# In a real scenario, these would be actual image paths
img1_path = "img1.jpg"
img2_path = "img2.jpg"
person_img_path = "person.jpg"

# Generate dummy images (replace with actual image files for real usage)
if not os.path.exists(img1_path):
    cv2.imwrite(img1_path, np.zeros((224, 224, 3), dtype=np.uint8) + 100)
if not os.path.exists(img2_path):
    cv2.imwrite(img2_path, np.zeros((224, 224, 3), dtype=np.uint8) + 150)
if not os.path.exists(person_img_path):
    cv2.imwrite(person_img_path, np.zeros((224, 224, 3), dtype=np.uint8) + 200)

try:
    # Verify two faces
    result_verify = DeepFace.verify(img1_path, img2_path)
    print("Face Verification Result:", result_verify)

    # Analyze facial attributes
    analysis_result = DeepFace.analyze(person_img_path, actions=['age', 'gender', 'emotion', 'race'])
    print("\nFacial Analysis Result:", analysis_result)

    # Generate a face embedding (representation)
    embedding = DeepFace.represent(img1_path)
    print("\nFace Embedding (first 5 elements of first face):", embedding[0]['embedding'][:5])

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure you have valid image files at the specified paths.")
    print("Also, DeepFace downloads models on first run, requiring an internet connection.")

# Clean up dummy images (optional)
# os.remove(img1_path)
# os.remove(img2_path)
# os.remove(person_img_path)

view raw JSON →