A real-time driver drowsiness detection system that monitors eye state through a webcam and triggers an audio alarm when prolonged eye closure is detected.
- Captures a live webcam feed using OpenCV
- Detects the face and eyes using Haar Cascade classifiers
- Classifies each eye as Open or Closed using a pre-trained CNN
- Maintains a running score — +1 each frame both eyes are closed, −1 otherwise (floor 0)
- When score exceeds 15, the system:
- Plays
alarm.wavvia pygame - Draws a pulsing red border on the video feed
- Saves a snapshot of the drowsy frame as
image.jpg
- Plays
Press q to quit the detection window.
drowsiness-detection/
├── drowsiness detection.py # Real-time detection pipeline
├── model.py # CNN training script
├── alarm.wav # Alert sound
├── image.jpg # Snapshot saved on drowsiness event
├── models/
│ └── cnnCat2.h5 # Pre-trained CNN weights
└── haar cascade files/
├── haarcascade_frontalface_alt.xml
├── haarcascade_lefteye_2splits.xml
└── haarcascade_righteye_2splits.xml
- Python 3.12+
- uv (recommended package manager)
- A webcam
# Clone the repository
git clone <repo-url>
cd drowsiness-detection
# Install dependencies
uv syncuv run python "drowsiness detection.py"The detection window will open. Press q to quit.
Note: The script uses
cv2.VideoCapture(1)by default. If your webcam is not detected, change the index to0indrowsiness detection.pyline 16.
The pre-trained model (models/cnnCat2.h5) is included — retraining is only needed if you want to use a custom dataset.
Prepare your dataset with this structure:
data/
├── train/
│ ├── Open/
│ └── Closed/
└── valid/
├── Open/
└── Closed/
Then run:
uv run python model.pyThe retrained model will be saved to models/cnnCat2.h5.
Compatibility note:
drowsiness detection.pyusestf_keras(TF 2.x standalone package), whilemodel.pyuses the olderkerasAPI. If you retrain, updatemodel.pyimports totf_kerasto avoid conflicts.
Input: 24×24 grayscale eye region of interest (ROI)
Conv2D(32) + MaxPool → Conv2D(32) + MaxPool → Conv2D(64) + MaxPool
→ Dropout(0.25) → Flatten → Dense(128) → Dropout(0.5) → Dense(2, softmax)
Output: 0 = Closed, 1 = Open
| Package | Purpose |
|---|---|
opencv-python |
Webcam capture, Haar Cascade detection, frame rendering |
tf-keras |
Loading and running the pre-trained CNN |
tensorflow |
Backend for tf-keras |
numpy |
Image array manipulation |
pygame |
Audio alarm playback |