Search code examples
javamacosopencvwebcam

OpenCV 2.4.4 Java - Grab Webcam picture/stream (OSX)


I'm new in the world of Stackoverflow and in OpenCV programming. I've made some projects with OpenCV Bindings for Java (the opencv.org officials, not JavaCV), like object recognition through ORB and SURF features, working with images. Everything ok. Now I'm moving to object recognition in video streams. I want to grab stream from webcam and apply object recognition. I'm not a Java guru, so I found in OpenCV the VideoCapture class, but I'm not able to obtain pictures from the camera.

I'm running my project in Eclipse with OpenCV 2.4.4 bindings, in OSX Mountain Lion.

The result in the console:

Hello, OpenCV
Camera OK?
Frame Obtained
Captured Frame Width 0
Invalid memory access of location 0x7fae00000000 rip=0x7fff8b4c5263

The code:

import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;

public class Webcam {

    public static void main (String args[]){

    System.out.println("Hello, OpenCV");
    // Load the native library.
    System.loadLibrary("opencv_java244");

    VideoCapture camera = new VideoCapture(0);
    camera.open(0); //Useless
    if(!camera.isOpened()){
        System.out.println("Camera Error");
    }
    else{
        System.out.println("Camera OK?");
    }

    Mat frame = new Mat();

    //camera.grab();
    //System.out.println("Frame Grabbed");
    //camera.retrieve(frame);
    //System.out.println("Frame Decoded");

    camera.read(frame);
    System.out.println("Frame Obtained");

    /* No difference
    camera.release();
    */

    System.out.println("Captured Frame Width " + frame.width());

    Highgui.imwrite("camera.jpg", frame);
    System.out.println("OK");
    }
}

Solution

  • The problem was simply that camera need time to initialize. I've added

    Thread.sleep(1000);
    

    after

    VideoCapture camera = new VideoCapture(0);