-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdrowsy.py
More file actions
84 lines (67 loc) · 2.56 KB
/
drowsy.py
File metadata and controls
84 lines (67 loc) · 2.56 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
import cv2
import numpy as np
import dlib
from imutils import face_utils
def compute(ptA, ptB):
dist = np.linalg.norm(ptA - ptB)
return dist
def blinked(a, b, c, d, e, f):
up = compute(b, d) + compute(c, e)
down = compute(a, f)
ratio = up / (2.0 * down)
# Checking if it is blinked
if ratio > 0.25:
return 2
elif 0.21 < ratio <= 0.25:
return 1
else:
return 0
class Drowsy:
def __init__(self):
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
self.sleep, self.drowsy, self.active = 0, 0, 0
self.status = ""
self.color = (0, 0, 0)
def dd(self, frame):
faces = self.detector(frame)
for face in faces:
x1 = face.left()
y1 = face.top()
x2 = face.right()
y2 = face.bottom()
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
landmarks = self.predictor(frame, face)
landmarks = face_utils.shape_to_np(landmarks)
# The numbers are actually the landmarks which will show eye
left_blink = blinked(landmarks[36], landmarks[37],
landmarks[38], landmarks[41], landmarks[40], landmarks[39])
right_blink = blinked(landmarks[42], landmarks[43],
landmarks[44], landmarks[47], landmarks[46], landmarks[45])
# Now judge what to do for the eye blinks
if left_blink == 0 or right_blink == 0:
self.sleep += 1
self.drowsy = 0
self.active = 0
if self.sleep > 6:
self.status = "SLEEPING !!!"
self.color = (255, 0, 0)
elif left_blink == 1 or right_blink == 1:
self.sleep = 0
self.active = 0
self.drowsy += 1
if self.drowsy > 6:
self.status = "Drowsy !"
self.color = (0, 0, 255)
else:
self.drowsy = 0
self.sleep = 0
self.active += 1
if self.active > 6:
self.status = "Active :)"
self.color = (0, 255, 0)
cv2.putText(frame, self.status, (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.2, self.color, 3)
for n in range(0, 68):
(x, y) = landmarks[n]
cv2.circle(frame, (x, y), 1, (255, 255, 255), -1)
return self.status, frame