Home > Java > javaTutorial > body text

Face detection and recognition technology implemented using Java

WBOY
Release: 2023-06-18 09:08:12
Original
2574 people have browsed it

With the continuous development of artificial intelligence technology, face detection and recognition technology has become more and more widely used in daily life. Face detection and recognition technologies are widely used in various occasions, such as face access control systems, face payment systems, face search engines, etc. As a widely used programming language, Java can also implement face detection and recognition technology. This article will introduce how to use Java to implement face detection and recognition technology.

1. Face detection technology

Face detection technology refers to the technology that detects faces in images or videos. In Java, you can use OpenCV, an open source computer vision library, to implement face detection technology. OpenCV is a cross-platform computer vision library with the advantages of efficiency, ease of use, and scalability.

The following are the basic steps to implement face detection technology in Java using OpenCV:

  1. Import the OpenCV library: You can use Maven or manual download to import the OpenCV library.
  2. Load Haar classifier: Haar classifier is a feature-based classifier commonly used to detect faces. In Java, Haar classifier models can be loaded using the CascadeClassifier class.
  3. Loading images: You can use the Imgcodecs class to load image files or the VideoCapture class to load video streams.
  4. Detect faces: Use the detectMultiScale method in the CascadeClassifier class to detect faces. This method will return the position and size of the face in the image.
  5. Drawing detection results: Use the rectangle method in the Imgproc class to draw the detected face position in the image.

The following is a sample code that uses OpenCV to implement face detection in Java:

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class FaceDetector {
    public static void main(String[] args) {
        // Load OpenCV library
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        // Load Haar classifier
        CascadeClassifier faceDetector = new CascadeClassifier("path/to/haarcascade_frontalface_default.xml");

        // Load image
        Mat image = Imgcodecs.imread("path/to/image.jpg");

        // Detect faces
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);

        // Draw rectangles around detected faces
        for (Rect rect : faceDetections.toArray()) {
            Imgproc.rectangle(image, new Point(rect.x, rect.y),
                    new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 0, 255), 2);
        }

        // Save image with detected faces
        Imgcodecs.imwrite("path/to/result.jpg", image);
    }
}
Copy after login

In the above code, OpenCV's Core, Imgcodecs, Imgproc and CascadeClassifier classes are used. Among them, the CascadeClassifier class loads the Haar classifier model, while the Imgcodecs and Imgproc classes are used to load images and draw detection results. Use this code to detect and locate faces in an image.

2. Face recognition technology

Face recognition technology refers to comparing the input face with the faces in the face database when the face database is known, and A technique for finding faces that are similar to them. In Java, you can use the FaceRecognizer class for face recognition. FaceRecognizer is a class specifically used for face recognition in OpenCV. It encapsulates some recognition algorithms, such as Eigenfaces, Fisherfaces, LBPH, etc.

The following are the basic steps to implement face recognition technology in Java using FaceRecognizer:

  1. Load the face library: You can use the Imgcodecs class to load face images in the face library.
  2. Extract facial features: Use the train method in the FaceRecognizer class to train all faces in the face database to generate facial features.
  3. Recognize faces: Use the predict method in the FaceRecognizer class to recognize the input face. The recognition results are similarity and identifier.
  4. Display recognition results: You can use the Imgproc class to draw the recognition results in the image.

The following is a sample code that uses FaceRecognizer to implement face recognition in Java:

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;
import org.opencv.face.FaceRecognizer;
import org.opencv.face.LBPHFaceRecognizer;

public class FaceRecognizer {
    public static void main(String[] args) {
        // Load OpenCV library
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        // Load Haar classifier
        CascadeClassifier faceDetector = new CascadeClassifier("path/to/haarcascade_frontalface_default.xml");

        // Load face recognizer
        FaceRecognizer recognizer = LBPHFaceRecognizer.create();

        // Load all images from the directory
        for (int i = 1; i <= 10; i++) {
            String fileName = "path/to/database/" + i + ".jpg";
            Mat image = Imgcodecs.imread(fileName);

            // Convert image to grayscale
            Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2GRAY);

            // Detect faces
            MatOfRect faceDetections = new MatOfRect();
            faceDetector.detectMultiScale(image, faceDetections);

            // Extract face features
            Mat face = new Mat();
            face = image.submat(faceDetections.toArray()[0]);
            recognizer.train(face, new Mat());
        }

        // Load input image
        Mat inputImage = Imgcodecs.imread("path/to/input/image.jpg");
        Imgproc.cvtColor(inputImage, inputImage, Imgproc.COLOR_BGR2GRAY);

        // Detect face
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(inputImage, faceDetections);

        // Recognize face
        Mat inputFace = new Mat();
        inputFace = inputImage.submat(faceDetections.toArray()[0]);
        int[] label = new int[1];
        double[] confidence = new double[1];
        recognizer.predict(inputFace, label, confidence);

        // Draw rectangle and name of recognized person
        Imgproc.rectangle(inputImage, faceDetections.toArray()[0].tl(),
                faceDetections.toArray()[0].br(), new Scalar(0, 0, 255), 2);
        Imgproc.putText(inputImage, "Person " + label[0], faceDetections.toArray()[0].tl(),
                Imgproc.FONT_HERSHEY_PLAIN, 1, new Scalar(0, 255, 0), 2);

        // Show and save result
        Imgcodecs.imwrite("path/to/result.jpg", inputImage);
    }
}
Copy after login

In the above code, the Haar classifier is first used to detect faces and extract them from the face database Load face images for training and generate facial features. Then, input an image to be recognized, extract the faces appearing in it, and use the FaceRecognizer class to recognize them. Finally, the results of detection and recognition are plotted in the image using the Imgproc class. A simple face recognition system can be implemented using this code.

Summary

This article introduces how to use Java to implement face detection and recognition technology. For Java developers, mastering these technologies can implement face-based applications, such as face access control systems, face payment systems, face search engines, etc. Although the OpenCV library is used in the sample code, there are many similar computer vision libraries, such as JavaCV, BoofCV, etc. Interested readers can try to use these libraries to implement face detection and recognition technology.

The above is the detailed content of Face detection and recognition technology implemented using Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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