#include <dlib/opencv.h>
#include <opencv2/highgui/highgui.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <iomanip>
#include<iostream>
#include <opencv2/opencv.hpp>
using namespace dlib;
using namespace std;
int main() {
try {
cv::VideoCapture cap(0); //范围解析运算符,定义类成员。
if (!cap.isOpened()) {
cout << "连接不上摄像头" << endl;
return 1;
}
frontal_face_detector detector = get_frontal_face_detector();
shape_predictor pos_modle; //将文件中的模型放置再pos_modle中
deserialize("/home/xxp/Desktop/face/shape_predictor_68_face_landmarks.dat") >> pos_modle;
while (cv::waitKey(30)!=27)
{
double t = (double)cv::getTickCount();//计时开始时间
//获取一帧
cv::Mat temp,gray; //将摄像头获取的当前帧图片放入到中间文件中
cap >> temp;
//cv_image<bgr_pixel> cimg(temp); //将其转化为RGB像素图片
cv::cvtColor(temp,gray,cv::COLOR_BGR2GRAY);
cv_image<unsigned char>cimg(gray);
std::vector<rectangle> faces = detector(cimg); //开始进行脸部识别
std::vector<full_object_detection> shapes; //发现每一个脸的pos估计
unsigned faceNumber=faces.size(); //将所有脸的区域放入集合之中
for (unsigned i = 0; i < faceNumber; i++)
shapes.push_back(pos_modle(cimg, faces[i])); //第i个人的关键点。
if (!shapes.empty()) {
int faceNumber = shapes.size();
for (int j = 0; j < faceNumber; j++)
{
for (int i = 0; i < 68; i++)
{
cv::circle(temp, cvPoint(shapes[j].part(i).x(), shapes[j].part(i).y()), 1, cv::Scalar(255, 255, 255), -1);
//cv::putText(temp,to_string(i), cvPoint(shapes[0].part(i).x(), shapes[0].part(i).y()), CV_FONT_HERSHEY_PLAIN,1, cv::Scalar(0, 0, 255));
//cout << shapes[0].part(38).y() <<" "<< shapes[0].part(40).y()<<endl;
double a,b,c,d,e,g,f,eye,mouth;
a=shapes[0].part(41).y()-shapes[0].part(37).y();
b=shapes[0].part(40).y()-shapes[0].part(38).y();
c=shapes[0].part(39).x()-shapes[0].part(36).x();
f=shapes[0].part(66).y()-shapes[0].part(62).y();
g=shapes[0].part(64).x()-shapes[0].part(60).x();
d=abs(a)+abs(b);
e=abs(c);
eye=d/e;
mouth=abs(f)/abs(g);
double rate = cap.get(CV_CAP_PROP_FPS); //获取帧率
//cout<<fixed<<setprecision(4)<<mouth<<" "<<eye<<" "<<e<<" "<<rate<<endl;
if (eye<0.286)
{
cv::putText(temp,"don't sleep eye", cvPoint(100, 100), CV_FONT_HERSHEY_PLAIN,4, cv::Scalar(255, 0, 255),2);
}
if (mouth>0.7)
{
cv::putText(temp,"don't sleep mouth", cvPoint(10, 80), CV_FONT_HERSHEY_PLAIN,4, cv::Scalar(255, 0, 255),2);
}
}
}
}
cv::namedWindow("特征点检测",2);
imshow("特征点检测", temp);
t = (double)cv::getTickCount() - t;//代码运行时间=结束时间-开始时间
cout<<t*1000 / cv::getTickFrequency()<<endl;
}
}
catch (serialization_error &e) {
cout << "你需要添加landmark.bat文件,才可以跑这个实例" << endl;
cout << endl << e.what() << endl;
}
catch(exception &e){
cout << e.what() << endl;
}
}