Skip to content

Commit 45eab6e

Browse files
author
HappySaxena
committed
fixing in face_try.py file
2 parents 7d78650 + 2f17976 commit 45eab6e

File tree

8 files changed

+298
-36
lines changed

8 files changed

+298
-36
lines changed

CONTRIBUTION.md renamed to CONTRIBUTING.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
Thanks for your interest in contributing! This guide will help you get started.
44

5+
🙏 **If you haven't already, please consider [starring the repository ⭐](https://github.com/Gagandeep-2003/Driver-Drowsiness-Detection-System)** to show your support and help others discover the project.
6+
57
---
68

79
## 🛠️ Project Setup

License

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) [2025] [jai-76]
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,25 @@
11
# Driver Drowsiness Detection System
22

3+
<p align="center">
4+
<img src="https://img.shields.io/github/stars/Gagandeep-2003/Driver-Drowsiness-Detection-System?style=social" alt="GitHub stars" />
5+
<img src="https://img.shields.io/github/forks/Gagandeep-2003/Driver-Drowsiness-Detection-System?style=social" alt="GitHub forks" />
6+
<img src="https://img.shields.io/github/issues/Gagandeep-2003/Driver-Drowsiness-Detection-System" alt="GitHub issues" />
7+
</p>
8+
9+
310
## Project Overview
411
The Driver Drowsiness Detection System is a non-intrusive solution designed to monitor and detect signs of fatigue in drivers. By analyzing eye states through a camera feed, the system can identify early symptoms of drowsiness and issue timely warnings, helping to prevent accidents caused by driver fatigue. This project aims to enhance road safety, especially for those driving long distances who may not recognize their own drowsiness in time.
512

