How to detect faces in an image using Java OpenCV library?

The CascadeClassifier class of is used to load the classifier file and detects the desired objects in the image.

The detectMultiScale() of this class detects multiple objects of various sizes. This method accepts −

  • An object of the class Mat holding the input image.

  • An object of the class MatOfRect to store the detected faces.

To get the number of faces in the image −

  • Load the lbpcascade_frontalface.xml file using the CascadeClassifier class.

  • Invoke the detectMultiScale() method.

  • Convert the MatOfRect object to an array.

  • The length of the array is the number of faces in the image.


import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
public class FaceDetection {
   public static void main (String[] args) {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the Image from the file
      String file ="D:\Images\faces.jpg";
      Mat src = Imgcodecs.imread(file);
      //Instantiating the CascadeClassifier
      String xmlFile = "lbpcascade_frontalface.xml";
      CascadeClassifier classifier = new CascadeClassifier(xmlFile);
      //Detecting the face in the snap
      MatOfRect faceDetections = new MatOfRect();
      classifier.detectMultiScale(src, faceDetections);
      System.out.println(String.format("Detected %s faces",
      //Drawing boxes
      for (Rect rect : faceDetections.toArray()) {
            new Point(rect.x, rect.y),
            new Point(rect.x + rect.width, rect.y + rect.height),
            new Scalar(0, 0, 255),
      //Writing the image
      Imgcodecs.imwrite("D:\Images\face_Detection.jpg", src);
      System.out.println("Image Processed");



No of faces detected: 3