使用opencv在视频中检测人脸
#include <iostream>
#include "cxcore.h"
#include "cv.h"
//#include "highgui.h"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdio.h>
using namespace std;
using namespace cv;
void detectAndDisplay(Mat face);
string face_cascade_name = "haarcascade_frontalface_alt.xml";
CascadeClassifier face_cascade;
int main(int _argc, char **_argv){
char *videoName;
if (_argc != 2){
videoName = "ny.avi";
}
else
{
videoName = _argv[1];
}
//cvNamedWindow("video", 0);
//打开视频文件---
VideoCapture capture(videoName);
if (!capture.isOpened())cout << "fail to open!" << endl;
//获取帧的总数
long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT);
cout << "整个视频共" << totalFrameNumber << "帧" << endl;
//从第30帧开始捕捉
long frameToStart = 300;
long currentFrame = frameToStart;//记录当前读取的是第几帧
capture.set(CV_CAP_PROP_POS_FRAMES, frameToStart);
//获取帧率
double rate = capture.get(CV_CAP_PROP_FPS);
cout << "帧率为:" << rate << endl;
namedWindow("Extracted Frame"); //建立一个用以显示图像的窗口
Mat frame; //存放每一帧的图像
//利用while循环读取帧
while (true){
if (!capture.read(frame)){
cout << "读取视频失败" << endl;
return -1;
}
//在当前帧图片中检测人脸/
if (!face_cascade.load(face_cascade_name)){
printf("级联分类器错误,可能未找到文件,拷贝该文件到工程目录下!\n");
return -1;
}
detectAndDisplay(frame); //调用人脸检测函数
/
imshow("Extracted Frame",frame);
cout << "正在读取第" << currentFrame << "帧" << endl;
int c = waitKey(33); //等待33毫秒 //当时间结束前没有按键按下时,返回值为-1;否则返回按键
if (c == 27 || currentFrame >= totalFrameNumber)
{
break;
}
if (c >= 0){
waitKey(0);
}
currentFrame++;
}
capture.release();
waitKey(0);
return 0;
}
void detectAndDisplay(Mat face){
std::vector<Rect> faces;
Mat face_gray;
cvtColor(face, face_gray, CV_BGR2GRAY); //rgb类型转换为灰度类型
equalizeHist(face_gray, face_gray); //直方图均衡化
/*
//iplImage to Mat
cv::Mat pmatImage = cv::cvarrToMat(face_gray); //第二个参数表示不进行像素数据copy;
*/
face_cascade.detectMultiScale(face_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(1, 1));
for (int i = 0; i < faces.size(); i++){
Point center(faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5);
ellipse(face, center, Size(faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar(255, 0, 0), 2, 7, 0);
}
imshow("Extracted Frame", face);
}