13+
## ⭐ Support the Project
14+
15+
If you find this project helpful, please consider giving it a **star** ⭐ on GitHub!
16+
It helps others discover the project and motivates us to keep improving it.
17+
18+
👉 Click the ⭐ button at the top-right of this page!
19+
20+
[![GitHub stars](https://img.shields.io/github/stars/Gagandeep-2003/Driver-Drowsiness-Detection-System.svg?style=social)](https://github.com/Gagandeep-2003/Driver-Drowsiness-Detection-System/stargazers)
21+
22+
623
## Key Features
724
- Real-time monitoring of driver’s eyes using a camera
825
- Fatigue and drowsiness detection algorithm
@@ -15,6 +32,12 @@ The Driver Drowsiness Detection System is a non-intrusive solution designed to m
1532
- Dlib or Mediapipe (for facial landmark detection)
1633
- NumPy, Pandas
1734

35+
36+
## Optional: create a virtual environment
37+
python -m venv venv
38+
source venv/bin/activate # On Windows: venv\Scripts\activate
39+
40+
1841
## Setup Instructions
1942
1. **Clone the repository:**
2043
```bash
@@ -39,10 +62,17 @@ The Driver Drowsiness Detection System is a non-intrusive solution designed to m
3962
## Folder Structure
4063
```
4164
Driver-Drowsiness-Detection-System/
65+
├── drowsiness_detector/
66+
│ ├── detector.py
67+
│ └── utils.py
68+
├── models/
69+
│ └── shape_predictor_68_face_landmarks.dat
70+
├── assets/
71+
│ └── demo.gif
4272
├── main.py
4373
├── requirements.txt
4474
├── README.md
45-
├── ... (other scripts and folders)
75+
4676
```
4777

4878
## Contribution Guidelines
@@ -54,10 +84,35 @@ We welcome contributions to improve this project! To get started:
5484
5. Push your branch to your forked repo.
5585
6. Open a Pull Request describing your changes.
5686

87+
---
88+
89+
## 🌐 Streamlit Web App (New Feature!)
90+
91+
This app version uses Streamlit + Mediapipe to detect drowsiness via webcam directly in the browser.
92+
93+
### Usage:
94+
```bash
95+
streamlit run streamlit_app/streamlit_app.py
96+
97+
Dependencies:
98+
Install using:
99+
pip install -r requirements.txt
100+
101+
Features:
102+
Real-time Eye Aspect Ratio (EAR) monitoring
103+
Drowsiness warning overlay
104+
Web-based UI with live video
105+
57106
**Note:** Please do not add a license section. A contributor will be adding license information soon.
58107

59108
If you have any questions or need guidance, feel free to open an issue or ask in the discussions!
60109

61110
---
62111

63112
Thank you for your interest in improving the Driver Drowsiness Detection System! Your contributions are greatly appreciated.
113+
114+
<p align="center">
115+
<a href="#top" style="font-size: 18px; padding: 8px 16px; display: inline-block; border: 1px solid #ccc; border-radius: 6px; text-decoration: none;">
116+
⬆️ Back to Top
117+
</a>
118+
</p>

face-try.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# -*- coding: utf-8 -*-
1+
# -- coding: utf-8 --
22
"""
33
Created on Sun Dec 29 18:48:12 2019
44

main.py

Lines changed: 35 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,46 @@
1-
# -*- coding: utf-8 -*-
2-
"""
3-
Created on Fri Nov 22 11:04:42 2019
1+
import tkinter as tk
2+
from tkinter import ttk
3+
import subprocess
44

5-
@author: Lenovo
6-
"""
5+
face_proc = None
76

8-
from tkinter import *
9-
from tkinter.ttk import *
10-
import subprocess
117

12-
def blink():
13-
subprocess.call(["python", "face-try.py"])
14-
15-
def lane():
8+
def run_face_detection():
9+
global face_proc
10+
face_proc = subprocess.Popen(["python", "face-try.py"])
11+
12+
13+
def run_blink_detection():
1614
subprocess.call(["python", "blinkDetect.py"])
1715

18-
root = Tk()
19-
root.geometry('500x500')
20-
style = Style()
21-
style.configure('TButton', font =('calibri', 20, 'bold'), borderwidth = '2')
22-
#root.title('The game')
23-
root.geometry("500x500")
24-
#tk.resizable(0, 0)
25-
frame = tk.Frame(root)
26-
frame.pack()
16+
def on_quit(root):
17+
if face_proc and face_proc.poll() is None:
18+
face_proc.terminate()
19+
root.destroy()
20+
21+
22+
def main():
23+
root = tk.Tk()
24+
root.title("Driver Drowsiness Detection System")
25+
root.geometry("500x500")
26+
27+
style = ttk.Style()
28+
style.configure('TButton', font=('Calibri', 20, 'bold'), borderwidth=2)
2729

30+
frame = ttk.Frame(root, padding=20)
31+
frame.pack(expand=True)
2832

29-
button1 = Button(frame, text="Face Detection", fg="red", command=blink,height=25, width=10)
30-
button1.pack(side=root.LEFT)
33+
btn_face = ttk.Button(frame, text="Face Detection", command=run_face_detection)
34+
btn_face.pack(side=tk.LEFT, padx=10, pady=10)
3135

32-
button2 = Button(frame, text="Blink Detection", fg="red",command=lane)
33-
button2.pack(side=root.RIGHT)
36+
btn_blink = ttk.Button(frame, text="Blink Detection", command=run_blink_detection)
37+
btn_blink.pack(side=tk.RIGHT, padx=10, pady=10)
3438

35-
button3 = Button(frame, text="Quit", fg="red",command=root.destroy)
36-
button3.pack(side=root.BOTTOM)
39+
# btn_quit = ttk.Button(root, text="Quit", command=root.destroy)
40+
btn_quit = ttk.Button(root, text="Quit", command=lambda: on_quit(root))
41+
btn_quit.pack(side=tk.BOTTOM, pady=20)
3742

43+
root.mainloop()
3844

39-
root.mainloop()
45+
if __name__ == "__main__":
46+
main()

requirements.txt

Lines changed: 77 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,77 @@
1-
opencv-python
2-
dlib
3-
numpy
4-
scipy
5-
playsound
6-
matplotlib
1+
# ====================================================================
2+
# DRIVER DROWSINESS DETECTION SYSTEM - REQUIREMENTS
3+
# ====================================================================
4+
# This file contains all the Python dependencies required to run the
5+
# driver drowsiness detection system. Each package is carefully versioned
6+
# to ensure compatibility and stable performance.
7+
#
8+
# INSTALLATION INSTRUCTIONS:
9+
# 1. Create a virtual environment (recommended):
10+
# python -m venv drowsiness_env
11+
# source drowsiness_env/bin/activate # On Windows: drowsiness_env\Scripts\activate
12+
#
13+
# 2. Install all dependencies:
14+
# pip install -r requirements.txt
15+
#
16+
# 3. Additional setup for dlib (if installation fails):
17+
# - Install cmake: pip install cmake
18+
# - Install dlib: pip install dlib
19+
# ====================================================================
20+
21+
# ====================================================================
22+
# COMPUTER VISION AND IMAGE PROCESSING
23+
# ====================================================================
24+
opencv-python>=4.5.0,<5.0.0
25+
# Optional: for GPU support
26+
# opencv-contrib-python
27+
28+
# ====================================================================
29+
# FACIAL LANDMARK DETECTION AND SHAPE PREDICTION
30+
# ====================================================================
31+
dlib>=19.22.0,<20.0.0
32+
33+
# ====================================================================
34+
# NUMERICAL COMPUTING AND MATHEMATICAL OPERATIONS
35+
# ====================================================================
36+
numpy>=1.19.0,<2.0.0
37+
scipy>=1.7.0,<2.0.0
38+
39+
# ====================================================================
40+
# AUDIO PROCESSING AND ALERTS
41+
# ====================================================================
42+
playsound>=1.2.2,<2.0.0
43+
playsound; platform_system == "Windows" # For compatibility on Windows
44+
45+
# ====================================================================
46+
# DATA VISUALIZATION AND PLOTTING
47+
# ====================================================================
48+
matplotlib>=3.3.0,<4.0.0
49+
50+
# ====================================================================
51+
# STREAMLIT WEB APP DEPENDENCIES
52+
# ====================================================================
53+
streamlit>=1.25.0,<2.0.0
54+
streamlit-webrtc>=0.45.0,<1.0.0
55+
mediapipe>=0.10.0,<1.0.0
56+
57+
# ====================================================================
58+
# BUILT-IN PYTHON LIBRARIES (No installation required)
59+
# ====================================================================
60+
# - tkinter
61+
# - threading
62+
# - queue
63+
# - subprocess
64+
# - time
65+
# - sys
66+
67+
# ====================================================================
68+
# COMPATIBILITY NOTES
69+
# ====================================================================
70+
# Python Version: Tested with Python 3.7 - 3.10
71+
# Operating Systems: Windows 10/11, macOS 10.15+, Ubuntu 18.04+
72+
#
73+
# TROUBLESHOOTING:
74+
# - If dlib installation fails, install Visual Studio Build Tools (Windows)
75+
# - For macOS users, install Xcode command line tools: xcode-select --install
76+
# - Linux users may need: sudo apt-get install cmake libopenblas-dev liblapack-dev
77+
# ====================================================================

streamlit_app/alarm.mp3

15.6 KB
Binary file not shown.

streamlit_app/streamlit_app.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import streamlit as st
2+
import cv2
3+
import mediapipe as mp
4+
import numpy as np
5+
from streamlit_webrtc import webrtc_streamer, VideoTransformerBase
6+
import av
7+
import threading
8+
import time
9+
import base64
10+
11+
# Eye aspect ratio threshold and consecutive frames
12+
EAR_THRESHOLD = 0.25
13+
CONSEC_FRAMES = 20
14+
15+
# Load alarm
16+
def play_alarm():
17+
try:
18+
from playsound import playsound
19+
playsound('alarm.mp3')
20+
except:
21+
st.warning("Audio alert failed to play.")
22+
23+
alarm_thread = None
24+
25+
def euclidean(p1, p2):
26+
return np.linalg.norm(np.array(p1) - np.array(p2))
27+
28+
def calculate_ear(landmarks, eye_indices):
29+
# Eye landmarks
30+
p1, p2 = landmarks[eye_indices[1]], landmarks[eye_indices[5]]
31+
p3, p4 = landmarks[eye_indices[2]], landmarks[eye_indices[4]]
32+
p5, p6 = landmarks[eye_indices[0]], landmarks[eye_indices[3]]
33+
34+
vertical1 = euclidean(p2, p4)
35+
vertical2 = euclidean(p3, p5)
36+
horizontal = euclidean(p1, p6)
37+
38+
ear = (vertical1 + vertical2) / (2.0 * horizontal)
39+
return ear
40+
41+
class DrowsinessDetector(VideoTransformerBase):
42+
def __init__(self):
43+
self.mp_face = mp.solutions.face_mesh
44+
self.face_mesh = self.mp_face.FaceMesh(refine_landmarks=True)
45+
self.frame_count = 0
46+
self.drowsy = False
47+
48+
def transform(self, frame):
49+
global alarm_thread
50+
img = frame.to_ndarray(format="bgr24")
51+
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
52+
results = self.face_mesh.process(img_rgb)
53+
54+
if results.multi_face_landmarks:
55+
for face_landmarks in results.multi_face_landmarks:
56+
h, w, _ = img.shape
57+
landmarks = [(int(l.x * w), int(l.y * h)) for l in face_landmarks.landmark]
58+
59+
# Left and right eyes
60+
left_eye = [362, 385, 387, 263, 373, 380]
61+
right_eye = [33, 160, 158, 133, 153, 144]
62+
63+
left_ear = calculate_ear(landmarks, left_eye)
64+
right_ear = calculate_ear(landmarks, right_eye)
65+
ear = (left_ear + right_ear) / 2.0
66+
67+
if ear < EAR_THRESHOLD:
68+
self.frame_count += 1
69+
else:
70+
self.frame_count = 0
71+
self.drowsy = False
72+
73+
if self.frame_count >= CONSEC_FRAMES:
74+
self.drowsy = True
75+
cv2.putText(img, "DROWSY!", (30, 60),
76+
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 4)
77+
# Play alarm in separate thread
78+
if alarm_thread is None or not alarm_thread.is_alive():
79+
alarm_thread = threading.Thread(target=play_alarm)
80+
alarm_thread.start()
81+
else:
82+
cv2.putText(img, f"EAR: {ear:.2f}", (30, 30),
83+
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
84+
85+
return img
86+
87+
# Streamlit app
88+
st.set_page_config(page_title="Driver Drowsiness Detection", layout="centered")
89+
st.title("🚗 Driver Drowsiness Detection")
90+
st.markdown("Detects eye closure and triggers an audio alert if drowsiness is detected.")
91+
92+
# Run webcam with Streamlit
93+
webrtc_streamer(
94+
key="drowsiness-app",
95+
video_processor_factory=DrowsinessDetector,
96+
media_stream_constraints={"video": True, "audio": False},
97+
async_processing=True,
98+
)
99+
100+
# Embed alarm.wav to trigger download if needed
101+
with open("alarm.wav", "rb") as f:
102+
b64 = base64.b64encode(f.read()).decode()
103+
st.markdown(
104+
f'<a href="data:audio/wav;base64,{b64}" download="alarm.wav">Download alarm.wav if needed</a>',
105+
unsafe_allow_html=True,
106+
)

0 commit comments

Comments
 (0)