OpenCvSharp 打开rtsp视频并录制mp4文件

  public class OpenCvSharpUtils
    {
        private VideoCapture Capture;
        private VideoWriter VideoWriter;
        private PictureBox PictureBox;
        private bool StopFlag = false;
        private bool SaveFlag = false;
		
        //
        public void OpenVideo(string rtspUrl,PictureBox PictureBox)
        {
            Capture = new VideoCapture(rtspUrl);
            int time = Convert.ToInt32(Math.Round(1000 / Capture.Fps));
            while (!StopFlag)
            {
                if (Capture == null || Capture.IsDisposed)
                {
                    continue;
                }
                Mat mat = new Mat();
                bool res = Capture.Read(mat);//会阻塞线程
                if (!res || mat.Empty())
                {
                    continue;
                }
                if (SaveFlag && VideoWriter != null)
                {
                    VideoWriter.Write(mat);
                }
                if (PictureBox != null)
                {
                    System.Drawing.Image image = PictureBox.Image;
                    PictureBox.Image = BitmapConverter.ToBitmap(mat);
                    if (image != null)
                    {
                        image.Dispose();//释放以前的图片,不然吃内存
                    }
                }
                Cv2.WaitKey(time);
                
                mat.Dispose();
            }
            Capture.Dispose();
        }

        public void CloseVideo()
        {
            StopFlag = true;
        }

        public bool StartRecord(string videoFullPath)
        {
            if (Capture == null || Capture.IsDisposed)
            {
                return false;
            }
            VideoWriter = new VideoWriter(videoFullPath,FourCC.MPG4,Capture.Fps,new Size(Capture.FrameWidth,Capture.FrameHeight));
            SaveFlag = true;
            return true;
        }

        public bool StopRecord()
        {
            SaveFlag = false;
            if (VideoWriter != null && !VideoWriter.IsDisposed)
            {
                VideoWriter.Dispose();
                VideoWriter = null;
            }
            return true;
        }
    }
原文地址:https://www.cnblogs.com/FlyonGrass/p/14435461.html