A Python project that detects human faces from a webcam and predicts facial emotions in real time using OpenCV and a CNN trained with TensorFlow/Keras.
- Detects faces from live webcam video using Haar Cascade.
- Preprocesses face ROI with grayscale conversion, resizing, and normalization.
- Trains a CNN on FER2013 or a similar folder-based emotion dataset.
- Classifies seven emotions: Angry, Disgust, Fear, Happy, Sad, Surprise, Neutral.
- Draws a bounding box and emotion label on the webcam feed.
- Saves the trained model, class labels, and accuracy/loss plots.
- Optional CSV emotion logging during real-time detection.
.
├── dataset/
│ └── README.md
├── logs/
│ └── .gitkeep
├── model/
│ └── .gitkeep
├── plots/
│ └── .gitkeep
├── main.py
├── train.py
├── utils.py
├── requirements.txt
└── README.md
Create and activate a virtual environment:
py -3.11 -m venv .venv
.\.venv\Scripts\activateInstall dependencies:
pip install -r requirements.txtFER2013 is commonly distributed as fer2013.csv with these columns:
emotion: numeric class idpixels: 48x48 grayscale image pixels as a space-separated stringUsage:Training,PublicTest, orPrivateTest
Place it here:
dataset/fer2013.csv
The FER2013 label mapping used by this project is:
0 Angry
1 Disgust
2 Fear
3 Happy
4 Sad
5 Surprise
6 Neutral
You can also use a folder dataset:
dataset/
├── train/
│ ├── Angry/
│ ├── Happy/
│ └── ...
├── validation/
│ ├── Angry/
│ ├── Happy/
│ └── ...
└── test/
├── Angry/
├── Happy/
└── ...
Train with FER2013 CSV:
python train.py --dataset dataset/fer2013.csv --epochs 35 --batch-size 64Train with a folder dataset:
python train.py --dataset dataset --epochs 35 --batch-size 64Training creates:
model/emotion_cnn.h5model/labels.jsonplots/training_curves.png
The terminal prints test accuracy and loss when a test split is available.
After training:
python main.py --model model/emotion_cnn.h5Press q or Esc to close the webcam window.
Optional logging:
python main.py --save-logs --log-file logs/emotion_log.csvpython train.py --help
python main.py --helpExamples:
python main.py --camera 1
python main.py --min-confidence 0.60
python train.py --epochs 50 --learning-rate 0.0005- The model file is not included because it must be trained from the dataset.
- Accuracy depends on the dataset quality, lighting, camera angle, and class balance.
- For better results, train for more epochs, use balanced data, and keep the face well lit and centered.
- TensorFlow wheels are tied to Python versions. If
pip install tensorflowfails on a very new Python release, install a TensorFlow-supported Python version and recreate the virtual environment with that interpreter.