天天看點

使用 AForge.NET 做視訊采集

AForge.NET 是基于C#設計的,在計算機視覺和人工智能方向擁有很強大功能的架構。btw... it's an open source framework. 附上官網位址: http://www.aforgenet.com/aforge/framework/ 。

今天要介紹的是AForge中的視訊采集功能,這裡的視訊包括從攝像頭等裝置的輸入和從視訊檔案的輸入。

首先來認識一下 視訊源播放器:VideoSourcePlayer,從攝像頭和檔案輸入的視訊,都會通過它來播放,并按幀(Frame)來輸出Bitmap資料。

VideoSourcePlayer 使用有這麼幾個重要的步驟:

  • 初始化它,設定 VideoSource 屬性。VideoSource 接受 IVideoSource 類型的參數,對應到攝像頭輸入和檔案輸入,我們分别會把它設定為 VideoCaptureDevice 和 FileVideoSource。
  • 注冊 NewFrame 事件,開始播放。在 NewFrame 注冊的事件中處理每一幀的Bitmap。
  • 處理完成後,取消 NewFrame 事件注冊,停止它。使用 SignalToStop(); and WaitForStop();

整個使用過程是非常簡單的。下面分别來看看攝像頭輸入和檔案輸入的代碼吧:

 1. 攝像頭輸入

首先是初始化和開始:

// 擷取視訊輸入裝置清單
FilterInfoCollection devices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

// 擷取第一個視訊裝置(示例代碼,未對devices個數為0的情況做處理)
VideoCaptureDevice source = new VideoCaptureDevice(devices[0].MonikerString);
// 設定Frame 的 size 和 rate
source.DesiredFrameSize = new Size(640, 360);
source.DesiredFrameRate = 1;

// 設定VideoSourcePlayer的VideoSource
VideoSourcePlayer videoPlayer = new VideoSourcePlayer();
videoPlayer.VideoSource = source;

videoPlayer.NewFrame += videoPlayer_NewFrame;

videoPlayer.Start();      

這裡是NewFrame事件代碼:

private void videoPlayer_NewFrame(object sender, ref Bitmap image)
{
    // do sth with image
    ...
}      

在使用完成後,停止的代碼:

videoPlayer.NewFrame -= videoPlayer_NewFrame;
videoPlayer.SignalToStop();
videoPlayer.WaitForStop();      

2. 檔案輸入

// 活體對應視訊路徑的檔案作為視訊源
FileVideoSource videoSource = new FileVideoSource(videoFilePath);
videoPlayer.VideoSource = videoSource;

videoPlayer.NewFrame += videoPlayer_NewFrame;

videoPlayer.Start();      

其餘兩部分代碼和攝像頭輸入是一樣的,這裡就不重複了。

對于檔案輸入,還有一點需要注意的,有些機器的codec并不完整,導緻FileVideoSource讀取某些格式,比如mp4的時候會出現讀取錯誤,這時需要安裝一個codec的pack,就可以了。

好了,AForge.NET 的視訊采集功能就介紹完了,接下來會再挑一些AForge中有趣的功能來做介紹。