#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/face.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace cv;
using namespace std;
using namespace cv::face;
static void detecHumenFrontFace(Mat& rgb, Mat& gray)
{
string cascadeFile = "D:/environment/opencv4.1.1/build/etc/haarcascades/haarcascade_frontalface_alt2.xml";
CascadeClassifier cascade;
cascade.load(cascadeFile);
if (cascade.empty())
{
cerr << "Open File error!" << endl;
return;
}
vector<cv::Rect> rects;
cascade.detectMultiScale(gray, rects, 1.1, 3, 0 | CASCADE_SCALE_IMAGE, Size(30, 30)); //追踪效果
if (rects.size() > 0)
{
cout << "检测到人脸!" << endl;
for (auto it = rects.begin(); it != rects.end(); it++)
{
rectangle(rgb,
Point((*it).x, (*it).y),
Point((*it).x + (*it).width, (*it).y + (*it).height),
Scalar(0, 255, 0), 2);
}
}
}
int main()
{
VideoCapture video;
//video = VideoCapture(CAP_DSHOW);
//cv::String url = "http://admin:admin@192.168.0.109:8081";
video.open(0);
if (!video.isOpened())
{
cout << "Open Video Failed!" << endl;
return -1;
}
video.set(CAP_PROP_FOURCC, VideoWriter::fourcc('M', 'J', 'P', 'G'));
video.set(CAP_PROP_FPS,30);
video.set(CAP_PROP_FRAME_WIDTH, 640);
video.set(CAP_PROP_FRAME_HEIGHT, 480);
Mat img, rgb, gray, graysmall2;
double fps, t;
char string[10];
while (1)
{
t = (double)getTickCount();
video >> img;
t = ((double)getTickCount() - t) / getTickFrequency();
fps = 1.0 / t;
sprintf_s(string, "%.2f", fps);
std::string fpsString("FPS:");
fpsString += string;
if (!video.read(img)) break;
cvtColor(img, rgb, COLOR_BGR2RGB);
cvtColor(rgb, gray, COLOR_RGB2GRAY);
resize(gray, graysmall2, Size(gray.cols / 2, gray.rows / 2));
detecHumenFrontFace(img, gray);//detecHumenFrontFace(rgb, gray);
putText(img, fpsString, Point(5, 20), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255));
imshow("Video", img);//imshow("Video", rgb);
if (waitKey(10) >= 0 )
{
break;
}
}
cv::destroyAllWindows();
video.release();
return 0;
}