Ask Your Question

Revision history [back]

Gives wrong number of faces

I am using following code to detect face. Basically in my ai project i want to add functionality like admin can only upload face image not other than that. so the alert will be displayed if the profile image contains more than two faces and image does not contain any face but when i use image which does not contain any face it gives wrong output like 1 face or 9 face detected.

package ai_project;

import javax.swing.JOptionPane;

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 FaceDetector {

public static void main(String[] args) {

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    System.out.println("\nRunning FaceDetector");

    CascadeClassifier faceDetector = new CascadeClassifier();
   // Mat image = Imgcodecs
     //       .imread(FaceDetector.class.getResource("shekhar.JPG").getPath());

    if(!faceDetector.load("F:\\haarcascade_frontalface_alt.xml"))
        System.out.println("haarcascade_frontalface_alt.xml not found!");
    System.out.println("Loading analyse method Done!");
    Mat image = Imgcodecs.imread("F:\\c.JPG");
    System.out.println("hello 2");

    MatOfRect faceDetections = new MatOfRect();
    System.out.println("hello 2.2");
    faceDetector.detectMultiScale(image, faceDetections);
    System.out.println("hello 3");
    if(faceDetections.toArray().length!=1)
    {
        JOptionPane.showMessageDialog(null, "you are trying to upload wrong image");
    }
    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
    System.out.println("hello 4");
    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, 255, 0));
    }
    System.out.println("hello 5");
    String filename = "ouput.png";
    System.out.println(String.format("Writing %s", filename));
    Imgcodecs.imwrite(filename, image);
}

}

for example i am using following image for testing and it gives 1 face detected image description