This is a real-time face liveness detection demo using:
- OpenCV DNN Face Detector (Caffe SSD)
- Keras/TensorFlow liveness classifier
imutilsthreaded webcam capture
The script opens your webcam, detects faces, and classifies them as real or fake.
- Python 3.8–3.11
- Webcam
- Python packages:
opencv-pythonimutilstensorflow(includes Keras)numpy
Install dependencies:
# Create and activate a virtual environment (recommended)
python -m venv .venv
# Windows: .venv\Scripts\activate
# macOS/Linux:
source .venv/bin/activate
pip install --upgrade pip
pip install opencv-python imutils tensorflow numpy.
├── liveness_demo.py # The demo script
├── liveness.model # Pre-trained Keras model
├── le.pickle # LabelEncoder pickle file
└── face_detector/ # OpenCV Caffe SSD face detector
├── deploy.prototxt
└── res10_300x300_ssd_iter_140000.caffemodel
Download the ResNet-10 SSD face detector model files (deploy.prototxt and res10_300x300_ssd_iter_140000.caffemodel) and place them in the face_detector/ directory.
python liveness_demo.py --model liveness.model --le le.pickle --detector face_detector --confidence 0.5Arguments:
--model: Path to the trained Keras model--le: Path to the label encoder pickle file--detector: Path to face detector folder--confidence: Minimum probability to filter weak detections (default: 0.5)
Controls:
- Press
qto quit
A window titled "Frame" will display your webcam feed. Detected faces will be highlighted with a red bounding box and labeled with the prediction:
real: 0.9876
or
fake: 0.8431
liveness.modelandle.picklemust match the preprocessing in the script:- Face resized to 32×32
- Normalized to
[0, 1]
- If your model uses different input sizes or preprocessing, update:
face = cv2.resize(face, (32, 32)) face = face.astype("float") / 255.0
- Black window / No camera: Check webcam connection or change
src=0tosrc=1 - Missing files: Ensure
deploy.prototxtand.caffemodelare inface_detector/ - Shape mismatch: Adjust preprocessing to match model training
- Label index error: Ensure label encoder matches model’s output classes
This script is for educational purposes only and should not be used as the sole factor in real-world authentication or identity verification.
python -m venv .venv
source .venv/bin/activate
pip install opencv-python imutils tensorflow numpy
mkdir face_detector
# Place deploy.prototxt and res10_300x300_ssd_iter_140000.caffemodel in face_detector/
python liveness_demo.py --model liveness.model --le le.pickle --detector face_detector