Skip to content

SACHIN-S-2004/Facial-Emotion-Recognition

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

17 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ˜Š Facial Emotion Recognition

๐Ÿง  CNN-Powered Emotion Classifier built with Flask & PyTorch

Python Flask PyTorch OpenCV Bootstrap


โœจ Overview

Facial Emotion Recognition is a sophisticated Flask web application that detects and classifies human emotions from facial expressions in real-time. Built with PyTorch CNNs and powered by advanced face detection algorithms, this application recognizes 7 distinct emotions with high accuracy across images, videos, GIFs, and live camera feeds.

The project seamlessly combines state-of-the-art deep learning with an intuitive, modern web interface featuring glassmorphism design patterns. Whether you're analyzing a static image or processing dynamic video content, our AI delivers instant, intelligent emotion predictions.

๐Ÿ“ฆ Key Capabilities:

  • โœ” Real-time emotion detection from live camera feeds
  • โœ” Image analysis (PNG, JPG, JPEG, BMP)
  • โœ” GIF frame processing & emotion tracking
  • โœ” Video file support (MP4, AVI, MOV, MKV, FLV, WEBM)
  • โœ” Confident predictions with top-3 emotion scores
  • โœ” Automatic face detection & extraction
  • โœ” Interactive web interface with instant feedback

All in milliseconds.


๐ŸŽฏ Demo Flow

Upload Image / GIF / Video / Stream from Live Camera
            โ†“
Extract Face(s) using Haar Cascade Classifier
            โ†“
Preprocess: Grayscale โ†’ Normalize โ†’ Resize (48ร—48)
            โ†“
Feed into PyTorch CNN Model
            โ†“
Predict Emotion + Confidence Score
            โ†“
Display Result with Top-3 Emotions & Emoji

๐Ÿ“ธ Screenshots

๐Ÿ’ป Default Interface

Interface

๐Ÿ˜ฎ Image Emotion Prediction (Surprise)

Image Prediction

๐ŸŽฌ Video Emotion Analysis

Demo Video

Click the image above to watch the full demo video


๐Ÿ”ฅ Features

๐ŸŽฅ Multiple Input Modes

  • Live Camera Stream โ€” Real-time emotion detection with continuous face tracking
  • Image Upload โ€” Analyze single photographs for dominant emotions
  • Video Processing โ€” Extract and analyze emotions across video frames
  • GIF Animation โ€” Track emotional changes frame-by-frame
  • All modes return predicted emotion + confidence score + top-3 alternatives

๐Ÿง  PyTorch CNN Model

  • Architecture: 4 Convolutional blocks + 2 Dense layers
  • Training Data: FER2013 & custom datasets (thousands of facial images)
  • Layer Stack:
    • Conv2D (32 filters) โ†’ BatchNorm โ†’ ReLU โ†’ MaxPooling โ†’ Dropout(0.25)
    • Conv2D (64 filters) โ†’ BatchNorm โ†’ ReLU โ†’ MaxPooling โ†’ Dropout(0.25)
    • Conv2D (128 filters) โ†’ BatchNorm โ†’ ReLU โ†’ MaxPooling โ†’ Dropout(0.3)
    • Conv2D (256 filters) โ†’ BatchNorm โ†’ ReLU โ†’ MaxPooling โ†’ Dropout(0.3)
    • Flatten โ†’ Dense(256) โ†’ BatchNorm โ†’ Dropout(0.5) โ†’ Dense(7) โ†’ Softmax
  • Output Classes: 7 emotions (Angry, Disgust, Fear, Happy, Neutral, Sad, Surprise)
  • Device Support: Automatic GPU/CPU detection (CUDA optimized)

๐ŸŽฏ Emotion Classification

  • Angry โ€” Detected through furrowed brows & tensed jaw
  • Disgust โ€” Nose wrinkle & lip curl patterns
  • Fear โ€” Wide eyes & raised eyebrows signatures
  • Happy โ€” Smile detection & crow's feet recognition
  • Neutral โ€” Resting face with minimal expression
  • Sad โ€” Downturned mouth & inner eyebrow raise
  • Surprise โ€” Maximum eye/mouth opening signals

