C#使用EmguCV預覽RTSP視頻,EmguCV保存RTSP視頻

在作一個視頻相關的業務,須要調用攝像頭查看監控,攝像頭使用的是海思的品牌,本打算用海思的SDK,但考慮到客戶可能不僅是一個牌子的攝像頭,海思的SDK可能對其餘品牌不兼容,因此考慮使用RTSP方式調用。html

那麼在C#中怎麼調用RTSP實時視頻呢,在網上查了不少資料,各位大神提供的資料都是有始無終的,最後在國外的網站找到了答案,免費分享出來供你們參考(發現不少資料CSDN上的,須要積分下載 並且不必定有用)。ide

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();
            }
        }

    }
}
    
相關文章
相關標籤/搜索