OpenCV+Python+Dlib面部标定、眨眼、打哈欠和疲劳检测代码
时间: 2023-09-03 19:12:58 浏览: 198
OpenCV+Python+Dlib面部标定、眨眼和疲劳检测代码
4星 · 用户满意度95%
以下是一个简单的面部标定、眨眼、打哈欠和疲劳检测的Python代码,使用了OpenCV和Dlib库:
```python
import cv2
import dlib
import numpy as np
# 初始化dlib的人脸检测器和关键点检测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 定义常量
EYE_AR_THRESH = 0.3 # 眨眼的阈值
EYE_AR_CONSEC_FRAMES = 48 # 连续多少帧达到阈值才算眨眼
YAWN_THRESH = 18 # 打哈欠的阈值
YAWN_CONSEC_FRAMES = 24 # 连续多少帧达到阈值才算打哈欠
FRAME_COUNT = 0 # 总帧数
BLINK_COUNT = 0 # 眨眼次数
YAWN_COUNT = 0 # 打哈欠次数
# 定义函数:计算两个点之间的距离
def euclidean_dist(pt1, pt2):
return np.linalg.norm(pt1 - pt2)
# 定义函数:计算眼睛长宽比
def eye_aspect_ratio(eye):
A = euclidean_dist(eye[1], eye[5])
B = euclidean_dist(eye[2], eye[4])
C = euclidean_dist(eye[0], eye[3])
ear = (A + B) / (2.0 * C)
return ear
# 定义函数:检测眨眼
def detect_blink(landmarks):
global BLINK_COUNT
leftEye = landmarks[36:42]
rightEye = landmarks[42:48]
leftEAR = eye_aspect_ratio(leftEye)
rightEAR = eye_aspect_ratio(rightEye)
ear = (leftEAR + rightEAR) / 2.0
if ear < EYE_AR_THRESH:
BLINK_COUNT += 1
# 定义函数:检测打哈欠
def detect_yawn(landmarks):
global YAWN_COUNT
mouth = landmarks[48:68]
yawn_dist = euclidean_dist(mouth[0], mouth[6])
if yawn_dist > YAWN_THRESH:
YAWN_COUNT += 1
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
FRAME_COUNT += 1
# 转换为灰度图
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 人脸检测
rects = detector(gray, 0)
for rect in rects:
# 关键点检测
landmarks = np.array([[p.x, p.y] for p in predictor(gray, rect).parts()])
# 绘制关键点
for i, point in enumerate(landmarks):
x, y = point
cv2.circle(frame, (x, y), 2, (0, 255, 0), -1)
# 检测眨眼
detect_blink(landmarks)
# 检测打哈欠
detect_yawn(landmarks)
# 显示视频帧
cv2.imshow("Frame", frame)
# 按q键退出
if cv2.waitKey(1) == ord("q"):
break
# 计算疲劳度
blink_rate = BLINK_COUNT / FRAME_COUNT
yawn_rate = YAWN_COUNT / FRAME_COUNT
fatigue = blink_rate + yawn_rate
# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
# 打印结果
print("Blink rate:", blink_rate)
print("Yawn rate:", yawn_rate)
print("Fatigue:", fatigue)
```
这个代码使用了Dlib库进行人脸检测和关键点检测,并使用了OpenCV库进行视频捕获和显示。在关键点检测之后,我们通过计算眼睛长宽比来检测眨眼,通过计算嘴巴的张开距离来检测打哈欠。最后,我们计算眨眼率、打哈欠率和疲劳度,并输出结果。
阅读全文