๐Ÿ–ผ๏ธ Advanced Face Detection

  • Haar Cascade Classifier for robust face localization
  • Automatic face extraction & cropping
  • Multi-face support (processes first detected face)
  • Fallback to full image if no face detected
  • Works across diverse lighting conditions & angles

๐Ÿ“Š Intelligent Preprocessing

  • Grayscale conversion for model optimization
  • Dynamic resizing to 48ร—48 pixel standard
  • Normalization with mean=0.5, std=0.5
  • Automatic frame sampling for long videos (โ‰ค200 frames)
  • Memory-efficient batch processing

๐Ÿ’Ž UI/UX Excellence

  • Glassmorphism Design โ€” Modern frosted glass aesthetic
  • Gradient Animated Background โ€” Smooth color transitions
  • Real-time Progress Visualization โ€” Live confidence bars
  • Responsive Layout โ€” Works seamlessly on mobile & desktop
  • Intuitive Controls โ€” Drag-drop file upload, one-click camera
  • Emoji Feedback โ€” Visual emotion representation
  • Dark Theme โ€” Easy on the eyes, modern feel

โšก Backend Performance

  • Flask lightweight web server
  • Real-time frame streaming capabilities
  • Efficient video/GIF decoding with OpenCV
  • File upload handling (โ‰ค16MB limit)
  • Asynchronous processing pipeline
  • CORS-compatible API endpoints

๐Ÿง  How It Works (Step-by-Step)

Step 1 โ€” Extract & Detect Face

Raw Input (Image/Frame)
    โ†“
Convert to Grayscale
    โ†“
Apply Haar Cascade Classifier
    โ†“
Locate Face Region (x, y, w, h)
    โ†“
Extract Face ROI from Image

Step 2 โ€” Preprocess Image

Extracted Face Image
    โ†“
Convert to Grayscale (3-channel)
    โ†“
Resize to 48ร—48 pixels
    โ†“
Convert to PyTorch Tensor
    โ†“
Normalize: (pixel - 0.5) / 0.5
    โ†“
Add batch dimension (1, 3, 48, 48)

Step 3 โ€” CNN Forward Pass

Input (1, 3, 48, 48)
    โ†“
Conv2D(32) โ†’ BatchNorm โ†’ ReLU โ†’ MaxPool(2) โ†’ Dropout(0.25)
    โ†“
Conv2D(64) โ†’ BatchNorm โ†’ ReLU โ†’ MaxPool(2) โ†’ Dropout(0.25)
    โ†“
Conv2D(128) โ†’ BatchNorm โ†’ ReLU โ†’ MaxPool(2) โ†’ Dropout(0.3)
    โ†“
Conv2D(256) โ†’ BatchNorm โ†’ ReLU โ†’ MaxPool(2) โ†’ Dropout(0.3)
    โ†“
Flatten โ†’ Dense(256) โ†’ BatchNorm โ†’ Dropout(0.5)
    โ†“
Dense(7) โ†’ Softmax
    โ†“
Output Logits [7 classes]

Step 4 โ€” Emotion Recognition

Model Output: [angry_score, disgust_score, fear_score, ...]
    โ†“
Apply Softmax Normalization
    โ†“
argmax(predictions)  โ†’  Predicted Emotion
    โ†“
max(predictions)  โ†’  Confidence %
    โ†“
Sort & Extract Top-3 Results
    โ†“
Display with Emoji & Confidence Bar

๐Ÿ—๏ธ Tech Stack

Layer Technology
Backend Flask 2.3.2
Deep Learning PyTorch 2.0.1, TorchVision 0.15.2
Face Detection OpenCV 4.8.0 (Haar Cascade)
Image Processing Pillow (PIL) 10.0.0, NumPy 1.24.3
Frontend HTML5 + Bootstrap 5 + CSS3 + JavaScript
Styling Custom CSS (Glassmorphism Pattern)
Fonts Google Fonts (Poppins)
Icons Font Awesome 6.0
Deployment Werkzeug 2.3.6

๐Ÿ“‚ Project Structure

