OpenCV摄像头人脸识别

注:

从外设摄像装置中获取图像帧,把每帧的图片与人脸特征进行匹配,用方框框住识别出来的人脸

需要用到的函数:

CvHaarClassifierCascade* cvLoadHaarClassifierCascade( const char* directory, CvSize orig_window_size );

第一个参数:训练好的级联分类器的路径

第二个参数:级联分类器训练中采用的检测目标的尺寸

 

#include "stdafx.h"
#include "iostream"
using namespace std;
#include "opencv2/opencv.hpp"
#include "cv.h"
#include "highgui.h"
#include "cxcore.h"
#include "Windows.h"
void main()
{

    IplImage *pFrame = NULL;
    IplImage *pGrayImg = NULL;

    //加载Haar特征检测分类器  
    const char *pCascadeFileName = "E:/C_VC_code/opencv/haarcascade_frontalface_alt2.xml";
    //CvHaarClassifierCascade *pHaarCascade  = (CvHaarClassifierCascade*)cvLoad(pCascadeFileName);  
    CvHaarClassifierCascade *pHaarCascade  = cvLoadHaarClassifierCascade(pCascadeFileName,cvSize(200,200));  

    CvCapture *pCapture = cvCreateCameraCapture(0); //获取摄像头  
    cout<< "加载成功..." <<endl;
    int nFrmNum = 0;

    if(!pCapture)
    {
        cout<<"加载失败..."<<endl;
        return ;
    }
    //create window
    cvNamedWindow("Video",1);
    
    CvMemStorage *pcvMStorage; 
    CvSeq *pCvSeq;

    while(pFrame = cvQueryFrame(pCapture))    //逐帧读取
    {
        pGrayImg = cvCreateImage(cvGetSize(pFrame), IPL_DEPTH_8U, 1);
        cvCvtColor(pFrame, pGrayImg, CV_BGR2GRAY);  

        //---------------人脸识别-------------------------
        if (pHaarCascade != NULL)  
        {         
            pcvMStorage = cvCreateMemStorage(0);  
            cvClearMemStorage(pcvMStorage);

            // 识别  
            pCvSeq = cvHaarDetectObjects(pGrayImg, pHaarCascade, pcvMStorage);   
          
            // 标记  
            for(int i = 0; i <pCvSeq->total; i++)  
            {  
                CvRect* r = (CvRect*)cvGetSeqElem(pCvSeq, i);  
                CvPoint pt[4];
                pt[0] = cvPoint(r->x,r->y);
                pt[1] = cvPoint(r->x+r->width,r->y);
                pt[2] = cvPoint(r->x+r->width,r->y+r->height);
                pt[3] = cvPoint(r->x,r->y+r->height);
                CvPoint* ppt=pt;
                int count=4;
                cvPolyLine( pFrame, &ppt,&count,1,1,CV_RGB(10,240,33),2);//画矩形
            }  

            cvReleaseMemStorage(&pcvMStorage);
        }  
      
        cvShowImage("Video",pFrame);
        //---------------人脸识别-------------------------
        char c = cvWaitKey(33);    //按esc退出
        if(c==27)
        {
            cvDestroyWindow("Video");  
            cvReleaseImage(&pFrame);   
            cvReleaseImage(&pGrayImg);  
            return;
        }
    }
}

 

posted @ 2015-11-22 10:54  一样菜  阅读(3843)  评论(0编辑  收藏  举报