Home >Java >javaTutorial >How to detect faces in images using Java OpenCV library?

How to detect faces in images using Java OpenCV library?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBforward
2023-08-20 09:09:08903browse

The CascadeClassifier class is used to load the classifier file and detect the required objects in the image.

The detectMultiScale() method of this class can detect multiple objects of different sizes. This method accepts −

  • A Mat class object used to save the input image.

  • A MatOfRect class object used to store detected faces.

To get the number of faces in the image −

  • Use the CascadeClassifier class to load the lbpcascade_frontalface.xml file.

  • Call the detectMultiScale() method.

  • Convert the MatOfRect object to an array.

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

Example

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",
      faceDetections.toArray().length));
      //Drawing boxes
      for (Rect rect : faceDetections.toArray()) {
         Imgproc.rectangle(
            src,
            new Point(rect.x, rect.y),
            new Point(rect.x + rect.width, rect.y + rect.height),
            new Scalar(0, 0, 255),
            3
         );
      }
      //Writing the image
      Imgcodecs.imwrite("D:\Images\face_Detection.jpg", src);
      System.out.println("Image Processed");
   }
}

Input

如何使用Java OpenCV库在图像中检测人脸?

Output

No of faces detected: 3

The above is the detailed content of How to detect faces in images using Java OpenCV library?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete