# PROJECT CHALLENGE: Real-Time Emotion Detector
#
# Build a system that:
# 1. Captures live video from webcam
# 2. Detects faces in each frame (Module 8)
# 3. Crops each face region
# 4. Classifies the emotion using a pretrained CNN
# 5. Displays the emotion label and confidence on screen
#
# Approach sketch:
import cv2
import torch
import torchvision.transforms as transforms
from torchvision.models import resnet18, ResNet18_Weights
# Step 1: Set up face detector
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
# Step 2: Load emotion classifier
# Option A: Use FER+ dataset (7 emotions: angry, disgust, fear, happy, sad, surprise, neutral)
# Option B: Use DeepFace library (pip install deepface) for quick results
EMOTIONS = ["angry", "disgust", "fear", "happy", "neutral", "sad", "surprise"]
# Load a model trained on FER dataset (or use deepface)
model = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1)
model.fc = torch.nn.Linear(model.fc.in_features, len(EMOTIONS))
# model.load_state_dict(torch.load("emotion_model.pth"))
model.eval()
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((48, 48)),
transforms.Grayscale(3), # Convert to 3-channel grayscale
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
])
# Step 3: Capture and process
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5, minSize=(40,40))
for (x, y, w, h) in faces:
face_crop = frame[y:y+h, x:x+w]
tensor = transform(face_crop).unsqueeze(0)
with torch.no_grad():
output = model(tensor)
probs = torch.softmax(output[0], dim=0)
idx = probs.argmax().item()
emotion = EMOTIONS[idx]
confidence = probs[idx].item()
cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)
label = f"{emotion}: {confidence:.0%}"
cv2.putText(frame, label, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,255,0), 2)
cv2.imshow("Emotion Detector", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
print("Challenge: train or find a pretrained FER model and plug it in!")