Skip to content

DriveSafe AI is a real-time driver drowsiness detection system that uses Python and OpenCV to monitor eye movements through a webcam. The system detects fatigue based on eye closure patterns and provides instant audio and visual alerts using a web-based interface.

Notifications You must be signed in to change notification settings

ajitharunai/AI-Based-Driver-Drowsiness-Detection

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

4 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿš— DriveSafe AI - Driver Drowsiness Detection System

DriveSafe AI Python Flask OpenCV License

A real-time AI-powered system to detect driver drowsiness and prevent accidents

Features โ€ข Installation โ€ข Usage โ€ข Demo โ€ข Technology


๐Ÿ“‹ Overview

DriveSafe AI is an intelligent driver drowsiness detection system that uses computer vision and machine learning to monitor drivers in real-time. By analyzing facial features, eye movements, and yawning patterns, the system can detect early signs of fatigue and alert drivers before accidents occur.

๐ŸŽฏ Problem Statement

  • 1.35 million people die in road accidents globally each year
  • 20% of fatal crashes are caused by drowsy driving
  • Drivers are often unaware of early drowsiness signs

๐Ÿ’ก Solution

Real-time monitoring using:

  • Eye Aspect Ratio (EAR) to detect eye closure
  • Mouth Aspect Ratio (MAR) to detect yawning
  • MediaPipe Face Mesh for precise facial landmark detection
  • Instant alerts with audio and visual warnings

๐Ÿ‘จโ€๐Ÿ’ป Developer

Ajith Kumar Murugan

Ajith Kumar Murugan

AI Research Engineer/Scientist

LinkedIn GitHub

Passionate about creating AI solutions that make a real-world impact


โœจ Features

Core Functionality

  • โœ… Real-time face detection using MediaPipe Face Mesh (468 landmarks)
  • โœ… Eye tracking with EAR calculation to detect prolonged eye closure
  • โœ… Blink detection to identify excessive blinking patterns
  • โœ… Yawn detection using mouth aspect ratio analysis
  • โœ… Drowsiness scoring algorithm (0-100 scale)
  • โœ… Multi-level alerts (Normal/Warning/Alert)

Dashboard Features

  • ๐Ÿ“น Live video feed with facial landmark overlay
  • ๐Ÿ“Š Real-time statistics (blink count, yawn count, EAR/MAR values)
  • ๐Ÿ“ˆ Interactive Chart.js graph showing drowsiness timeline
  • ๐ŸŽจ Premium dark mode UI with glassmorphism effects
  • โšก Responsive design for all screen sizes
  • ๐Ÿ”Š Audio alerts when drowsiness detected
  • ๐Ÿšจ Visual alerts with red screen flash

Technical Highlights

  • โšก 15+ FPS real-time processing
  • ๐Ÿ’ป Offline capability - no cloud dependency
  • ๐ŸŽฏ High accuracy facial landmark detection
  • ๐Ÿ”„ Auto pause/resume when tab hidden
  • ๐Ÿ“ฑ Responsive across devices

๐Ÿ› ๏ธ Technology Stack

Backend

  • Python 3.8+ - Core language
  • Flask - Web framework
  • OpenCV - Computer vision
  • MediaPipe - Face mesh detection
  • NumPy - Numerical computing
  • SciPy - Distance calculations

Frontend

  • HTML5 - Structure
  • CSS3 - Premium dark mode styling
  • JavaScript (ES6+) - Interactivity
  • Chart.js - Real-time visualization

๐Ÿ“ฆ Installation

Prerequisites

  • Python 3.8 or higher
  • Webcam (built-in or external)
  • Modern web browser (Chrome, Firefox, Edge)
  • Windows/Mac/Linux operating system

Step 1: Clone or Download

cd "AI-Based Driver Drowsiness Detection"

Step 2: Create Virtual Environment

Windows:

python -m venv venv
venv\Scripts\activate

Mac/Linux:

python3 -m venv venv
source venv/bin/activate

Step 3: Install Dependencies

pip install -r requirements.txt

This will install:

  • Flask & Flask-CORS
  • OpenCV
  • MediaPipe
  • NumPy
  • SciPy

Step 4: Verify Installation

