C#使用EmguCV预览RTSP视频,EmguCV保存RTSP视频

在做一个视频相关的业务,需要调用摄像头查看监控,摄像头使用的是海思的品牌,本打算用海思的SDK,但考虑到客户可能不只是一个牌子的摄像头,海思的SDK可能对其他品牌不兼容,所以考虑使用RTSP方式调用。

那么在C#中怎么调用RTSP实时视频呢,在网上查了很多资料,各位大神提供的资料都是虎头蛇尾的,最后在国外的网站找到了答案,免费分享出来供大家参考(发现很多资料CSDN上的,需要积分下载 而且不一定有用)。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
namespace WpfAppTest
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        private Capture currentDevice;
        private VideoWriter videoWriter;
        private bool recording;
        private int videoWidth;
        private int videoHeight;

        public Window1()
        {
            InitializeComponent();
            InitializeVariables();
        }
        private void InitializeVariables()
        {
            currentDevice = new Capture("rtsp://admin:***@172.16.21.80:554");
            recording = false;
            videoWidth = currentDevice.Width;
            videoHeight = currentDevice.Height;
        }
        private void CurrentDevice_ImageGrabbed(object sender, EventArgs e)
        {
            try
            {
                Mat m = new Mat();
                currentDevice.Retrieve(m,0);
                VideoPictureBox.Image = m.Bitmap;
                if (recording && videoWriter != null)
                {
                    videoWriter.Write(m);
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void Preview_Click(object sender, RoutedEventArgs e)
        {
            currentDevice.ImageGrabbed += CurrentDevice_ImageGrabbed;
            currentDevice.Start();
        }

        private void StartRecording_Click(object sender, RoutedEventArgs e)
        {
            recording = true;
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = ".MP4";
            dialog.AddExtension = true;
            dialog.FileName = DateTime.Now.ToString();
            DialogResult dialogResult = dialog.ShowDialog();
            if (dialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            videoWriter = new VideoWriter(dialog.FileName, VideoWriter.Fourcc('M', 'P', '4', 'V'), 30, new System.Drawing.Size(videoWidth, videoHeight), true);
        }

        private void StopRecording_Click(object sender, RoutedEventArgs e)
        {
            recording = false;
            if (videoWriter != null)
            {
                currentDevice.Stop();
                videoWriter.Dispose();
            }
        }

    }
}