JavaGUI读取摄像头并1秒截图一次

java 文章 2022-03-17 14:32 0 全屏看文
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_imgcodecs;
import org.bytedeco.javacv.*;

import javax.swing.*;

public class TestRtsp {

    public static OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();

    public static void main(String[] args){
        String url = "rtsp://账号:密码@IP/h264/ch1/main/av_stream";
        FFmpegFrameGrabber grabber = null;
        try {
            grabber = FFmpegFrameGrabber.createDefault(url);
            grabber.setOption("rtsp_transport","tcp");
            grabber.setImageWidth(1920);
            grabber.setImageHeight(1080);
            grabber.start();

            CanvasFrame canvas = new CanvasFrame("摄像头");//新建一个窗口
            canvas.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            canvas.setAlwaysOnTop(true);
            int ex = 0;
            while (true) {
                if (!canvas.isDisplayable()) {//窗口是否关闭
                    grabber.stop();//停止抓取
                    System.exit(-1);//退出
                }
                Frame frame = grabber.grab();
                if(frame == null){
                    continue;
                }
                canvas.showImage(frame);//获取摄像头图像并放到窗口上显示, 这里的Frame frame=grabber.grab(); frame是一帧视频图像
                opencv_core.Mat mat = converter.convertToMat(frame);
                if(mat == null){
                    continue;
                }
                ex++;
                opencv_imgcodecs.imwrite(ex + ".png", mat);

                try {
                    Thread.sleep(1000);//1秒一次图像
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        }


    }
}


需要pom的依赖包:

<dependency>
	<groupId>org.bytedeco</groupId>
	<artifactId>javacv-platform</artifactId>
	<version>1.4.1</version>
</dependency>
<dependency>
	<groupId>org.bytedeco.javacpp-presets</groupId>
	<artifactId>opencv-platform</artifactId>
	<version>3.4.1-1.4.1</version>
</dependency>

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
	<scope>test</scope>
</dependency>


-EOF-