python -c "import cv2, mediapipe; print('โœ… All dependencies installed successfully!')"

๐Ÿš€ Usage

Start the Application

  1. Navigate to backend directory:

    cd backend
  2. Run the Flask server:

    python app.py
  3. Open your browser:

    • Navigate to: http://127.0.0.1:5000
    • Allow webcam permissions when prompted
  4. Start monitoring:

    • The dashboard will load automatically
    • Live video feed will appear on the left
    • Statistics and graph on the right

Stopping the Application

  • Press Ctrl+C in the terminal to stop the server
  • The camera will be released automatically

๐ŸŽฌ Demo Flow

Perfect for hackathon presentations:

1๏ธโƒฃ Opening (30 seconds)

  • Show the professional dashboard
  • Explain the problem (drowsy driving statistics)
  • Introduce DriveSafe AI

2๏ธโƒฃ Normal Operation (20 seconds)

  • Demonstrate live webcam feed with face mesh
  • Point out real-time EAR and MAR values
  • Show the drowsiness graph updating

3๏ธโƒฃ Drowsiness Detection (30 seconds)

  • Close eyes for 3+ seconds
  • Alert triggers! ๐Ÿšจ
    • Audio beep plays
    • Screen flashes red
    • Status changes to "ALERT"
    • Graph spikes above threshold
  • Emphasize instant response time

4๏ธโƒฃ Technical Explanation (20 seconds)

  • Explain EAR algorithm briefly
  • Mention MediaPipe's 468 facial landmarks
  • Highlight offline capability

5๏ธโƒฃ Impact Statement (20 seconds)

  • "This system can save lives"
  • Mention real-world applications
  • Discuss future enhancements

Total Demo: ~2 minutes โฑ๏ธ


๐Ÿ“Š How It Works

Eye Aspect Ratio (EAR)

EAR = (||p2-p6|| + ||p3-p5||) / (2 * ||p1-p4||)
  • EAR > 0.25 โ†’ Eyes open
  • EAR < 0.25 โ†’ Eyes closed
  • Prolonged closure (>2 seconds) โ†’ Drowsiness detected

Mouth Aspect Ratio (MAR)

MAR = (vertical distance) / (horizontal distance)
  • MAR > 0.6 โ†’ Yawning detected
  • Frequent yawning indicates fatigue

Drowsiness Score Calculation

score = 0
if eye_closed_duration > 2_seconds: score += 40
if blink_rate_excessive: score += 20
if yawn_detected: score += 30
if no_face_detected: score += 10

# Final score: 0-100

Alert Levels:

  • ๐ŸŸข 0-30: Normal
  • ๐ŸŸก 31-69: Warning
  • ๐Ÿ”ด 70-100: Alert (triggers audio/visual alarm)

๐ŸŽจ Dashboard Features

Video Panel

  • Live webcam stream with face mesh overlay
  • Real-time EAR and MAR display
  • FPS counter
  • Status badge (Normal/Warning/Alert)

Statistics Panel

  • Current Status: Visual indicator with emoji
  • Drowsiness Meter: Progress bar (0-100%)
  • Live Metrics:
    • Eye blink count ๐Ÿ‘๏ธ
    • Yawn count ๐Ÿฅฑ
    • EAR value โšก
    • MAR value ๐Ÿ˜ฎ
  • Alert History: Total alerts and last alert time

Timeline Chart

  • Rolling 60-second drowsiness graph
  • Color-coded line (green/yellow/red)
  • Alert threshold line at 70%
  • Interactive tooltips

๐Ÿ”ง Configuration

Adjusting Sensitivity

Edit backend/utils/eye_tracker.py:

self.EAR_THRESHOLD = 0.25  # Lower = more sensitive
self.CONSECUTIVE_FRAMES = 20  # Higher = less sensitive

Edit backend/utils/yawn_detector.py:

self.MAR_THRESHOLD = 0.6  # Lower = more sensitive
self.CONSECUTIVE_FRAMES = 15  # Higher = less sensitive

Alert Cooldown

Edit backend/utils/alert_manager.py:

self.alert_cooldown = 5  # seconds between alerts

๐Ÿงช Testing

