2016/07/23

C#.Net 透過EmguCV取得視訊影像

未安裝EmguCV的可以再NuGet輸入「Install-Package EmguCV」進行安裝
程式碼:


using Emgu.CV;
using Emgu.CV.CvEnum;
using System;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 擷取
        /// </summary>
        private Capture _capture;

        /// <summary>
        /// 計數器
        /// </summary>
        private Timer _timer;

        /// <summary>
        /// FPS,WebCAM無FPS
        /// </summary>
        protected virtual int _fps { get { return _capture.GetCaptureProperty(CapProp.Fps) == 0 ? 30 : Convert.ToInt16(_capture.GetCaptureProperty(CapProp.Fps)); } }

        /// <summary>
        /// 影像寬
        /// </summary>
        protected virtual int _width { get { return Convert.ToInt16(_capture.GetCaptureProperty(CapProp.FrameWidth)); } }

        /// <summary>
        /// 影像高
        /// </summary>
        protected virtual int _height { get { return Convert.ToInt16(_capture.GetCaptureProperty(CapProp.FrameHeight)); } }

        public Form1()
        {
            InitializeComponent();

            _capture = new Capture();

            _timer = new Timer();
            _timer.Tick += _timer_Tick;

            pictureBox1.Width = _width;
            pictureBox1.Height = Height;
            this.Width = _width;
            this.Height = _height + this.buttonStart.Height;
        }
        
        /// <summary>
        /// 按鈕點擊事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonStart_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;

            switch (btn.Text)
            {
                case "啟動":
                    Start();
                    break;

                case "停止":
                    Stop();
                    break;

                default:
                    break;
            }
        }

        /// <summary>
        /// 計數器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _timer_Tick(object sender, EventArgs e)
        {
            try
            {
             //將影像給予相框
                var frame = _capture.QueryFrame();
                pictureBox1.Image = frame.Bitmap;
            }
            catch (NullReferenceException ex)
            {
                Stop();
                MessageBox.Show("請確認電腦是否與視訊鏡頭連接", "注意", MessageBoxButtons.OK);
                return;
            }
        }

        /// <summary>
        /// 開始方法
        /// </summary>
        private void Start()
        {
            _capture.Start();
            _timer.Start();
            buttonStart.Text = "停止";
        }

        /// <summary>
        /// 停止方法
        /// </summary>
        private void Stop()
        {
            _capture.Stop();
            _timer.Stop();
            buttonStart.Text = "啟動";
        }
    }
}


執行結果: