C++:opencv 人脸检测

C++:opencv 人脸检测

问题描述:

要求

输入一张图片;输出圈出人脸的图片;
vs2015; opencv3.4.6;

效果

输入:
C++:opencv 人脸检测_第1张图片
输出:
C++:opencv 人脸检测_第2张图片

代码实现:

#include "opencv2/objdetect.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"

#include <iostream>

using namespace std;
using namespace cv;

/** Function Headers */
void detectAndDisplay( Mat frame );

/** Global variables */
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;

/** @function main */
int main( )
{
    if(!face_cascade.load("haarcascade_frontalface_alt.xml")) //opencv自带的人脸识别
    {
        cout << "--(!)Error loading face cascade\n";
        return -1;
    };
    if(!eyes_cascade.load("haarcascade_eye_tree_eyeglasses.xml"))
    {
        cout << "--(!)Error loading eyes cascade\n";
        return -1;
    };
	Mat frame = imread("lena.jpg");//输入图片
	if (frame.empty())
	{
		cout << " wrong" << endl;
	}
	detectAndDisplay(frame);
    return 0;
}
/** @function detectAndDisplay */
void detectAndDisplay( Mat frame )
{
    Mat frame_gray;
    cvtColor( frame, frame_gray, COLOR_BGR2GRAY );
    equalizeHist( frame_gray, frame_gray );
    //-- Detect faces
    std::vector<Rect> faces;
    face_cascade.detectMultiScale( frame_gray, faces );
    for ( size_t i = 0; i < faces.size(); i++ )
    {
        Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 );
        ellipse( frame, center, Size( faces[i].width/2, faces[i].height/2 ), 0, 0, 360, Scalar( 255, 0, 255 ), 4 );
        Mat faceROI = frame_gray( faces[i] );
        //-- In each face, detect eyes
        std::vector<Rect> eyes;
        eyes_cascade.detectMultiScale( faceROI, eyes );
        for ( size_t j = 0; j < eyes.size(); j++ )
        {
            Point eye_center( faces[i].x + eyes[j].x + eyes[j].width/2, 
            				faces[i].y + eyes[j].y + eyes[j].height/2 );
            				
            int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 );
            circle( frame, eye_center, radius, Scalar( 255, 0, 0 ), 4 );
        }
    }
    //-- Show what you got
    imshow( "Face detection", frame );
	waitKey(0);
}

总结

  1. 创建一个分类器
  2. 加载训练模型
  3. 创建保存人脸的矩阵
  4. 调包
  5. 绘图
  6. 显示
7. CascadeClassifier face_cascade;	
8. face_cascade.load("训练好的xml模型");
9. std::vector faces;//人脸的矩阵数据
10. face_cascade.detectMultiScale( frame_gray, faces );//输入人脸的照片; 输出人脸的矩形数据
11. Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 );
    ellipse( frame, center, Size( faces[i].width/2, faces[i].height/2 ), 0, 0, 360, Scalar( 255, 0, 255 ), 4 );//画
12.  imshow( "Face detection", frame );//显示

你可能感兴趣的:(opencv,c++,opencv,人脸识别,人脸检测)