java - 现有路径上的 NullPointerException

标签 java opencv path classification

我在创建分类器时遇到问题。我的现有路径导致 NullPointerException。我在 Eclipse 中使用 OpenCV 2.4.11。操作系统是 Windows,这就是我在文件夹之间添加另一个反斜杠的原因。当我在文件资源管理器中插入带有单反斜杠的路径时,它会正确打开 XML 文件。我的代码如下所示:

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        System.out.println("\nRunning FaceDetector");
        String path = "C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
        System.out.println("path:" + path);
        CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource(path).getPath());

输出是:

    Running FaceDetector

    path:C:\Users\Juergen\OpenCV\opencv\sources\data\haarcascades\haarcascade_frontalface_alt.xml
    Exception in thread "main" java.lang.NullPointerException
        at FaceDetector.main(FaceDetector.java:24)

代码基于以下instruction .

对于抛出 NullPointerException 的原因的任何想法都表示赞赏。

谢谢

最佳答案

当我们查看 Java API 时,我们会发现:

https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
  • Otherwise, the absolute name is of the following form:

    modified_package_name/name

因此你必须在你的绝对路径前加一个'/':

String path = "/C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";

而且您还应该摆脱 windows 文件分隔符。 Java 理解 unix 文件分隔符并知道如何在 windows 系统上处理它:

String path = "/C:/Users/Juergen/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";

I replaced my string by Yours, nothing changed. Still get a NullPointerException. The check

 if (!new File(path).exists()) { throw new FileNotFoundException("Yikes!");}

does not throw any Exception – Jürgen K

然后从 *.class.getResource(path) 你得到一个 URL 和从 URLgetPath( ) 方法你会得到一个 String ,它很可能与你的原始字符串相同。

您是否尝试过直接使用它(使用前导“/”)?

关于java - 现有路径上的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053140/

相关文章:

Java:读取特定格式的字符串

c++ - Matlab 到 OpenCV 的转换 - 优化?

java - 64 位整数与 32 位整数具有相同的限制

OpenCV 匹配图像

python - OpenCV显示带有黑条的额外窗口?

python - 使用 Python/PIL 裁剪图像的非对称区域

python - 如何将 x、y、z 坐标数组转换为 numpy 中的 3D 路径

java - 如何将 `java` 添加到 Vista 上的命令路径?

java - 迭代时删除和添加对象到列表

java - Selenium WebDriver StaleElementReferenceException