java opencv通过rtsp获取视频流,保存视频到本地

  • 代码都是来自网络,收集的比较乱,所有找不到出处了。
    获取视频流的核心代码
    private static void testRtsp() {
        //必须要加入这两个东西
        System.load("D:\\opencv-4.1.1\\opencv\\build\\x64\\vc15\\bin\\opencv_world411.dll");
        System.load("D:\\opencv-4.1.1\\opencv\\build\\bin\\opencv_videoio_ffmpeg411_64.dll");
        VideoCapture vc = new VideoCapture();
        boolean isOpen = vc.open("rtsp://admin:[email protected]");
    
        System.out.println("isOpen="+isOpen);
    
        Mat mat = new Mat();
        String winName = "showFrame";
        int height = 600,width = 800;
        HighGui.namedWindow(winName);
        HighGui.resizeWindow(winName, width, height);
        while(vc.read(mat)){
            // 重置大小
            Mat dst = new Mat();
            Imgproc.resize(mat, dst, new Size(width,height));
            // 显示
            HighGui.imshow(winName, dst);
            // waitkey 必须要,否则无法显示
            int key = HighGui.waitKey(1);
            System.out.println("key="+key);
            //esc键退出
            if(key == 27){
                break;
            }
            //拿到了每帧之后要干嘛就是后面逻辑的事情了
        }
        HighGui.destroyAllWindows();
        vc.release();
    }
  • 效果java opencv通过rtsp获取视频流,保存视频到本地_第1张图片
  • mat的一些处理方式
//mat转输入流
public static InputStream mat2InputStream(Mat mat){
    MatOfByte mob = new MatOfByte();
    imencode(".jpg", mat, mob);
    byte[] byteArray = mob.toArray();
    return new ByteArrayInputStream(byteArray);
}
//mat转图片
public static void mat2File(Mat mat){
    MatOfByte mob = new MatOfByte();
    imencode(".jpg", mat, mob);
    imwrite("f:\\img\\test.png",mat);
   // byte[] byteArray = mob.toArray();
}
  • 通过rtsp保存视频
private static void record(){
    System.load("D:\\opencv-4.1.1\\opencv\\build\\x64\\vc15\\bin\\opencv_world411.dll");
    System.load("D:\\opencv-4.1.1\\opencv\\build\\bin\\opencv_videoio_ffmpeg411_64.dll");
    VideoCapture vc = new VideoCapture();
    boolean isOpen = vc.open("rtsp://admin:[email protected]");
    System.out.println("isOpen="+isOpen);
    Mat mat = new Mat();
    VideoWriter vw = new VideoWriter();
    Size size  = new Size();
    size.width = vc.get(CAP_PROP_FRAME_WIDTH);
    size.height = vc.get(CAP_PROP_FRAME_HEIGHT);
    boolean t = vw.open("f:\\img\\test.avi",VideoWriter.fourcc('M', 'P', '4', '2'),30,size);
    System.out.println("开启状态:"+t);
    int times = 400;//测试录制时间
    while(times-->0 && vc.read(mat)){
        vw.write(mat);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    vc.release();
    vw.release();
    System.out.println("结束");
}
效果

你可能感兴趣的:(java)