AForge.Net C#的操作視頻,照片讀寫功能

作者
關鍵詞
摘要
引言
背景
最近在學習人臉識別,最趁手的還是.Net,所以還是現在C#的懷抱里學習了解了。第一站就是AForge。
需求
基本的視頻操作:
現狀
維護到2013年,不知道有沒有更新的中間件了。
必要性
預期目標
自如的控制視頻,圖片等。
實現
主要技術背景
配合AForge的控件和視頻設備或者文件使用,將視頻設備或者文件作為源,即可實現。感覺很方便,很符合C#的操作習慣
設計思路
拖一個視頻控件,然后獲得視頻設備信息,將視頻設備作為控件的源,就可以顯示了。
基本操作
1 准備工作
using AForge.Video.DirectShow;
private FilterInfoCollection filterInfoCollection;
private VideoCaptureDevice rgbVideoDevice;
同時,你拖一個視頻控件到winform上。
2 獲得設備信息
filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
3 實例化視頻設備
if(rgbVideoDevice!=null)
{
rgbVideoDevice=new VideoCaptureDevice(((FilterInfo)filterInfoCollection[0]).MonikerString);
}
4 關聯控件源和設備,並開始
vsp1.VideoSource = rgbVideoDevice;
vsp1.Start();
5 播放視頻(使用視頻作為源)
先定義一個源。
private FileVideoSource fileVideo;
用文件路徑實例化一個文件源
fileVideo = new FileVideoSource("hhha1.avi");
關聯控件源並開始
vsp1.VideoSource = fileVideo;
vsp1.Start();
進階操作
保存圖片
if(rgbVideoDevice.IsRunning)
{
currentpic = vsp1.GetCurrentVideoFrame();
string filepath1 = @"hhha1.jpg";
currentpic.Save(filepath1);
//pictureBox1.Image = Image.FromHbitmap(currentpic.GetHbitmap());//為啥要有這樣一個轉換?
}
錄制視頻
這個稍微麻煩一點,還有幾個坑
坑就不詳細介紹了,給個鏈接跳坑鏈接
通過 VideoFileWriter進行操作。
private VideoFileWriter writer;
實例化一個VideoFileWriter
開始錄制。
writer = new VideoFileWriter();
然后通過writer將文件和視頻控件鏈接起來
string filepath1 = @"hhha1.avi";
if (rgbVideoDevice.IsRunning)
{
writer.Open(filepath1, width, height, fps,VideoCodec.MPEG4);
}
相當於打開文件的口袋,這樣還不能保存視頻,還需要有個引擎或驅動將視頻的每一幀推到文件里。因為是一個引擎,他需要在錄制期間一直工作,所以我們需要一個一直運行的事件來做這個事情,一個簡單的辦法是通過視頻控件的paint來實現。
首先我們需要一個推送的函數
private void writeVideo2file(Bitmap img1) {
//if(isWriter&&writer.IsOpen)
if (writer.IsOpen)
{
writer.WriteVideoFrame(img1);
}
}
當然也可以將writer作為參數,以便獲得更高的靈活性。
然后就可以讓視頻控件的paint事件幫我們推到文件里了
private void videoSourcePlayer1_Paint(object sender, PaintEventArgs e) {
if(vsp1.IsRunning)
{
using (Bitmap img1 = vsp1.GetCurrentVideoFrame())
{
writeVideo2file(img1);
}
}
}
當然你還得記得關掉writer
if(vsp1.IsRunning)
{
vsp1.SignalToStop();
}
注意事項
winfrom的closed事件記得要關閉設備
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
if(vsp1.IsRunning)
{
vsp1.SignalToStop();
}
}
結束語
簡單好用。虹軟的demo就是結合這個控件來完成。
寫完這個東西,就再研究下虹軟的詳細操作。