闭眼睛打哈欠低头疲劳检测代码
时间: 2023-08-01 16:14:26 浏览: 106
以下是基于Python和OpenCV的闭眼睛打哈欠低头疲劳检测代码:
```
import cv2
import dlib
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
def detect_fatigue(frame, detector, predictor, ear_thresh, yawn_thresh, consec_frames):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
for rect in rects:
shape = predictor(gray, rect)
shape = shape_to_np(shape)
left_eye = shape[42:48]
right_eye = shape[36:42]
left_ear = eye_aspect_ratio(left_eye)
right_ear = eye_aspect_ratio(right_eye)
ear = (left_ear + right_ear) / 2.0
mouth = shape[48:68]
mar = mouth_aspect_ratio(mouth)
if ear < ear_thresh or mar > yawn_thresh:
consec_frames += 1
if consec_frames >= 15:
return True, consec_frames
else:
consec_frames = 0
return False, consec_frames
def main():
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
cap = cv2.VideoCapture(0)
ear_thresh = 0.25
yawn_thresh = 0.5
consec_frames = 0
while True:
ret, frame = cap.read()
if not ret:
break
fatigue, consec_frames = detect_fatigue(frame, detector, predictor, ear_thresh, yawn_thresh, consec_frames)
if fatigue:
cv2.putText(frame, "FATIGUE ALERT!", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
```
该代码使用dlib库检测面部和眼部特征,并计算眼睛的长宽比和嘴部的张开程度。如果长宽比小于给定的阈值或嘴部张开程度大于给定的阈值,并且这种情况持续了一段时间,则判断为疲劳状态,并显示警报。
阅读全文