OpenCV Background

From Ilianko
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using System.Windows.Threading;

   private Capture cap = new Capture();
   Image<Bgr, byte> frame;
   Image<Bgr, byte> background;
   Image<Gray, byte> bOr;
   private Image<Gray, byte> mask;
   private Image<Gray, byte> maskI;

   private DispatcherTimer timer = new DispatcherTimer();

   private void Form1_Load(object sender, EventArgs e)
   {
       background = new Image<Bgr, byte>("C:/images/test.jpg");
       this.Size = new System.Drawing.Size(100, 100);
           
            frame = cap.QueryFrame();
            frame = cap.QueryFrame();
            frame = cap.QueryFrame();
            frame = cap.QueryFrame();
            frame = cap.QueryFrame();
            frame = cap.QueryFrame();
            bOr = frame.Convert<Gray,byte>();
            
            this.Size = frame.Size;

            
            mask = frame.Convert<Gray, byte>();
            maskI = frame.Convert<Gray, byte>();

            background = background.Resize(frame.Size.Width, frame.Size.Height, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);
         
            timer.Tick += new EventHandler(timer_tick);
            timer.Interval = new TimeSpan(0, 0, 0, 0, 35);
            timer.Start();
        }

        private Image<Gray, byte> gray;
        Image<Bgr, byte> combined;

      
        void timer_tick(object sender, EventArgs e)
        {
            frame = cap.QueryFrame();
            gray = frame.Convert<Gray, byte>();

            mask.SetValue(0);
            maskI.SetValue(255);
           
            gray = gray.AbsDiff(bOr);
            gray = gray.ThresholdBinary(new Gray(20), new Gray(255));
            
            double largestarea = 0;
           
           Contour<Point> largestContour = null;
           var sourceContours = gray.FindContours(Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_NONE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_LIST);
         
           while (sourceContours != null)
           {
               if(largestarea < sourceContours.Area)
               {
                   largestarea = sourceContours.Area;
                   largestContour = sourceContours;
               }
               sourceContours = sourceContours.HNext;
           }

           if (largestContour != null)
           {
               largestarea = largestContour.Area;
               mask.Draw(largestContour, new Gray(255), -1);
               maskI = maskI.Sub(mask);

               combined = background.Copy(maskI);
               frame = frame.Copy(mask);
               frame = frame.Add(combined);
           }
 
            pictureBox1.Image = frame.Bitmap;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }
    }
}