眼部纵横比动态疲劳判断python代码
时间: 2023-11-08 19:12:13 浏览: 97
OpenCV+Python+Dlib面部标定、眨眼和疲劳检测代码
4星 · 用户满意度95%
以下是一个简单的 Python 代码示例,用于计算眼部纵横比并判断动态疲劳:
```python
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
# 加载面部特征检测器
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 = 3
# 初始化变量
COUNTER = 0
TOTAL = 0
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取视频流中的帧
ret, frame = cap.read()
# 转换帧为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测面部特征
faces = detector(gray, 0)
# 循环处理每张脸
for face in faces:
# 提取面部特征
shape = predictor(gray, face)
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_CONSEC_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)
# 检查用户是否按下 q 键
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
# 清理
cv2.destroyAllWindows()
cap.stop()
```
该代码使用 dlib 库和 OpenCV 库进行面部特征检测和眨眼检测。它使用眼部纵横比来判断眨眼,并计算连续的帧数以判断动态疲劳。最后,它在视频流中绘制了眼部区域和相关信息。
阅读全文