Facial-Emotion-Recognition/
โ”‚
โ”œโ”€โ”€ app.py                              # Main Flask application
โ”œโ”€โ”€ requirements.txt                    # Python dependencies
โ”‚
โ”œโ”€โ”€ model/
โ”‚   โ”œโ”€โ”€ best_model.pth                  # Trained PyTorch model
โ”‚   โ””โ”€โ”€ classes.json                    # Emotion class mappings
โ”‚
โ”œโ”€โ”€ notebooks/
โ”‚   โ””โ”€โ”€ Facial-Emotion-Recognition.ipynb # Jupyter training notebook
โ”‚
โ”œโ”€โ”€ scripts/
โ”‚   โ”œโ”€โ”€ generate_classes.py             # Utility to create classes.json
โ”‚   โ”œโ”€โ”€ learn.py                        # Model training & evaluation script
โ”‚   โ””โ”€โ”€ predict.py                      # Standalone prediction utility
โ”‚
โ”œโ”€โ”€ templates/
โ”‚   โ””โ”€โ”€ index.html                      # Web UI HTML template
โ”‚
โ”œโ”€โ”€ static/
โ”‚   โ”œโ”€โ”€ style.css                       # Glassmorphism styling
โ”‚   โ””โ”€โ”€ script.js                       # Frontend interactivity
โ”‚
โ”œโ”€โ”€ sampleScreenshots/
โ”‚   โ”œโ”€โ”€ Screenshot (18).png             # Default UI
โ”‚   โ””โ”€โ”€ Screenshot (19).png             # Emotion prediction result
โ”‚   โ””โ”€โ”€ videoThumbnail.png              # Demo video thumbnail
โ”‚
โ”œโ”€โ”€ sampleVideo.mp4                     # Demo video with multiple emotions
โ”‚
โ””โ”€โ”€ README.md                           # This file

โš™๏ธ Installation

1๏ธโƒฃ Clone Repository

git clone https://github.com/SACHIN-S-2004/Facial-Emotion-Recognition.git
cd Facial-Emotion-Recognition

2๏ธโƒฃ Create Virtual Environment (Recommended)

# Windows
python -m venv venv
venv\Scripts\activate

# macOS / Linux
python3 -m venv venv
source venv/bin/activate

3๏ธโƒฃ Install Dependencies

pip install -r requirements.txt

Dependencies:

  • torch==2.0.1
  • torchvision==0.15.2
  • numpy==1.24.3
  • Pillow==10.0.0
  • Flask==2.3.2
  • opencv-python==4.8.0.74
  • Werkzeug==2.3.6

4๏ธโƒฃ Run Application

python app.py

The server will start at: http://127.0.0.1:5000 ๐Ÿš€


5๏ธโƒฃ Open in Browser

http://localhost:5000

๐ŸŽ“ How to Use

๐Ÿ“ท Upload Image/GIF/Video

  1. Click "Drag & drop your file" or click to browse
  2. Select an image (PNG, JPG, JPEG, BMP), GIF, or video (MP4, AVI, MOV, etc.)
  3. Click "Initialize Analysis" button
  4. View predictions with confidence scores & top-3 emotions

๐ŸŽฅ Live Camera Detection

  1. Click "Live Camera" button in navigation bar
  2. Click "Start Camera" to begin real-time emotion detection
  3. Express different emotions to see instant classification
  4. Click "Stop Camera" to end session

๐Ÿ” Interpret Results

  • Top Emotion โ€” Most confident prediction with percentage
  • Confidence Bar โ€” Visual representation of certainty
  • Top-3 Alternatives โ€” Secondary emotion possibilities
  • Emoji Indicator โ€” Quick visual emotion representation

๐Ÿ“Š Model Performance

Metric Value
Input Size 48 ร— 48 pixels
Emotions 7 classes
Model Type Convolutional Neural Network (CNN)
Framework PyTorch
Optimization Adam Optimizer
Loss Function CrossEntropyLoss
Activation ReLU + Softmax
GPU Support CUDA-enabled
Inference Time ~50-100ms per frame

๐ŸŽฏ Supported Emotions

