Java运行OpenCV_使用java错误运行opencv

本文档描述了在尝试使用Java运行OpenCV时遇到的NullPointerException问题。问题出现在尝试加载lbpcascade_frontalface.xml文件时,由于文件未正确地包含在类路径中导致。解决方案包括检查文件是否在编译后的类文件位置或确保类路径包含该XML文件。
摘要由CSDN通过智能技术生成

我已经开始使用JAVA语言学习OpenCV.我试图运行从中借来的非常简单的代码

并使用eclipse(JUNO).当我运行以下代码时

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();

}

}

我明白了

Hello, OpenCV

Running DetectFaceDemo

Exception in thread "main" java.lang.NullPointerException

at DetectFaceDemo.run(HelloOpenCV.java:20)

at HelloOpenCV.main(HelloOpenCV.java:48)

哪里

**

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

48 new DetectFaceDemo().run();

**

我是这个领域的新手,不知道如何克服这个错误.我需要你的帮助.

最佳答案 getClass().getResource()从类路径加载资源,如果找不到文件,它将返回null.所以在你的情况下似乎没有加载文件,当你调用getPath()时,你会得到空指针异常.您需要检查,无论您正在构建,xml文件都会被复制到编译类文件的位置.或者只是确保类路径中存在xml文件.

希望能帮助到你!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值