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
Face detectors don't have 100% detection accuracy, so yes, you may have some false positives (more likely is your input is complex like the shown image). However, given your purpose, I understand that profile images will have fixed dimensions, and you can restrict the min and max size for the faces detections, reducing probability of false positives.
there is a 'minNeighbours' param in the detectMultiScale function. try to increase that, until you start missing positives.