python实现疲劳驾驶检测系统
时间: 2023-11-18 11:52:12 浏览: 141
疲劳驾驶检测系统是一个基于人工智能的应用,可以通过分析驾驶员的眼睛、面部表情、姿势等特征,来检测是否存在疲劳驾驶的行为并及时提醒驾驶员。以下是一个基于Python的疲劳驾驶检测系统的示例代码:
```python
import cv2
import dlib
import numpy as np
from scipy.spatial import distance
# 定义常量
EAR_THRESHOLD = 0.25
EAR_CONSEC_FRAMES = 30
YAWN_THRESH = 20
FRAME_COUNTER = 0
YAWN_COUNTER = 0
# 初始化dlib的人脸检测器和面部标志检测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 定义函数计算两个二维坐标点之间的欧氏距离
def euclidean_dist(ptA, ptB):
return distance.euclidean(ptA, ptB)
# 定义函数计算眼睛的EAR值
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值
ear = (A + B) / (2.0 * C)
return ear
# 加载摄像头
cap = cv2.VideoCapture(0)
while True:
# 获取视频帧
ret, frame = cap.read()
if not ret:
break
# 将视频帧转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = detector(gray, 0)
# 遍历每个人脸
for face in faces:
# 获取面部标志点
landmarks = predictor(gray, face)
landmarks = np.array([[p.x, p.y] for p in landmarks.parts()])
# 提取左右眼的坐标
left_eye = landmarks[36:42]
right_eye = landmarks[42:48]
# 计算左右眼的EAR值
left_ear = eye_aspect_ratio(left_eye)
right_ear = eye_aspect_ratio(right_eye)
# 计算平均EAR值
ear = (left_ear + right_ear) / 2.0
# 绘制眼部区域
cv2.polylines(frame, [left_eye], True, (0, 255, 0), 1)
cv2.polylines(frame, [right_eye], True, (0, 255, 0), 1)
# 判断是否疲劳驾驶
if ear < EAR_THRESHOLD:
FRAME_COUNTER += 1
if FRAME_COUNTER >= EAR_CONSEC_FRAMES:
cv2.putText(frame, "Fatigue Alert!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
else:
FRAME_COUNTER = 0
# 检测是否打哈欠
# 计算嘴部区域的坐标
mouth = landmarks[48:68]
# 计算嘴部区域的高度
mouth_height = euclidean_dist(mouth[2], mouth[10])
if mouth_height > YAWN_THRESH:
YAWN_COUNTER += 1
cv2.putText(frame, "Yawn Alert!", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
else:
YAWN_COUNTER = 0
# 显示EAR值和打哈欠计数器
cv2.putText(frame, "EAR: {:.2f}".format(ear), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame, "Yawn: {}".format(YAWN_COUNTER), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# 显示视频帧
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
这个代码使用了dlib库来检测人脸和面部标志点,通过计算眼睛的EAR值和嘴部区域高度来判断是否存在疲劳驾驶的行为,并在视频帧上显示警示信息。
阅读全文