如何用java和OpenCV关闭相机?

时间:2013-11-08 11:13:17

标签: java opencv camera

我是StackOverflow和OpenCV编程领域的新手。 我用一些Java代码打开了相机,因为相机的灯亮了,但是当我试图关闭相机时,我失败了。

代码:

public class camera {

    public static void main(String[] args)  {
        System.loadLibrary("opencv_java244");
        VideoCapture camera = new VideoCapture(0);
        if (camera.isOpened())
             System.out.println("Camera is ready!");
        else {
             System.out.println("Camera Error!");
             return;
        }
        Mat newMat = new Mat();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            //e.printStackTrace();
        }

        camera.read(newMat);
        Highgui.imwrite("testfile.jpg", newMat);

        camera.release();
        if (camera.isOpened()) {
            System.out.println("Camera is running!");
        }
        else {
            System.out.println("Camera closed!");
        }
    }
}

结果:

Camera is ready!
Camera closed!

我真的得到了照片,但灯还在! 附:每次当我尝试打开相机时,我的电脑都会打开一个名为YouCam的驱动软件,我必须手动将其关闭以释放相机。

1 个答案:

答案 0 :(得分:0)

尝试使用capture.retrieve()而不是capture.read()。这是一个快照,它对我有用,甚至不使用Thread.sleep()     VideoCapture capture = new VideoCapture(0);

    if (!capture.isOpened()) {
        imagePanel.add(new JLabel("Oops! Your camera is not working!"));
        return;
    } 
    Mat frame = new Mat();
    capture.retrieve(frame);
    frame = FaceDetector.detect(frame);
    BufferedImage image = GestureUtil.matToBufferedImage(frame);*/
    imagePanel.setImage(image);
    imagePanel.repaint();
    String window_name = "Capture - Face detection.jpg";
    Highgui.imwrite(window_name, frame);

    capture.release();

我和Swing一起使用它。但是,您可以忽略挥杆代码。希望这有帮助