How can I close the camera with java and OpenCV?

2019-07-27 03:47发布

问题:

I'm new in the world of StackOverflow and in OpenCV programming. I've opened my camera with some Java code and it worked because the light of camera was on, but when I tried to close the camera, I failed.

Code:

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!");
        }
    }
}

result:

Camera is ready!
Camera closed!

I really got the picture, but the light was still on! P.S. Everytime when I try to open my camera, my computer will open a drive software named YouCam, and I must close it manually to release the camera.

回答1:

Try capture.retrieve() instead of capture.read(). Here is a snapshot which works for me without using even 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();

I have using this along with Swing. However, you can ignore swing code. Hope this helps