基于opencv的疲劳驾驶检测 c++代码
时间: 2023-07-27 09:07:11 浏览: 199
基于OpenCV的疲劳驾驶检测系统的设计与实现
3星 · 编辑精心推荐
以下是基于OpenCV实现疲劳驾驶检测的C++代码:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
VideoCapture cap(0);
if (!cap.isOpened())
{
cout << "Failed to open camera." << endl;
return -1;
}
int frameCount = 0;
int eyeCloseCount = 0;
int eyeOpenCount = 0;
int yawnCount = 0;
while (true)
{
Mat frame;
cap >> frame;
if (frame.empty())
{
cout << "Failed to capture frame." << endl;
break;
}
// 人脸检测
CascadeClassifier faceDetector("haarcascade_frontalface_alt.xml");
vector<Rect> faces;
faceDetector.detectMultiScale(frame, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
if (faces.size() == 0)
{
cout << "Failed to detect face." << endl;
continue;
}
// 眼睛检测
CascadeClassifier eyeDetector("haarcascade_eye.xml");
vector<Rect> eyes;
eyeDetector.detectMultiScale(frame(faces[0]), eyes, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(20, 20));
bool isEyeOpen = false;
for (int i = 0; i < eyes.size(); i++)
{
rectangle(frame(faces[0]), eyes[i], Scalar(255, 0, 0), 2);
if (eyes[i].y + eyes[i].height / 2 < faces[0].y + faces[0].height / 2)
{
isEyeOpen = true;
}
}
// 嘴巴检测
CascadeClassifier mouthDetector("haarcascade_mcs_mouth.xml");
vector<Rect> mouths;
mouthDetector.detectMultiScale(frame(faces[0]), mouths, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
bool isMouthOpen = false;
for (int i = 0; i < mouths.size(); i++)
{
rectangle(frame(faces[0]), mouths[i], Scalar(0, 255, 0), 2);
if (mouths[i].y + mouths[i].height / 2 > faces[0].y + faces[0].height / 2)
{
isMouthOpen = true;
}
}
// 统计疲劳情况
frameCount++;
if (isEyeOpen)
{
eyeOpenCount++;
eyeCloseCount = 0;
}
else
{
eyeCloseCount++;
eyeOpenCount = 0;
}
if (isMouthOpen)
{
yawnCount++;
}
if (eyeCloseCount > 30 || yawnCount > 5)
{
cout << "Driver is fatigued!" << endl;
break;
}
imshow("Fatigue Detection", frame);
if (waitKey(30) == 'q')
{
break;
}
}
cout << "Frame Count: " << frameCount << endl;
cout << "Eye Open Count: " << eyeOpenCount << endl;
cout << "Eye Close Count: " << eyeCloseCount << endl;
cout << "Yawn Count: " << yawnCount << endl;
return 0;
}
```
这段代码基于OpenCV实现了疲劳驾驶检测,其中包括人脸检测、眼睛检测、嘴巴检测和疲劳情况统计。具体流程如下:
1. 打开摄像头,获取一帧图像。
2. 使用Haar级联分类器检测人脸。
3. 在人脸区域中使用Haar级联分类器检测眼睛和嘴巴。
4. 判断眼睛是否闭合,统计连续闭合的帧数。
5. 判断嘴巴是否张开,统计连续张开的帧数。
6. 如果眼睛连续闭合的帧数超过阈值或嘴巴连续张开的帧数超过阈值,则判定驾驶员疲劳。
7. 显示检测结果并等待用户按下“q”键退出程序。
注:上述代码中,使用了三个级联分类器文件:haarcascade_frontalface_alt.xml、haarcascade_eye.xml、haarcascade_mcs_mouth.xml。这些文件可以在OpenCV的安装目录下的data目录中找到。
阅读全文