This tutorial shows how to detect one or more faces with ViSP. Face detection is performed using OpenCV Haar cascade capabilities that are used in vpDetectorFace class. At least OpenCV 2.2.0 or a more recent version is requested.
In the next sections you will find examples that show how to detect faces in a video, or in images acquired by a camera connected to your computer.
Note that all the material (source code and video) described in this tutorial is part of ViSP source code and could be downloaded using the following command:
The following example also available in tutorial-face-detector.cpp allows to detect faces in an mpeg video located near the source code. The Haar cascade classifier file requested by OpenCV is also provided in the same folder as the source code.
Then we enter in the while loop where for each new image, the try to detect one or more faces:
bool face_found = face_detector.detect(I);
If a face is detected, vpDetectorFace::detect() returns true. It is then possible to retrieve the number of faces that are detected:
text << "Found " << face_detector.getNbObjects() << " face(s)";
For each face, we have access to its location using vpDetectorFace::getPolygon(), its bounding box using vpDetectorFace::getBBox() and its identifier message using vpDetectorFace::getMessage().
for (size_t i = 0; i < face_detector.getNbObjects(); i++) {
When more than one face is detected, faces are ordered from the largest to the smallest. That means that vpDetectorFace::getPolygon(0), vpDetectorFace::getBBox(0) and vpDetectorFace::getMessage(0) return always the characteristics of the largest face.
Face detection from a camera
This other example also available in tutorial-face-detector-live.cpp shows how to detect one or more faces in images acquired by a camera connected to your computer.
The usage of this example is similar to the previous one. Just run
$ ./tutorial-face-detector-live
Additional command line options are available to specify the location of the Haar cascade file and also the camera identifier if more than one camera is connected to your computer:
$ ./tutorial-face-detector-live --help
Usage: ./tutorial-face-detector-live [--device <camera device>] [--haar <haarcascade xml filename>] [--help]
The source code of this example is very similar to the previous one except that here we use camera framegrabber devices (see Tutorial: Image frame grabbing). Two different grabber may be used:
If ViSP was build with Video For Linux (V4L2) support available for example on Fedora or Ubuntu distribution, VISP_HAVE_V4L2 macro is defined. In that case, images coming from an USB camera are acquired using vpV4l2Grabber class.
If ViSP wasn't build with V4L2 support, but with OpenCV we use cv::VideoCapture class to grab the images. Notice that when images are acquired with OpenCV there is an additional conversion from cv::Mat to vpImage.