Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Beginner ⏱ 30 min

😲 Build a Face Emotion Detector with OpenCV and DeepFace

🎯 What You'll Build

A real-time webcam app that detects faces and labels their emotions (happy, sad, angry, surprised, neutral) live on screen.

📋 What You'll Need

1

Analyse a single image

DeepFace wraps several pre-trained models — one function call returns emotion, age, gender, and race.

from deepface import DeepFace

result = DeepFace.analyze(
    img_path="photo.jpg",
    actions=["emotion"],
    enforce_detection=False
)

print("Dominant emotion:", result[0]["dominant_emotion"])
print("All scores:", result[0]["emotion"])
Dominant emotion: happy
All scores: {'angry': 0.1, 'disgust': 0.0, 'fear': 0.2, 'happy': 94.3, 'sad': 0.8, 'surprise': 2.1, 'neutral': 2.5}
2

Real-time webcam detection

Capture frames with OpenCV, analyse each one, and draw labels.

import cv2
from deepface import DeepFace
import threading

cap = cv2.VideoCapture(0)
emotion_label = "Detecting..."

def analyse(frame):
    global emotion_label
    try:
        result = DeepFace.analyze(frame, actions=["emotion"], enforce_detection=False)
        emotion_label = result[0]["dominant_emotion"].capitalize()
    except:
        emotion_label = "No face"

EMOJI = {"Happy":"😊","Sad":"😢","Angry":"😠","Surprise":"😲","Fear":"😨","Disgust":"🤢","Neutral":"😐"}

print("Press Q to quit")
while True:
    ret, frame = cap.read()
    if not ret:
        break

    # Run analysis in background thread every N frames
    if cap.get(cv2.CAP_PROP_POS_FRAMES) % 15 == 0:
        threading.Thread(target=analyse, args=(frame.copy(),), daemon=True).start()

    label = f"{EMOJI.get(emotion_label, '')} {emotion_label}"
    cv2.putText(frame, label, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2)
    cv2.imshow("Emotion Detector", frame)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()
💡 Tip: Add face bounding boxes with DeepFace.extract_faces() to draw rectangles around each detected person in group photos.

🎉 You Did It!

Your emotion detector runs in real time with no model training. DeepFace uses pre-trained weights — the hard work is done for you.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.