使用java中的OpenCV lib读取框架时出现问题

时间:2016-10-02 16:08:16

标签: java opencv

我一直试图制作一个简单的小程序,从网络摄像头中检索图像并将其显示在gui上。但是当我从视频流中读取时,read()命令返回nullpointerexception。即使我有一个简单的类:

    import org.opencv.videoio.VideoCapture;
    import org.opencv.core.Mat;

public class Camera {

private VideoCapture camera;
private Mat test;

public Camera(){
    this.camera = new VideoCapture(0);
    this.camera.read(test);
}

我得到的例外情况如下:

Exception in thread "main" java.lang.NullPointerException
at org.opencv.videoio.VideoCapture.read(VideoCapture.java:152)
at sortingbot.Camera.<init>(Camera.java:26)
at sortingbot.Main.main(Main.java:39)

我正在使用OpenCV 3.1.0

为了确保相机已初始化而非null,我将代码更改为:

this.camera = new VideoCapture(0);
    if(camera == null){
        System.err.print("Ok, thats something");
    }
    else{
        if(!camera.isOpened()){
            System.err.print("Camera wasnt initialized");
        }
        else{
            System.out.print(("Why does this happen then? \n"));
            camera.read(test);
        }
    }

输出结果为:

Why does this happen then? 
Exception in thread "main" java.lang.NullPointerException
at org.opencv.videoio.VideoCapture.read(VideoCapture.java:152)
at sortingbot.Camera.<init>(Camera.java:35)
at sortingbot.Main.main(Main.java:39)
C:\Users\User\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

1 个答案:

答案 0 :(得分:0)

正如我后来发现的那样,Mat对象必须在我读入框架之前进行初始化,如下所示:

test = new Mat();