OpenCV笔记-利用OpenCV自带的Haar分类器检测人脸

示例代码:

#include <cv.h>

#include <highgui.h>



const char *cascade_name = "E:\\opencv\\opencv\\data\\haarcascades\\haarcascade_frontalface_alt2.xml";

CvHaarClassifierCascade* cascade = NULL;

CvMemStorage* storage = NULL;

void detect_and_draw(IplImage* img, double scale = 3.0);



int main()

{

    //加载OpenCV自带的Haar分类器

    cascade = (CvHaarClassifierCascade*)cvLoad(cascade_name, 0, 0, 0);

    assert(cascade != NULL);

    //分配调用cvHaarDetectObjects函数需要的内存

    storage = cvCreateMemStorage(0);

    assert(storage != NULL);

    //随机获取一个摄像头

    CvCapture*  capture = cvCreateCameraCapture(-1);

    if(capture == NULL)

    {

        printf("未找到任何摄像头!\n");

        return -1;

    }

    cvNamedWindow("haar object detect");

    while(true)

    {

        //从摄像头返回一帧图像

        IplImage* frame = cvQueryFrame(capture);

        //人脸检测和绘制

        detect_and_draw(frame);

        cvShowImage("haar object detect", frame);

        //按Esc退出

        if(27 == cvWaitKey(33))

            break;

    }



    cvDestroyWindow("haar object detect");

    cvReleaseMemStorage(&storage);

    cvReleaseHaarClassifierCascade(&cascade);

    return 0;

}



void detect_and_draw(IplImage* img, double scale)

{

    assert(img != NULL);

    static CvScalar colors[] = {

        {0, 0, 255}, {0, 128, 255}, {0, 255, 255}, {0, 255, 0},

        {255, 128, 0}, {255, 255, 0}, {255, 0, 0}, {255, 0, 255}

    };

    IplImage* gray = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);

    IplImage* small_img = cvCreateImage(cvSize(cvRound(img->width / scale), cvRound(img->height / scale)), IPL_DEPTH_8U, 1);



    assert(gray != NULL);

    assert(small_img != NULL);

    //转换为灰度图

    cvCvtColor( img, gray, CV_BGR2GRAY);

    //调整大小,图像越大,检测速度会慢

    cvResize(gray, small_img,CV_INTER_LINEAR );

    //直方图均衡化,提高对比度

    cvEqualizeHist(small_img, small_img);



    cvClearMemStorage( storage );

    //人脸检测

    CvSeq* objects = cvHaarDetectObjects(

        small_img,

        cascade,//使用的探测器

        storage,

        1.1,//决定2窗口之间的跳跃间隔

        3,//控制误检率

        0,

        cvSize(50, 50)//寻找人脸的最小区域

    );

    if(objects == NULL)

    {

        printf("call cvHaarDetectObjects fail!\n");

        return;

    }

    for(int i = 0; i < (objects ? objects->total : 0); ++i)

    {

        //得到检测到的每个人脸区域

        CvRect* r = (CvRect*)cvGetSeqElem(objects, i);

        //绘制人脸区域

        cvRectangle(

            img,

            cvPoint(r->x * scale, r->y * scale),

            cvPoint(r->x * scale + r->width * scale, r->y * scale + r->height * scale),

            colors[i % 8]

        );

    }



    cvReleaseImage(&gray);

    cvReleaseImage(&small_img);

}

 

你可能感兴趣的:(opencv)