Webcam frame not working on macbook in Java

I just waded through my first install of opencv on my mac air, and I've been trying to get input out of the camera built into the screen. So far as I can tell, I have the libraries running in Eclipse correctly, as I no longer get massive errors every time I try to call any of the methods. However, what is happening now is a problem with the webcam, which seems to be correctly created with 0 passed to the constructor (nothing else from 1-50 returns anything, and -1 I believe is the default). But when I try to use it to get a frame back, the mat is always empty.

As far as I can tell, it seems like I'm able to access the camera, but theres some sort of disconnect going on between the code and being able to actually activate the camera to take video. If it matters at all, the light that shows the camera active for most programs has always remained inactive.

The relevant code is posted below. I would greatly appreciate any insight you may have or examples of code working in java to get an image out of a webcam for use in a java gui. Thanks!

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    VideoCapture camera = new VideoCapture(0);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }


    //camera.open(0); //Useless
    if(!camera.isOpened()){
        System.out.println("Camera broken");
    }
    else{
        System.out.println("Camera OK!");
    }

    Mat frame = new Mat();

    camera.read(frame);

    System.out.println("width:" + frame.width());

    Highgui.imwrite("myframe.png", frame);

The output is:

Camera OK!
width:0
libpng warning: Image width is zero in IHDR
libpng warning: Image height is zero in IHDR
libpng error: Invalid IHDR data
Cleaned up camera.

it's been a while since this question was asked, but since I had essentially the same problem, I will post a solution (found here) (it's a rather simple fix actually for a stupid problem):

The camera needs time to initialize (not sure what the gory hardware details are, but there you go). To fix it I simply added Thread.sleep(1000), and it started working. A slightly better fix may be to wrap this in a loop which retries every 1000ms or so until the returned Mat is not empty.

Hope someone benefits from this :-)

EDIT: I should have read your code first. Silly me, apologies. The problem seemed very similar to mine, so I assumed it was the same.

链接地址: http://www.djcxy.com/p/83778.html

上一篇: 在qlabel上显示openCv视频的奇怪麻烦

下一篇: Webcam框架在Java中不能用于macbook