-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
92 lines (71 loc) · 2.6 KB
/
main.py
File metadata and controls
92 lines (71 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import cv2
import dlib
import time
import numpy as np
from scipy.spatial import distance
import threading
import os # used instead of winsound for Linux
# Compute Eye Aspect Ratio (EAR)
def eye_aspect_ratio(eye):
A = distance.euclidean(eye[1], eye[5])
B = distance.euclidean(eye[2], eye[4])
C = distance.euclidean(eye[0], eye[3])
ear = (A + B) / (2.0 * C)
return ear
# Play alert sound on Linux
def sound_alarm():
for _ in range(3):
os.system('aplay "alert.wav"') # or use full path if needed
time.sleep(0.1)
# EAR threshold and consecutive frame threshold
EAR_THRESHOLD = 0.25
EAR_CONSEC_FRAMES = 20
COUNTER = 0
ALARM_ON = False
# Load dlib's face detector and facial landmarks predictor
print("[INFO] Loading dlib model...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# Eye landmarks indices (from the 68-point model)
(lStart, lEnd) = (42, 48) # left eye
(rStart, rEnd) = (36, 42) # right eye
# Start webcam capture
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, (640, 480))
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
for rect in rects:
shape = predictor(gray, rect)
shape = np.array([[p.x, p.y] for p in shape.parts()])
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
leftEAR = eye_aspect_ratio(leftEye)
rightEAR = eye_aspect_ratio(rightEye)
ear = (leftEAR + rightEAR) / 2.0
# Draw eye contours
cv2.drawContours(frame, [cv2.convexHull(leftEye)], -1, (0, 255, 0), 1)
cv2.drawContours(frame, [cv2.convexHull(rightEye)], -1, (0, 255, 0), 1)
# Check for drowsiness
if ear < EAR_THRESHOLD:
COUNTER += 1
if COUNTER >= EAR_CONSEC_FRAMES:
if not ALARM_ON:
ALARM_ON = True
threading.Thread(target=sound_alarm).start()
cv2.putText(frame, "DROWSINESS ALERT!", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
else:
COUNTER = 0
ALARM_ON = False
# Display EAR on screen
cv2.putText(frame, f"EAR: {ear:.2f}", (480, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 1)
cv2.imshow("Drowsiness Detection", frame)
if cv2.waitKey(1) == 27: # ESC key to exit
break
cap.release()
cv2.destroyAllWindows()