Search code examples
javaopencvjavacv

How to save face and recognized using OpenCV and Java?


I am totally new to OpenCV. I am able to detect the face from webCam. I am little bit confused how to save detected face, how to save and recognized if again that person come again in front of camera.

Detection code

private void detectAndDisplay(Mat frame)
{
    MatOfRect faces = new MatOfRect();
    Mat grayFrame = new Mat();

    // convert the frame in gray scale
    Imgproc.cvtColor(frame, grayFrame, Imgproc.COLOR_BGR2GRAY);
    // equalize the frame histogram to improve the result
    Imgproc.equalizeHist(grayFrame, grayFrame);

    // compute minimum face size (20% of the frame height, in our case)
    if (this.absoluteFaceSize == 0)
    {
        int height = grayFrame.rows();
        if (Math.round(height * 0.2f) > 0)
        {
            this.absoluteFaceSize = Math.round(height * 0.2f);
        }
    }

    // detect faces
    this.faceCascade.detectMultiScale(grayFrame, faces, 1.1, 2, 0 | Objdetect.CASCADE_SCALE_IMAGE,
            new Size(this.absoluteFaceSize, this.absoluteFaceSize), new Size());

    // each rectangle in faces is a face: draw them!
    Rect[] facesArray = faces.toArray();
    for (int i = 0; i < facesArray.length; i++)
        Imgproc.rectangle(frame, facesArray[i].tl(), facesArray[i].br(), new Scalar(0, 255, 0), 3);

}

Solution

  • I got solution

          for (Rect rect : facesArray) {
                Imgproc.rectangle(frame, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
                        new Scalar(0, 255, 0)); // frame is Mat
                rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
    
                Mat image_roi = new Mat(frame,rectCrop);
                 Imgcodecs.imwrite("./face"+ i +".jpg",image_roi);
                 i++;
            }
    

    Now , I can cropped multiple faces