Search code examples
javaopencvvideo-capture

Java, OpenCV VideoWriter isOpened returns always false


I am using Java OpenJdk 14.0.2 and OpenCV-440 as well while everything is running on Windows 10. My JavaFX application is supposed to capture the frames of a webcam (or any other video device) and store the frames as a video file, for example avi.

Here is my code:

   public void run() {

        Mat frame = new Mat();
        VideoCapture videoCapture = new VideoCapture(0);
        videoCapture.read(frame);

        Size frameSize = new Size((int) videoCapture.get(Videoio.CAP_PROP_FRAME_WIDTH), (int) videoCapture.get(Videoio.CAP_PROP_FRAME_HEIGHT));
        int fourcc = VideoWriter.fourcc('x', '2','6','4');
        VideoWriter writer = new VideoWriter();
        //if myuniquefile%02d.jpg is using any kind of video extension instead, it is not working (e.g. avi)
        writer.open("images/myuniquefile%02d.jpg", fourcc,
                videoCapture.get(Videoio.CAP_PROP_FPS), frameSize, true);
        
        while (isRunning) {
            if (videoCapture.read(frame)) {
                writer.write(frame);
            }
        }
        videoCapture.release();
        writer.release();
    }

This code is working fine, but as soon I change the ".jpg" to an extension like .avi it is not working any longer. For the code above VideoWriter.isOpened() returns true and for the same code with ".avi" it returns false. I tried a lot of combinations of file extensions and codecs (VideoWriter.fourcc), but it is never open.

Lets go ahead to my settings, I am using Intellij (2020.1.2) and openCV 440 is linked this way: enter image description here

The only additional lib is the javafx-sdk-14.0.2.1

I was going with this example in the first place, but it was never working that way for me. I am very grateful for any suggestions

BR Michael


Solution

  • Because you are creating H264 codec VideoWriter but trying to get .avi codec video.

    Here is the correct codec format for .avi or .mp4:

    int fourcc = VideoWriter.fourcc('M', 'J','P','G');
    writer.open("images/out.avi", fourcc,
                    videoCapture.get(Videoio.CAP_PROP_FPS), frameSize, true);
    

    Here is similar problem and also opencv documentation for VideoWriter