Emgu.CV Capture类抛出异常

本文关键字:抛出异常 Capture CV Emgu | 更新日期: 2023-09-27 18:12:04

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

基本上我所做的是点击一个按钮,开始捕捉,capture . start()。在帧处理程序中,我抓取帧并调用Capture.Pause()。我再次单击按钮以再次启动该过程。我可以这样做一段时间,然后它就不起作用了。我可以从头到尾播放视频,只要开始捕捉,不要暂停,重新开始。这是我使用的代码。

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

Emgu.CV Capture类抛出异常

我认为问题是在另一个线程中执行的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;
              }
            }));
}