Emotion Emoji Characteristics
Angry ๐Ÿ˜  Furrowed brows, tensed jaw
Disgust ๐Ÿคข Nose wrinkle, lip curl
Fear ๐Ÿ˜จ Wide eyes, raised eyebrows
Happy ๐Ÿ˜Š Smile, crow's feet
Neutral ๐Ÿ˜ Minimal expression
Sad ๐Ÿ˜ข Downturned mouth
Surprise ๐Ÿ˜ฎ Maximum eye opening

๐ŸŽจ UI Features

๐ŸŒŸ Glassmorphism Design

Modern aesthetic with semi-transparent, frosted glass effect cards and smooth animations.

๐ŸŽฌ Real-time Visualization

Live emotion detection in camera modal with split-screen layout showing video feed and results simultaneously.

๐Ÿ“Š Confidence Visualization

Animated progress bars showing emotion confidence percentages with gradient styling.

๐ŸŽฏ Responsive Layout

Adapts seamlessly to different screen sizes (mobile, tablet, desktop) using Bootstrap grid system.

๐ŸŽจ Color-coded Results

Visual distinction between emotions using emoji and color gradients for intuitive understanding.


๐Ÿš€ Advanced Features

Video Frame Sampling

  • Automatically samples frames from long videos to optimize processing
  • Maximum 200 frames processed per video (configurable)
  • Maintains emotion tracking across temporal sequences

Multi-face Handling

  • Detects multiple faces in a single frame
  • Processes primary face for emotion classification
  • Fallback mechanisms for edge cases

Efficient Preprocessing

  • Grayscale conversion reduces computation
  • Standardized 48ร—48 resolution for consistency
  • Normalization ensures model stability

Real-time Streaming

  • Live camera feed with millisecond latency
  • Continuous face detection & emotion prediction
  • Smooth UI updates with minimal lag

๐Ÿ”ง Configuration

Modify Model Parameters

Edit app.py to adjust:

MAX_FRAMES = 200              # Max frames from video to process
MAX_CONTENT_LENGTH = 16MB     # Max file upload size
ALLOWED_EXTENSIONS = {...}   # Supported file types

๐Ÿ“š API Endpoints

POST /predict

Accepts image upload and returns emotion prediction

Request:

{
  "file": <image_file>
}

Response:

{
  "emotion": "happy",
  "confidence": 0.95,
  "top_3": [
    {"emotion": "happy", "score": 0.95},
    {"emotion": "surprise", "score": 0.03},
    {"emotion": "neutral", "score": 0.02}
  ]
}

๐ŸŽ“ Learning Outcomes

This project demonstrates:

  • โœ” Deep Learning โ€” CNN architecture design & training
  • โœ” Computer Vision โ€” Face detection & image preprocessing
  • โœ” PyTorch โ€” Model building, training, and inference
  • โœ” Flask Development โ€” Backend API creation & deployment
  • โœ” Frontend Integration โ€” Interactive web UI with real-time updates
  • โœ” Video Processing โ€” GIF & video frame extraction
  • โœ” Model Optimization โ€” GPU acceleration & efficient inference
  • โœ” Full-Stack Development โ€” End-to-end application architecture

๐Ÿ› Troubleshooting

No faces detected

  • Ensure good lighting conditions
  • Face should occupy ~30-40% of image frame
  • Try uploading a clearer portrait

Low confidence predictions

  • Model works best with frontal face views
  • Avoid extreme angles or side profiles
  • Ensure facial features are clearly visible

Slow inference

  • CPU processing is slower than GPU
  • Install CUDA for GPU acceleration
  • Reduce video frame count or resolution

Camera not working

  • Grant browser camera permissions
  • Check if another app is using the camera
  • Try a different browser

๐Ÿ“ Model Training

To retrain the model on custom dataset:

python scripts/learn.py

Refer to notebooks/Facial-Emotion-Recognition.ipynb for detailed training notebook.


๐Ÿค Contributing

Contributions are welcome! Feel free to:

  • Report bugs or issues
  • Suggest improvements
  • Create pull requests
  • Share feedback

โญ If you like this project

Give it a star โ€” it helps a lot! ๐ŸŒŸ

About

Real-time facial emotion recognition system built with PyTorch CNN and Flask. Detects 7 emotions from live camera feeds, images, videos, and GIFs with high accuracy using advanced face detection.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors