0

I've been trying to make a small simple program that retrieves an image from the webcam and displays it on a gui. But when I read from the videostream the read() command returns a nullpointerexception. Even though I have a simple class as such:

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

The exception i get is as follows:

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)

I'm using OpenCV 3.1.0

To make sure that the camera was initialized and not null, I changed the code to this:

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

Where the output was:

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
JSON C11
  • 11,272
  • 7
  • 78
  • 65
Zamor
  • 59
  • 1
  • 9
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Nikolas Charalambidis Oct 02 '16 at 16:12

1 Answers1

0

As i later discovered, it was the Mat object that had to be initialized before i read a frame into it, like so:

test = new Mat();
Zamor
  • 59
  • 1
  • 9