How to open and process a video file like .mpeg or .avi using openCV's VideoCapture method in Java

Vishnu picture Vishnu · Sep 24, 2013 · Viewed 7.2k times · Source
    import org.opencv.core.Core;        
    import org.opencv.core.Mat;        
    import org.opencv.core.Size;        
    import org.opencv.highgui.Highgui;        
    import org.opencv.highgui.VideoCapture;        
    import org.opencv.imgproc.Imgproc;        

    public class Video        
    {        
        public static void main(String[] args)        
        {        
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);        

    VideoCapture cap = new VideoCapture(0);

    cap.open(1);

    if(!cap.isOpened())
    {
        System.out.println("No camera");
    }

    else
    {
        System.out.println("Yes. Camera");
    }

    Mat frame = new Mat();
    cap.retrieve(frame);

    Highgui.imwrite("me1.jpg", frame);
    Mat frameBlur = new Mat();

    Imgproc.blur(frame, frameBlur, new Size(5,5));
    Highgui.imwrite("me2-blurred.jpg", frameBlur);

    Imgproc.GaussianBlur(frame, frameBlur, new Size(25, 25), 20);
    Highgui.imwrite("me3-blurred.jpg", frameBlur);

    cap.release();
        }
    }

I have used this code to open my Camera device and capture 3 different frames and made some operations on it. But, I couldn't open a file like .avi/.mpg/.mp4 etc., using {n_open} method of VideoCapture. There is a method in the VideoCapture implementation here. But because its a private and native method, that method can't be accesses using VideoCapture's object.

Could some one help how to do that using pure OpenCV 2.4.6 and Java
(Please dont suggest solution using Processing libraries)

Answer

lukk picture lukk · Jan 17, 2014

Take a look on OpenCV 2.4.8. The VideoCapture API has been extended of public VideoCapture(String filename) method. The question remains why this feature has been implemented so late.

If using of recent version of OpenCV isn't acceptable for you for some reason, you have several options:

  • Rebuild OpenCV by yourself with this method marked as public

  • HACKY ONE: Make your copy of VideoCapture class (or extend original one and play with reflection) with public VideoCapture(String) constructor. Then give support for native method private static native long n_VideoCapture(java.lang.String filename) by creating your own DLL using C++ OpenCV API. (Tested!)