首页 > 解决方案 > 如何在 java OpenCV 上循环我的网络摄像头流

问题描述

我一直在尝试在Java上使用OpenCV(我对它比较陌生),但它似乎比其他语言复杂得多。虽然像 python 这样的语言有imshow来循环网络摄像头,但 java 没有这个选项。

我想要做的只是运行一个将加载 opencv 的文件,并使用它在 Jframe 中处理的图像,以便不断显示来自相机(我的网络摄像头)的更新图像(如视频)。

我可以获取代码来拍摄快照,但是每当我尝试循环超过这个次数时,我仍然只能得到一个快照。

这是代码:`System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    // Instantiating the VideoCapture class (camera:: 0)
    VideoCapture capture = new VideoCapture(0);

    // Reading the next video frame from the camera
    Mat matrix = new Mat();

    //Instantiate JFrame 
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    //When we find the user close our window.
            frame.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                    System.out.println("Frame closing...");
                    frame.setVisible(false);
                    capture.release();
                }
            });

    // Instantiating the imgcodecs class
    Imgcodecs imageCodecs = new Imgcodecs();
    // Where we will save the image.
    String file = "C:/Users/Jim/Documents/Samples/sample.jpg";

    // If camera is opened
    if (capture.isOpened()) {
        frame.setVisible(true);

        // While there is next video frame
        while (capture.read(matrix)) {
            System.out.println("Retrieving Frames...");
            capture.read(matrix);

            // Creating BuffredImage from the matrix
            BufferedImage image = new BufferedImage(matrix.width(),
                    matrix.height(), BufferedImage.TYPE_3BYTE_BGR);

            //Saving the mat to an image.
            imageCodecs.imwrite(file, matrix);
            imageCodecs.imread(file);

            ImageIcon icon = new ImageIcon(file); // Inserts the image icon
            JLabel label = new JLabel(icon); //Label of ImageIcon

            frame.getContentPane().add(label);
            frame.pack();   
        }
    }`

请帮我找到我需要添加什么来更新图像,还有什么是不必要的。

标签: javaswingopencvjframeopencv3.0

解决方案


推荐阅读