疲劳检测代码
时间: 2023-08-06 13:22:43 浏览: 119
以下是一个简单的基于眼睛疲劳检测的示例代码:
```python
import cv2
import dlib
import numpy as np
from scipy.spatial import distance as dist
def eye_aspect_ratio(eye):
A = dist.euclidean(eye[1], eye[5])
B = dist.euclidean(eye[2], eye[4])
C = dist.euclidean(eye[0], eye[3])
ear = (A + B) / (2.0 * C)
return ear
thresh = 0.25
frame_check = 20
detect = dlib.get_frontal_face_detector()
predict = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 人脸特征点检测器
(lStart, lEnd) = (42, 48)
(rStart, rEnd) = (36, 42)
cap=cv2.VideoCapture(0)
flag=0
while True:
ret, frame=cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
subjects = detect(gray, 0)
for subject in subjects:
shape = predict(gray, subject)
shape = np.matrix([[p.x, p.y] for p in shape.parts()])
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
l_ear = eye_aspect_ratio(leftEye)
r_ear = eye_aspect_ratio(rightEye)
ear = (l_ear + r_ear) / 2.0
leftEyeHull = cv2.convexHull(leftEye)
rightEyeHull = cv2.convexHull(rightEye)
cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)
if ear < thresh:
flag += 1
print (flag)
if flag >= frame_check:
cv2.putText(frame, "****************ALERT!****************", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.putText(frame, "****************ALERT!****************", (10,325),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
else:
flag = 0
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cv2.destroyAllWindows()
cap.stop()
```
这个代码使用了dlib库中的人脸特征点检测器来检测眼睛位置和状态,通过计算眼睛长宽比(EAR)来检测眼睛疲劳程度,并在连续一段时间内检测到眼睛闭合时触发警报。
阅读全文