OpenCV——人脸检测

OpenCV支持的目标检测的方法: 利用样本的Haar特征进行的分类器训练,得到的级联boosted分类器(Cascade Classification)

1.加载级联分类器

CascadeClassifier cascade;
cascade.load("haarcascade_frontalface_alt2.xml");

2.打开视频

VideoCapture capture(0);
if (!capture.isOpened()){
        return -1;
    }

3.对每一帧图像进行检测并标出人脸

while (true){
        Mat Image, grayImage;
        capture >> Image;                                //读取当前帧

        //缩小图片加快检测速度
        Mat smallImg(cvRound(Image.rows / 2.0), cvRound(Image.cols / 2.0), CV_8UC1);

        //处理图像
        grayImage.create(Image.size(), Image.type());
        cvtColor(Image, grayImage, CV_BGR2GRAY);
        resize(grayImage, smallImg, smallImg.size(), 0, 0, INTER_LINEAR);
        equalizeHist(smallImg, smallImg);

        vector<Rect> rect;
        cascade.detectMultiScale(smallImg, rect);

        for (int i = 0; i < rect.size(); i++)
        {
            Point  center;                                                      //圆心
            int radius;                                                         //圆的半径

            //由于smallImg是Image的1/2,检测smallImg在Image上绘制圆,要将圆的各类信息扩大一倍

            center.x = cvRound((rect[i].x + rect[i].width * 0.5)) * 2;
            center.y = cvRound((rect[i].y + rect[i].height * 0.5)) * 2;
            radius = cvRound((rect[i].width + rect[i].height) * 0.25) * 2;

            circle(Image, center, radius, CV_RGB(255, 0, 0), 2);                //绘制圆形
        }
        imshow("人脸识别", Image);
        if (waitKey(30) >= 0)break;
    }

 4. 头文件

#include<opencv2/objdetect/objdetect.hpp>  
#include<opencv2/highgui/highgui.hpp>  
#include<opencv2/imgproc/imgproc.hpp>  

 

OK,就是这样

posted @ 2016-10-26 11:09  Not-Bad  阅读(546)  评论(0编辑  收藏  举报