Test Normal State

  1. Start the application
  2. Look at the camera normally
  3. Verify status shows "Normal" (green)
  4. Check EAR value is around 0.25-0.30

Test Drowsiness Detection

  1. Close your eyes for 3+ seconds
  2. Verify:
    • โœ… Status changes to "Alert" (red)
    • โœ… Audio beep plays
    • โœ… Screen flashes red
    • โœ… Drowsiness score jumps to 70+
    • โœ… Graph shows spike

Test Yawn Detection

  1. Simulate a yawn (wide mouth opening)
  2. Verify:
    • โœ… MAR value increases above 0.6
    • โœ… Yawn count increments
    • โœ… Drowsiness score increases

๐Ÿ“ Project Structure

AI-Based Driver Drowsiness Detection/
โ”œโ”€โ”€ backend/
โ”‚   โ”œโ”€โ”€ app.py                    # Flask application
โ”‚   โ”œโ”€โ”€ drowsiness_detector.py    # Core detection engine
โ”‚   โ””โ”€โ”€ utils/
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ eye_tracker.py        # EAR calculation
โ”‚       โ”œโ”€โ”€ yawn_detector.py      # MAR calculation
โ”‚       โ””โ”€โ”€ alert_manager.py      # Alert logic
โ”œโ”€โ”€ frontend/
โ”‚   โ”œโ”€โ”€ index.html                # Dashboard
โ”‚   โ”œโ”€โ”€ css/
โ”‚   โ”‚   โ””โ”€โ”€ style.css            # Dark mode styling
โ”‚   โ”œโ”€โ”€ js/
โ”‚   โ”‚   โ”œโ”€โ”€ main.js              # Core JavaScript
โ”‚   โ”‚   โ””โ”€โ”€ chart-config.js      # Chart.js setup
โ”‚   โ””โ”€โ”€ assets/
โ”‚       โ””โ”€โ”€ alert-sound.mp3      # Audio alert
โ”œโ”€โ”€ requirements.txt              # Python dependencies
โ””โ”€โ”€ README.md                     # This file

๐Ÿš€ Future Enhancements

Phase 2 (Short-term)

  • SQLite session logging
  • Export session data to CSV
  • Head pose detection (tilting/nodding)
  • Multiple camera support
  • Custom alert sounds

Phase 3 (Medium-term)

  • SMS/Email alerts to emergency contacts
  • Mobile app (React Native)
  • Cloud dashboard for fleet management
  • Historical analytics and reports
  • Multi-language support

Phase 4 (Long-term)

  • Integration with car systems (OBD-II)
  • Steering pattern analysis
  • Heart rate monitoring (with wearables)
  • AI model fine-tuning with custom dataset
  • Edge device deployment (Raspberry Pi, Jetson)

๐Ÿ› Troubleshooting

Webcam Not Detected

# Check available cameras
import cv2
for i in range(5):
    cap = cv2.VideoCapture(i)
    if cap.isOpened():
        print(f"Camera {i} available")
        cap.release()

Low FPS

  • Close other applications using the webcam
  • Reduce video resolution in app.py:
    camera.set(cv2.CAP_PROP_FRAME_WIDTH, 480)
    camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 360)

Audio Not Playing

  • Check browser permissions
  • Click anywhere on the page to enable audio
  • Try different browser (Chrome recommended)

MediaPipe Errors

pip uninstall mediapipe
pip install mediapipe==0.10.8

๐Ÿ“„ License

This project is licensed under the MIT License.

MIT License

Copyright (c) 2025 DriveSafe AI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

๐Ÿ™ Acknowledgments

  • MediaPipe by Google for facial landmark detection
  • OpenCV community for computer vision tools
  • Chart.js for beautiful visualizations
  • Research papers on drowsiness detection algorithms

๐Ÿ“ง Contact & Support

For questions, suggestions, or contributions:


Made with โค๏ธ for safer roads by Ajith Kumar Murugan

โญ Star this project if you find it useful!

Back to Top

About

DriveSafe AI is a real-time driver drowsiness detection system that uses Python and OpenCV to monitor eye movements through a webcam. The system detects fatigue based on eye closure patterns and provides instant audio and visual alerts using a web-based interface.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published