Dot-Net
在 C# 和 WPF 中使用 Aforge.NET 獲取網路攝像頭流
我想用我的相機捕捉網路攝像頭。為此,我使用了 2 個參考:
AForge.Video.dll和AForge.Video.DirectShow.dll.這是我找到的一個片段:
public FilterInfoCollection CamsCollection; public VideoCaptureDevice Cam = null; void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs) { frameholder.Source = (Bitmap)eventArgs.Frame.Clone(); /* ^ * Here it cannot convert implicitly from System.Drawing.Bitmap to * System.Windows.Media.ImageSource */ } private void startcam_Click(object sender, RoutedEventArgs e) { CamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice); Cam = new VideoCaptureDevice(CamsCollection[1].MonikerString); Cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame); Cam.Start(); } private void stopcam_Click(object sender, RoutedEventArgs e) { Cam.Stop(); }}
他們使用 a
PictureBox來顯示框架。當我在 WPF 中工作時,我使用了這個總結一下,這就是我的程式碼目前的樣子。
public FilterInfoCollection CamsCollection; public VideoCaptureDevice Cam = null; void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs) { System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone(); BitmapImage bi = new BitmapImage(); bi.BeginInit (); MemoryStream ms = new MemoryStream (); imgforms.Save(ms, ImageFormat.Bmp); ms.Seek(0, SeekOrigin.Begin); bi.StreamSource = ms; frameholder.Source = bi; /* ^ runtime error here because `bi` is occupied by another thread. */ bi.EndInit(); } private void startcam_Click(object sender, RoutedEventArgs e) { CamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice); Cam = new VideoCaptureDevice(CamsCollection[1].MonikerString); Cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame); Cam.Start(); } private void stopcam_Click(object sender, RoutedEventArgs e) { Cam.Stop(); }
**Edit1:**有關詳細說明,請查看我關於同一主題的博文。
Dispatcher我使用類作為互斥鎖修復了錯誤:void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs) { System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone(); BitmapImage bi = new BitmapImage(); bi.BeginInit(); MemoryStream ms = new MemoryStream(); imgforms.Save(ms, ImageFormat.Bmp); ms.Seek(0, SeekOrigin.Begin); bi.StreamSource = ms; bi.EndInit(); //Using the freeze function to avoid cross thread operations bi.Freeze(); //Calling the UI thread using the Dispatcher to update the 'Image' WPF control Dispatcher.BeginInvoke(new ThreadStart(delegate { frameholder.Source = bi; /*frameholder is the name of the 'Image' WPF control*/ })); }現在它按預期執行,我獲得了良好的性能,而 fps 沒有任何下降。