1. 程式人生 > >Opencv之簡單人臉檢測

Opencv之簡單人臉檢測

話不多說,直接上程式碼:

#include "stdafx.h"

#include <opencv2\opencv.hpp>

using namespace cv;

int main()

{

    CascadeClassifier face_cascade;

    //use the haarcascade_frontalface_alt2.xml library

    face_cascade.load("E:\\Opencv\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt2.xml"

);

    const char* imagename = "F:\\Picture\\test.jpg";

    //從檔案中讀入影象

    Mat img = imread(imagename);

    //如果讀入影象失敗

    if (img.empty())

    {

        fprintf(stderr,"Can not load image %s\n", imagename);

        return -1;

    }

    //setup image files used in the process

    Mat grayscaleFrame;

    //convert captured image to gray scale and equalize

    cvtColor(img, grayscaleFrame, CV_BGR2GRAY);

    equalizeHist(grayscaleFrame,grayscaleFrame);

    //create a vector array to store the face found

    std::vector<Rect> faces;

    //find faces and store them in the vector array

    face_cascade.detectMultiScale(grayscaleFrame,faces, 1.1, 3, 0,Size

(20, 20));

    //draw a rectangle for all found faces in the vectorarray on the original image

    for (int i = 0; i < faces.size(); i++)

    {

        Point pt1(faces[i].x + faces[i].width, faces[i].y + faces[i].height);

        Point pt2(faces[i].x, faces[i].y);

        rectangle(img, pt1, pt2, cvScalar(0,255, 255, 0), 1, 8, 0);

    }

    //print the output

    imshow("FaceRecognition", img);

    waitKey(0);

    return 0;

}

效果圖:


關於函式:CV_WRAP void detectMultiScale( InputArray image,

                          CV_OUT std::vector<Rect>& objects,

                          double scaleFactor = 1.1,

                          int minNeighbors = 3,int flags = 0,

                          Size minSize =Size(),

                          Size maxSize =Size() );

說明如下:

 @brief Detects objects of different sizes inthe input image. The detected objects are returned as a listof rectangles.

    @param image Matrix of the type CV_8U containingan image where objects are detected.

    @param objects Vector of rectangles whereeach rectangle contains the detected object, therectangles may be partiallyoutside the original image.

    @param scaleFactor Parameter specifying howmuch the image size is reduced at each image scale.

    @param minNeighbors Parameter specifyinghow many neighbors each candidate rectangle should haveto retain it.

    @param flags Parameter with the samemeaning for an old cascade as in the functioncvHaarDetectObjects. It is not used for a new cascade.

    @param minSize Minimum possible objectsize. Objects smaller than that are ignored.

@param maxSize Maximum possible object size.Objects larger than that are ignored.

原始碼下載:http://download.csdn.net/detail/cracent/9492682