PYTHON闭眼检测

参考于这篇眨眼检测博客,在他原来的代码上的条件做了修改。https://blog.csdn.net/ctwy291314/article/details/81665328
谢谢这位大佬。
本来是想做睡觉检测的,但是我只能走到这一步了,希望有大佬可以帮助我实现闭眼7秒则程序会提示。

代码如下

from scipy.spatial import distance as dist```
from imutils.video import FileVideoStream
from imutils.video import VideoStream
from imutils import face_utils
import numpy as np
import argparse
import imutils
import time
import dlib
import cv2

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

EYE_AR_THRESH = 0.2
EYE_AR_CONSEC_FRAMES = 3

COUNTER = 0
TOTAL = 0

print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]

cap = cv2.VideoCapture(0)

while True:	
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    rects = detector(gray, 0)

    for rect in rects:
        shape = predictor(gray, rect)
        shape = face_utils.shae_to_np(shape)
        leftEye = shape[lStart:lEnd]
        rightEye = shape[rStart:rEnd]

        ear = (leftEAR + rightEAR) / 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)

        left = rect.left()
        top = rect.top()
        right = rect.right()
        bottom = rect.bottom()
        cv2.rectangle(frame, (left,top),(right,bottom),(0,255,0), 3)
        
        if ear < EYE_AR_THRESH:
            cv2.putText(frame,"Warning",(150,30),
            cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,0,255), 2)
        
    cv2.imshow("Frame", frame)        
    print(len(rects))   
        
    if cv2.waitKey(1) & 0xFF == ord('q'): 
        break
               
cv2.destroyAllWindows()        
        
 '''
 EYE_AR_THRESH的值可以自己调试修改,我用的是0.25比较准确
 我其实就是修改了这位大佬的条件语句罢了。
 在发表的时候代码是纯手打的(原谅我是新人不知道怎么复制过来),
 可能会出现一些缩进错误,敬请原谅!
 '''
 
 
 

猜你喜欢

转载自blog.csdn.net/weixin_43810148/article/details/88931576