Emgu.CV Capture类抛出异常

时间:2014-07-08 17:20:42

标签: c# wpf opencv emgucv

我正在尝试创建一个允许我逐帧点击视频的WPF应用。我正在使用Emgu.CV框架Capture类。我可以点击20到30帧然后它停止工作。

基本上我正在做的是单击一个开始捕获的按钮Capture.Start()。在帧处理程序中,我抓住帧并调用Capture.Pause()。我再次单击buttom以再次启动该过程。我可以这样做一段时间,它们就会停止工作。如果只是启动捕获并且不暂停并重新启动它,我可以一直播放视频。 这是我正在使用的代码。

    private void btnCapture_Click(object sender, RoutedEventArgs e) {
        capture = new Capture("C:\\AAAAA\\testVideo.mp4");
        capture.ImageGrabbed += ProcessFrame;
        webCamDisplay.DataContext = webCamManager;
        capture.Start();
    }
    private void btnNextFrame_Click(object sender, RoutedEventArgs e) {
        try {
            capture.Start();
        } catch (Exception ex ) {   
            string msg = ex.Message;
        }
    } 
    private void ProcessFrame(object sender, EventArgs arg) {
        try {
            Image<Bgr, Byte> frame = capture.RetrieveBgrFrame();
            try {
                this.Dispatcher.Invoke((Action)(() => {
                    webCamDisplay.Source = BitmapSourceConvert.ToBitmapSource(frame);
                    webCamManager.Update(frame);
                }));
            } catch (Exception ex) {
                string msg = ex.Message;
            }
            capture.Pause();
        } catch (Exception ex) {                
            string msg = ex.Message;
        }
    }

public class BitmapSourceConvert {
    public static BitmapImage ToBitmapSource(IImage image) {
        using (System.Drawing.Bitmap source = image.Bitmap) {
            System.Windows.Media.Imaging.BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage();
            try {
                MemoryStream ms = new MemoryStream();
                source.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                bImg.BeginInit();
                bImg.StreamSource = new MemoryStream(ms.ToArray());
                bImg.EndInit();
                return bImg;
            } catch (Exception ex) {
                string ms = ex.Message;
                throw new Exception(ms);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为问题出现在this.Dispatcher.Invoke中,它在另一个线程中执行。尝试将capture放在Invoke

private void ProcessFrame(object sender, EventArgs arg) {

            this.Dispatcher.Invoke((Action)(() => {
              try 
              {
                using(var frame = capture.RetrieveBgrFrame())
                {
                          webCamDisplay.Source = BitmapSourceConvert.ToBitmapSource(frame);
                          webCamManager.Update(frame);
                }
                capture.Pause();
              } 
              catch (Exception ex) 
              {
                      string msg = ex.Message;
              }
            }));

}