10

我想用我的相机捕捉网络摄像头。为此,我使用了 2 个参考:AForge.Video.dllAForge.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();
}

}

他们使用 aPictureBox来显示框架。当我在 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();
}
4

2 回答 2

7

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 没有任何下降。

于 2011-05-30T11:11:59.827 回答
1

如果您想支持 Silverlight,无论是 Web 版、独立版还是 WP7,都不应从 WPF 开始,因为 Silverlight 中缺少 WPF 的许多功能。

这是 Silverlight 4+ 教程:

http://www.silverlightshow.net/items/Capturing-the-Webcam-in-Silverlight-4.aspx

于 2011-05-29T07:35:49.753 回答