OpenCV+Python+Dlib面部标定、眨眼和疲劳检测代码
时间: 2023-09-03 18:12:58 浏览: 95
python 3利用Dlib 19.7实现摄像头人脸检测特征点标定
以下是一个基于OpenCV、Python和Dlib的面部标定、眨眼和疲劳检测代码:
```python
import cv2
import dlib
import numpy as np
from scipy.spatial import distance as dist
# 用于计算眼睛长宽比的常量
EYE_AR_THRESH = 0.2
EYE_AR_CONSEC_FRAMES = 3
# 初始化计数器和总帧数
COUNTER = 0
TOTAL = 0
# 加载面部检测器和预测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 提取左眼和右眼的索引
(lStart, lEnd) = (42, 48)
(rStart, rEnd) = (36, 42)
# 计算眼睛长宽比
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
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取每一帧
ret, frame = cap.read()
# 将帧调整为合适大小
frame = cv2.resize(frame, (800, 600))
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测脸部
faces = detector(gray, 0)
# 循环每张脸
for face in faces:
# 提取脸部标志点
shape = predictor(gray, face)
shape = np.array([(shape.part(i).x, shape.part(i).y) for i in range(68)])
# 提取左眼和右眼的坐标
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
# 如果连续N帧眼睛长宽比小于阈值,则认为眼睛在闭合
if COUNTER >= EYE_AR_CONSEC_FRAMES:
cv2.putText(frame, "Blink Detected", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
else:
COUNTER = 0
# 绘制眼睛长宽比
cv2.putText(frame, "EAR: {:.2f}".format(ear), (480, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
# 统计总帧数
TOTAL += 1
# 显示视频流
cv2.imshow("Frame", frame)
# 按'q'键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头并销毁所有窗口
cap.release()
cv2.destroyAllWindows()
```
这段代码可以检测眨眼和疲劳,当连续若干帧眼睛长宽比小于阈值时,程序会输出"Blink Detected",表示检测到了眨眼。同时,程序也会输出当前的眼睛长宽比。
阅读全文