How to display webcam images captured with Emgu?

前端 未结 7 926
北恋
北恋 2020-12-10 14:18

I\'m currently working on a project that use Facial Recognition. I therefore need a way to display the webcam images to the user so he can adjust his face.

I\'ve bee

7条回答
  •  执念已碎
    2020-12-10 14:59

    If you are using WPF and MVVM here is how you would do it using EMGU.

    View:

    
    
        
            
                
                    
                        
                    
                
            
        
    
    

    Viewmodel:

    namespace HA.FacialRecognition.Enroll.ViewModels
    {
    public class PhotoCaptureViewModel : INotifyPropertyChanged
    {
        public PhotoCaptureViewModel()
        {
            StartVideo();
        }
    
        private DispatcherTimer Timer { get; set; }
    
        private Capture Capture { get; set; }
    
        private BitmapSource _currentFrame;
        public BitmapSource CurrentFrame
        {
            get { return _currentFrame; }
            set
            {
                if (_currentFrame != value)
                {
                    _currentFrame = value;
                    OnPropertyChanged();
                }
            }
        }
    
        private void StartVideo()
        {
            Capture = new Capture();
            Timer = new DispatcherTimer();
            //framerate of 10fps
            Timer.Interval = TimeSpan.FromMilliseconds(100);
            Timer.Tick += new EventHandler(async (object s, EventArgs a) =>
            {
                //draw the image obtained from camera
                using (Image frame = Capture.QueryFrame())
                {
                    if (frame != null)
                    {
                        CurrentFrame = ToBitmapSource(frame);
                    }
                }
            });
            Timer.Start();
        }
    
        public static BitmapSource ToBitmapSource(IImage image)
        {
            using (System.Drawing.Bitmap source = image.Bitmap)
            {
                IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap
                BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                DeleteObject(ptr); //release the HBitmap
                return bs;
            }
        }
    
        /// 
        /// Delete a GDI object
        /// 
        [DllImport("gdi32")]
        private static extern int DeleteObject(IntPtr o);
    
        //implementation of INotifyPropertyChanged, viewmodel disposal etc
    
    }
    

提交回复
热议问题