Home > Java > javaTutorial > body text

How to detect faces in images using Java OpenCV library?

WBOY
Release: 2023-08-20 09:09:08
forward
850 people have browsed it

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");
   }
}
Copy after login

Input

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

Output

No of faces detected: 3
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template