Running opencv using java error

I started learning OpenCV using the JAVA language. I tried to run a very simple code, borrowed from http://docs.opencv.org/2.4.4-beta/doc/tutorials/introduction/desktop_java/java_dev_intro.html

and using eclipse (JUNO). When I run the following codes

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.highgui.Highgui; import org.opencv.objdetect.CascadeClassifier; // // Detects faces in an image, draws boxes around them, and writes the results // to "faceDetection.png". // class DetectFaceDemo { public void run() { System.out.println("\nRunning DetectFaceDemo"); // Create a face detector from the cascade file in the resources // directory. CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("/lbpcascade_frontalface.xml").getPath()); Mat image = Highgui.imread(getClass().getResource("/lena.png").getPath()); // Detect faces in the image. // MatOfRect is a special container class for Rect. MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); // Draw a bounding box around each face. for (Rect rect : faceDetections.toArray()) { Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0)); } // Save the visualized detection. String filename = "faceDetection.png"; System.out.println(String.format("Writing %s", filename)); Highgui.imwrite(filename, image); } } public class HelloOpenCV { public static void main(String[] args) { System.out.println("Hello, OpenCV"); // Load the native library. System.loadLibrary("opencv_java245"); new DetectFaceDemo().run(); } } 

I get

 Hello, OpenCV Running DetectFaceDemo Exception in thread "main" java.lang.NullPointerException at DetectFaceDemo.run(HelloOpenCV.java:20) at HelloOpenCV.main(HelloOpenCV.java:48) 

where **

 20 CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("lbpcascade_frontalface.xml").getPath()); 48 new DetectFaceDemo().run(); 

**

I am new to this area and do not know how to get to this error. I need your help.

+4
source share
2 answers

getClass (). getResource () loads resources from the class path, and if the file is not found, it returns null. So in your case it seems that the file is not loaded, and when you call getPath (), you get a null pointer exception. You need to check that no matter how you build, the xml file is copied to where the class files are compiled. Or just make sure the xml file is present in your classpath.

Hope this helps!

+2
source

pass the full path Mat image = Highgui.imread ("/Users/test/workspace/OpenCV/bin/lena.png");

0
source

Source: https://habr.com/ru/post/1482766/