opencv 利用Haar 人臉識別

 

 

#include <opencv2/opencv.hpp>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <Windows.h>  
using namespace std;
int main()
{
    // 加載Haar特徵檢測分類器
    // haarcascade_frontalface_alt.xml系OpenCV自帶的分類器 下面是我機器上的文件路徑
    const char *pstrCascadeFileName = "D:\\opencv\\opencv2.4.10\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
    CvHaarClassifierCascade *pHaarCascade = NULL;
    pHaarCascade = (CvHaarClassifierCascade*)cvLoad(pstrCascadeFileName);

    // 載入圖像
    const char *pstrImageName = "D:\\721.jpg";
    IplImage *pSrcImage = cvLoadImage(pstrImageName, CV_LOAD_IMAGE_UNCHANGED);
    
    IplImage *pGrayImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);
    cvCvtColor(pSrcImage, pGrayImage, CV_BGR2GRAY);

    // 人臉識別與標記
    if (pHaarCascade != NULL)
    {        
        CvScalar FaceCirclecolors[] = 
        {
            {{0, 0, 255}},
            {{0, 128, 255}},
            {{0, 255, 255}},
            {{0, 255, 0}},
            {{255, 128, 0}},
            {{255, 255, 0}},
            {{255, 0, 0}},
            {{255, 0, 255}}
        };

        CvMemStorage *pcvMStorage = cvCreateMemStorage(0);
        cvClearMemStorage(pcvMStorage);
        DWORD dwTimeBegin, dwTimeEnd;
        dwTimeBegin = GetTickCount();
        CvSeq *pcvSeqFaces = cvHaarDetectObjects(pGrayImage, pHaarCascade, pcvMStorage);
        dwTimeEnd = GetTickCount();

        printf("人臉個數: %d   識別用時: %d ms\n", pcvSeqFaces->total, dwTimeEnd - dwTimeBegin);
        
        for(int i = 0; i <pcvSeqFaces->total; i++)
        {
            CvRect* r = (CvRect*)cvGetSeqElem(pcvSeqFaces, i);
            CvPoint center;
            int radius;
            center.x = cvRound((r->x + r->width * 0.5));
            center.y = cvRound((r->y + r->height * 0.5));
            radius = cvRound((r->width + r->height) * 0.25);
            cvCircle(pSrcImage, center, radius, FaceCirclecolors[i % 8], 2);
        }
        cvReleaseMemStorage(&pcvMStorage);
    }
    
    const char *pstrWindowsTitle = "人臉識別";
    cvNamedWindow(pstrWindowsTitle, CV_WINDOW_AUTOSIZE);
    cvShowImage(pstrWindowsTitle, pSrcImage);

    cvWaitKey(0);

    cvDestroyWindow(pstrWindowsTitle);
    cvReleaseImage(&pSrcImage);    
    cvReleaseImage(&pGrayImage);
    return 0;
}
相關文章
相關標籤/搜索