微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在C#和WPF中使用Aforge.NET获取网络摄像头流

我想使用我的相机捕获网络摄像头.为此,我使用了2个参考:AForge.Video.dll和AForge.Video.DirectShow.dll.

Here’s我发现一个片段:

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();
}

}

他们使用PictureBox显示帧.当我在WPF工作时,我使用了this

总结一下这里我的代码看起来像现在.

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();
}

解决方法

编辑1:详细解释我的 blogpost在同一主题.

我将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.

原文地址:https://www.jb51.cc/csharp/95503.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