基於OpenCV harr級聯分類器的人臉及眼睛、鼻子、嘴巴檢測程序。
代碼很簡單:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui//highgui.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <string>
#include <vector>
using namespace std;
int main()
{
cv::CascadeClassifier mFaceDetector;
cv::CascadeClassifier mEyeDetector;
cv::CascadeClassifier mMouthDetector;
cv::CascadeClassifier mNoseDetector;
//載入四個人臉特征分類器文件,可以從opencv的安裝目錄中找到
if( mFaceDetector.empty() )
mFaceDetector.load( "haarcascade_frontalface_default.xml" );
if( mEyeDetector.empty() )
mEyeDetector.load( "haarcascade_mcs_eyepair_big.xml" );
if( mNoseDetector.empty() )
mNoseDetector.load("haarcascade_mcs_nose.xml" );
if( mMouthDetector.empty() )
mMouthDetector.load( "haarcascade_mcs_mouth.xml" );
//打開視頻文件
//cv::VideoCapture capture("bike.avi");
//0 open default camera
cv::VideoCapture capture(0);
//檢查視頻是否打開
if(!capture.isOpened())
return 1;
// 得到幀率
double rate= capture.get(CV_CAP_PROP_FPS);
bool stop(false);
cv::Mat frame; // 現在的視頻幀
cv::Mat mElabImage;//備份frame圖像
cv::namedWindow("Extracted Frame");
// 兩幀之間的間隔時間
int delay= 1000/rate;
// 循環播放所有的幀
while (!stop) {
// 讀下一幀
if (!capture.read(frame))
break;
frame.copyTo( mElabImage );
//檢測臉
//縮放因子
float scaleFactor = 3.0f;
vector< cv::Rect > faceVec;
mFaceDetector.detectMultiScale( frame, faceVec, scaleFactor );
int i, j;
for( i=0; i<faceVec.size(); i++ )
{
cv::rectangle( mElabImage, faceVec[i], CV_RGB(255,0,0), 2 );
cv::Mat face = frame( faceVec[i] );
//檢測眼睛
vector< cv::Rect > eyeVec;
mEyeDetector.detectMultiScale( face, eyeVec );
for( j=0; j<eyeVec.size(); j++ )
{
cv::Rect rect = eyeVec[j];
rect.x += faceVec[i].x;
rect.y += faceVec[i].y;
cv::rectangle( mElabImage, rect, CV_RGB(0,255,0), 2 );
}
//檢測鼻子
vector< cv::Rect > noseVec;
mNoseDetector.detectMultiScale( face, noseVec, 3 );
for( j=0; j<noseVec.size(); j++ )
{
cv::Rect rect = noseVec[j];
rect.x += faceVec[i].x;
rect.y += faceVec[i].y;
cv::rectangle( mElabImage, rect, CV_RGB(0,0,255), 2 );
}
//檢測嘴巴
vector< cv::Rect > mouthVec;
cv::Rect halfRect = faceVec[i];
halfRect.height /= 2;
halfRect.y += halfRect.height;
cv::Mat halfFace = frame( halfRect );
mMouthDetector.detectMultiScale( halfFace, mouthVec, 3 );
for( j=0; j<mouthVec.size(); j++ )
{
cv::Rect rect = mouthVec[j];
rect.x += halfRect.x;
rect.y += halfRect.y;
cv::rectangle( mElabImage, rect, CV_RGB(255,255,255), 2 );
}
}
//在窗口中顯示圖像
cv::imshow("Extracted Frame",mElabImage);
// 按任意鍵停止視頻播放
//if (cv::waitKey(delay)>=0)
// stop= true;
cv::waitKey(20);
}
// 關閉視頻文件
capture.release();
return 0;
}