先抄为敬
import cv2
import cv2 as cv
import dlib
import imutils
from imutils import face_utils
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])
return (a + b) / (2.0 * c)
EYE_AR_THRESH = 0.3
EYE_AR_frameS = 3
COUNTER = 0
TOTAL = 0
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('./1.dat')
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
cap = cv.VideoCapture(0, cv.CAP_DSHOW)
while True:
ret, frame = cap.read()
frame = imutils.resize(frame, width=450) # 设置宽度 ·450
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
rs = detector(gray, 0)
for rect in rs:
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
leftEAR = eye_aspect_ratio(leftEye)
rightEAR = eye_aspect_ratio(rightEye)
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)
if ear < EYE_AR_THRESH:
COUNTER += 1
else:
if COUNTER >= EYE_AR_frameS:
TOTAL += 1
COUNTER = 0
cv2.putText(frame, "Blinks: {}".format(TOTAL), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.putText(frame, "EAR: {:.2f}".format(ear), (300, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
cv2.destroyAllWindows()
cap.release()