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.
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
Click the image above to watch the full demo video
- 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
- 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)
- 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
- 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
- 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
- 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
- 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
Raw Input (Image/Frame)
โ
Convert to Grayscale
โ
Apply Haar Cascade Classifier
โ
Locate Face Region (x, y, w, h)
โ
Extract Face ROI from 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)
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]
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
| 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 |
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
git clone https://github.com/SACHIN-S-2004/Facial-Emotion-Recognition.git
cd Facial-Emotion-Recognition# Windows
python -m venv venv
venv\Scripts\activate
# macOS / Linux
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtDependencies:
- 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
python app.pyThe server will start at: http://127.0.0.1:5000 ๐
http://localhost:5000
- Click "Drag & drop your file" or click to browse
- Select an image (PNG, JPG, JPEG, BMP), GIF, or video (MP4, AVI, MOV, etc.)
- Click "Initialize Analysis" button
- View predictions with confidence scores & top-3 emotions
- Click "Live Camera" button in navigation bar
- Click "Start Camera" to begin real-time emotion detection
- Express different emotions to see instant classification
- Click "Stop Camera" to end session
- 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
| 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 |
| 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 |
Modern aesthetic with semi-transparent, frosted glass effect cards and smooth animations.
Live emotion detection in camera modal with split-screen layout showing video feed and results simultaneously.
Animated progress bars showing emotion confidence percentages with gradient styling.
Adapts seamlessly to different screen sizes (mobile, tablet, desktop) using Bootstrap grid system.
Visual distinction between emotions using emoji and color gradients for intuitive understanding.
- Automatically samples frames from long videos to optimize processing
- Maximum 200 frames processed per video (configurable)
- Maintains emotion tracking across temporal sequences
- Detects multiple faces in a single frame
- Processes primary face for emotion classification
- Fallback mechanisms for edge cases
- Grayscale conversion reduces computation
- Standardized 48ร48 resolution for consistency
- Normalization ensures model stability
- Live camera feed with millisecond latency
- Continuous face detection & emotion prediction
- Smooth UI updates with minimal lag
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 typesAccepts 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}
]
}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
- Ensure good lighting conditions
- Face should occupy ~30-40% of image frame
- Try uploading a clearer portrait
- Model works best with frontal face views
- Avoid extreme angles or side profiles
- Ensure facial features are clearly visible
- CPU processing is slower than GPU
- Install CUDA for GPU acceleration
- Reduce video frame count or resolution
- Grant browser camera permissions
- Check if another app is using the camera
- Try a different browser
To retrain the model on custom dataset:
python scripts/learn.pyRefer to notebooks/Facial-Emotion-Recognition.ipynb for detailed training notebook.
Contributions are welcome! Feel free to:
- Report bugs or issues
- Suggest improvements
- Create pull requests
- Share feedback
Give it a star โ it helps a lot! ๐
.png)
.png)