Ask Your Question
0

NullPointerException in face-detection

asked 2018-05-29 00:48:49 -0600

nikshita gravatar image

updated 2018-05-29 00:52:37 -0600

berak gravatar image

Hi! i am trying to crop a detected face from an image using the code below and i am getting the error as Exception in thread "main" java.lang.NullPointerException. Kindly help.

Here is the code:

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.LocatorEx.Snapshot;
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.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class FaceDetector {
    private static Mat cropImage;

public static void main(String[] args)throws Exception {
    int x = 0,y = 0,height = 0,width = 0;

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

//CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource("haarcascade_frontalface_alt.xml").getPath());
   CascadeClassifier faceDetector = new CascadeClassifier(Snapshot.class.getResource("haarcascade_frontalface_alt.xml").getPath().substring(1));
Mat image = Imgcodecs.imread("C:\\image.jpg");
        MatOfRect face_Detections = null;
faceDetector.detectMultiScale(image, face_Detections);
System.out.println(String.format("Detected %s faces",  face_Detections.toArray().length));
Rect rectCrop=null;
for (Rect rect : face_Detections.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));
    rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
}



 Mat image_roi = new Mat(image,rectCrop);
  Imgcodecs.imwrite("C:\\cropimage_912.jpg",image_roi);



}}

And the error is:

 Exception in thread "main" java.lang.NullPointerException

Running FaceDetector
    at FaceDetector.main(FaceDetector.java:25)
C:\Users\sss\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2018-05-29 00:54:17 -0600

berak gravatar image

updated 2018-05-29 00:59:49 -0600

Rect rectCrop=null;

it can and will happen, that NO face will be detected. you have to take care for this:

//only write an image IF we have a valid rect !
if (rectCrop != null) {
  Mat image_roi = new Mat(image,rectCrop);
  Imgcodecs.imwrite("C:\\cropimage_912.jpg",image_roi);
}
edit flag offensive delete link more

Comments

Thanks! i got the point.

nikshita gravatar imagenikshita ( 2018-05-29 05:22:29 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-05-29 00:48:49 -0600

Seen: 256 times

Last updated: May 29 '18