context: using System;
  using System.Collections.Generic;
  using System.Text;
  using NUnit.Framework;
  using Emgu.CV;
  using Emgu.CV.UI;
  using Emgu.CV.Structure;
  using Emgu.UI;
  using Emgu.Util;
  using Emgu.CV.VideoSurveillance;
  using System.Diagnostics;
  using System.Drawing;
  using System.Windows.Forms;
  using System.Xml;
  using System.IO;
  using System.Runtime.Serialization;
  using System.Runtime.InteropServices;
  using System.Reflection;
  using System.Globalization;
  using System.Threading;
  
  namespace Emgu.CV.Test
  {
     public class Tester
     {
        public void TestRotationMatrix2D()
        {
           RotationMatrix2D<float> mat = new RotationMatrix2D<float>(new PointF(1, 2), 30, 1);
           RotationMatrix2D<double> mat2 = new RotationMatrix2D<double>(new PointF(1, 2), 30, 1);
           //Trace.WriteLine(Emgu.Toolbox.MatrixToString<float>(mat.Data, ", ", ";\r\n"));
        }
  
        public void TestCapture()
        {
           Capture capture = new Capture("abc.efg");
           Image<Bgr, Byte> image = capture.QueryFrame();
        }
  
        public void GenerateLogo()
        {
           Image<Bgr, Byte> semgu = new Image<Bgr, byte>(160, 72, new Bgr(0, 0, 0));
           Image<Bgr, Byte> scv = new Image<Bgr, byte>(160, 72, new Bgr(0, 0, 0));
           MCvFont f1 = new MCvFont(CvEnum.FONT.CV_FONT_HERSHEY_TRIPLEX, 1.5, 1.5);
           MCvFont f2 = new MCvFont(CvEnum.FONT.CV_FONT_HERSHEY_COMPLEX, 1.6, 2.2);
           semgu.Draw("Emgu", ref f1, new Point(6, 50), new Bgr(55, 155, 255));
           semgu._Dilate(1);
           scv.Draw("CV", ref f2, new Point(50, 60), new Bgr(255, 55, 255));
           scv._Dilate(2);
           Image<Bgr, Byte> logoBgr = semgu.Or(scv);
           Image<Gray, Byte> logoA = new Image<Gray, byte>(logoBgr.Width, logoBgr.Height);
           logoA.SetValue(255, logoBgr.Convert<Gray, Byte>());
           logoBgr._Not();
           logoA._Not();
           Image<Gray, Byte>[] channels = logoBgr.Split();
           channels = new Image<Gray, byte>[] { channels[0], channels[1], channels[2], new Image<Gray, Byte>(channels[0].Width, channels[0].Height, new Gray(255.0)) };
           Image<Bgra, Byte> logoBgra = new Image<Bgra, byte>(channels);
           logoBgra.SetValue(new Bgra(0.0, 0.0, 0.0, 0.0), logoA);
           logoBgra.Save("EmguCVLogo.gif");
  
           Image<Bgr, Byte> bg_header = new Image<Bgr, byte>(1, 92);
           for (int i = 0; i < 92; i++)
              bg_header[i, 0] = new Bgr(210, 210 - i * 0.4, 210 - i * 0.9);
           bg_header.Save("bg_header.gif");
        }
  
        public void TestImage()
        {
  
  
           ImageViewer viewer = new ImageViewer();
           Application.Idle += delegate(Object sender, EventArgs e)
           {
              Image<Bgr, Byte> image = new Image<Bgr, byte>(400, 400);
              image.SetRandUniform(new MCvScalar(), new MCvScalar(255, 255, 255));
              image.Save("temp.jpeg");
              Image<Bgr, Byte> img = new Image<Bgr, byte>("temp.jpeg");
              viewer.Image = img;
           };
  
           viewer.ShowDialog();
           /*
           for (int i = 0; i < 10000; i++)
           {
              Image<Bgr, Byte> img = new Image<Bgr, byte>("temp.jpeg");
              viewer.Image = img;
           }*/
  
  
        }
  
        /*
        public void TestPointPerformance()
        {
           #region test point constructors
           int numberOfPoints = 100000;
           Stopwatch stopwatch = Stopwatch.StartNew();
           Point2D<int>[] pts = new Point2D<int>[numberOfPoints];
           for (int i = 0; i < pts.Length; i++)
              pts[i] = new Point2D<int>();
           stopwatch.Stop();
           Trace.WriteLine("Point2D creation: " + stopwatch.ElapsedMilliseconds + " milliseconds.");
           stopwatch.Reset(); stopwatch.Start();
           System.Drawing.Point[] mpts = new System.Drawing.Point[numberOfPoints];
           stopwatch.Stop();
           Trace.WriteLine("System.Drawing.Point creation: " + stopwatch.ElapsedMilliseconds + " milliseconds.");
           #endregion
  
           #region System.Drawing.Point example
           System.Drawing.Point p1 = new System.Drawing.Point(0, 0); 
  
           System.Drawing.Point[] ptsArray = new System.Drawing.Point[1]; //structure (value type) in array are initialized, ptsArray[0] has been allocated to a default point (0,0)
           ptsArray[0] = p1; //ptsArray[0] now contains a copy of p1 (0, 0)
           p1.X = 1; //change the value on p1, now p1 is (1, 0)
           Trace.WriteLine("difference in X: " + (p1.X - ptsArray[0].X)); //ptsArray[0] returns a copy of the point (0,0)
           #endregion
  
           int numberOfPointsInArray = 1000000;
           int numberOfReadyAccess = 1000;
  
           stopwatch.Reset(); stopwatch.Start();
           //initialize Point2D array
           Point2D<int>[] pointArray = new Point2D<int>[numberOfPointsInArray];
           for (int i = 0; i < pointArray.Length; i++)
              pointArray[i] = new Point2D<int>();
  
           for (int j = 0; j < numberOfReadyAccess; j++)
              for (int i = 0; i < pointArray.Length; i++)
              {
                 pointArray[i].X = 2;
              }
           stopwatch.Stop();
           Trace.WriteLine("Time to access elements in Point2D<int> array: " + stopwatch.ElapsedMilliseconds);
  
           stopwatch.Reset(); stopwatch.Start();
           //initialize System.Drawing.Point array
           System.Drawing.Point[] pointStructures = new System.Drawing.Point[numberOfPointsInArray];
  
           for (int j = 0; j < numberOfReadyAccess; j++)
              for (int i = 0; i < pointStructures.Length; i++)
              {
                 pointStructures[i].X = 2;
              }
           stopwatch.Stop();
           Trace.WriteLine("Time to access elements in System.Drawing.Point array: " + stopwatch.ElapsedMilliseconds);
  
        }*/
  
        public void TestCvNamedWindow1()
        {
           //The name of the window
           String win1 = "Test Window";
  
           //Create the window using the specific name
           CvInvoke.cvNamedWindow(win1);
  
           //Create an image of 400x200 of Blue color
           using (Image<Bgr, Byte> img = new Image<Bgr, byte>(400, 200, new Bgr(255, 0, 0))) 
           {
              //Create the font
              MCvFont f = new MCvFont(CvEnum.FONT.CV_FONT_HERSHEY_COMPLEX, 1.0, 1.0);
              //Draw "Hello, world." on the image using the specific font
              img.Draw("Hello, world", ref f, new Point(10, 80), new Bgr(0, 255, 0));
  
              //Show the image
              CvInvoke.cvShowImage(win1, img.Ptr);
              //Wait for the key pressing event
              CvInvoke.cvWaitKey(0);
              //Destory the window
              CvInvoke.cvDestroyWindow(win1); 
           }
        }
  
        public void TestCvNamedWindow2()
        {
           //Create an image of 400x200 of Blue color
           using (Image<Bgr, Byte> img = new Image<Bgr, byte>(400, 200, new Bgr(255, 0, 0))) 
           {
              //Create the font
              MCvFont f = new MCvFont(CvEnum.FONT.CV_FONT_HERSHEY_COMPLEX, 1.0, 1.0);
  
              //Draw "Hello, world." on the image using the specific font
              img.Draw("Hello, world", ref f, new Point(10, 80), new Bgr(0, 255, 0)); 
              
              //Show the image using ImageViewer from Emgu.CV.UI
              ImageViewer.Show(img, "Test Window");
           }
        }
  
        public void TestModuleInfo()
        {
           string pluginName;
           string versionName;
           Emgu.CV.Util.GetModuleInfo(out pluginName, out versionName);
           Trace.WriteLine(String.Format("Plugin: {0}\r\nVersion: {1}", pluginName, versionName ));
        }
  
        public void TestRandom()
        {
           using (Image<Bgr, byte> img = new Image<Bgr, byte>(200, 200))
           {
              img.SetRandNormal(0xffffffff, new MCvScalar(0.0, 0.0, 0.0), new MCvScalar(50.0, 50.0, 50.0));
              ImageViewer.Show(img);
           }
        }
  
        public void CameraTest()
        {
           ImageViewer viewer = new ImageViewer(); //create an image viewer
           Capture capture = new Capture(); //create a camera captue
           Application.Idle += new EventHandler(delegate(object sender, EventArgs e)
           {  //run this until application closed (close button click on image viewer)
              viewer.Image = capture.QueryFrame(); //draw the image obtained from camera
           });
           viewer.ShowDialog(); //show the image viewer
        }
  
        public void CameraTest2()
        {
           ImageViewer viewer = new ImageViewer();
           Capture capture = new Capture();
           Application.Idle += delegate(object sender, EventArgs e)
           {
              Image<Bgr, Byte> img = capture.QueryFrame();
              img = img.Resize(0.8, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);
              Image<Gray, Byte> gray = img.Convert<Gray, Byte>();
              gray._EqualizeHist();
  
              viewer.Image = gray;
           };
           viewer.ShowDialog();
        }
  
        public void TestHaarPerformance()
        {
           HaarCascade face = new HaarCascade("haarcascade_frontalface_alt2.xml");
           Image<Gray, Byte> img = new Image<Gray, byte>("lena.jpg");
           Stopwatch watch = Stopwatch.StartNew();
           img.DetectHaarCascade(face);
           watch.Stop();
           Trace.WriteLine(String.Format("Detecting face from {0}x{1} image took: {2} milliseconds.", img.Width, img.Height, watch.ElapsedMilliseconds));
        }
  
        public void TestFaceDetect()
        {
           using (Image<Bgr, Byte> image = new Image<Bgr, byte>("lena.jpg"))
           using (Image<Bgr, Byte> smooth = image.SmoothGaussian(7))
           {
              DateTime t1 = DateTime.Now;
  
              FaceDetector fd = new FaceDetector();
              Face f = fd.Detect(smooth)[0];
              TimeSpan ts = DateTime.Now.Subtract(t1);
              Trace.WriteLine(ts.TotalMilliseconds);
  
              Eye e = f.DetectEye()[0];
  
              //Application.Run(new ImageViewer(e.RGB));
  
              /*
              Image<Rgb, Byte> res = f.RGB.BlankClone();
              res.Draw(f.SkinContour, new Rgb(255.0, 255.0, 255.0), new Rgb(255.0, 255.0, 255.0), -1);
              Application.Run(new ImageViewer(res.ToBitmap()));
              */
           }
        }
  
        public void TestCompression()
        {
           Image<Bgr, Byte> image = new Image<Bgr, byte>("lena.jpg");
           DateTime t1 = DateTime.Now;
           int l1 = image.Bytes.Length;
           DateTime t2 = DateTime.Now;
           image.SerializationCompressionRatio = 9;
           int l2 = image.Bytes.Length;
           DateTime t3 = DateTime.Now;
           TimeSpan ts1 = t2.Subtract(t1);
           TimeSpan ts2 = t3.Subtract(t2);
           Trace.WriteLine(String.Format("Image Size: {0} x {1}", image.Width, image.Height));
           Trace.WriteLine(String.Format("T1: {0}, T2: {1}, Delta: {2}", ts1.TotalMilliseconds, ts2.TotalMilliseconds, ts2.TotalMilliseconds - ts1.TotalMilliseconds));
  
           Trace.WriteLine(
               String.Format(
               "Original size: {0}; Compressed Size: {1}, Compression Ratio: {2}%",
               l1,
               l2,
               l2 * 100.0 / l1));
        }
  
        public void TestMarshalIplImage()
        {
           Image<Bgr, Single> image = new Image<Bgr, float>(2041, 1023);
           DateTime timeStart = DateTime.Now;
           for (int i = 0; i < 10000; i++)
           {
              MIplImage img = image.MIplImage;
           }
           TimeSpan timeSpan = DateTime.Now.Subtract(timeStart);
           Trace.WriteLine(String.Format("Time: {0} milliseconds", timeSpan.TotalMilliseconds));
        }
  
        public void TestImageViewer()
        {
           //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN");
  
           ImageViewer viewer = new ImageViewer(null);
           //viewer.Image = new Image<Bgr, Byte>(50, 50);
           //viewer.Image = null;
           //viewer.ImageBox.FunctionalMode = ImageBox.FunctionalModeOption.RightClickMenu;
           viewer.ShowDialog();
  
           //Application.Run(new ImageViewer(null));
  
        }
  
        public void TestImageViewerFrameRate()
        {
           ImageViewer viewer = new ImageViewer(null);
           Image<Bgr, Byte> img = new Image<Bgr, Byte>(1024, 1024);
           
           Application.Idle += delegate(Object sender, EventArgs e)
           {
              double v = DateTime.Now.Ticks % 30;
              img.SetValue(new Bgr(v, v, v));
  
              viewer.Image = img;
           };
           viewer.ShowDialog();
  
        }
  
        public static void TestCodeBook()
        {
           int learningFrames = 40;
           using (Capture capture = new Capture("tree.avi"))
           using (BGCodeBookModel<Ycc> bgmodel = new BGCodeBookModel<Ycc>())
           {
              #region Set color thresholds values
              MCvBGCodeBookModel param = bgmodel.MCvBGCodeBookModel;
              param.modMin[0] = param.modMin[1] = param.modMin[2] = 3;
              param.modMax[0] = param.modMax[1] = param.modMax[2] = 10;
              param.cbBounds[0] = param.cbBounds[1] = param.cbBounds[2] = 10;
              bgmodel.MCvBGCodeBookModel = param;
              #endregion
              
              ImageViewer viewer = new ImageViewer();
              int count = 0;
              EventHandler processFrame = delegate(Object sender, EventArgs e)
              {
                 Image<Bgr, Byte> img = capture.QueryFrame();
                 if (img == null)
                 {
                    return;
                 }
                 Image<Gray, byte> mask = new Image<Gray, Byte>(img.Size);
                 mask.SetValue(255);
  
                 viewer.Text = String.Format("Processing {0}th image. {1}", count++, learningFrames > 0 ? "(Learning)" : String.Empty);
  
                 using (Image<Ycc, Byte> ycc = img.Convert<Ycc, Byte>()) //using YCC color space for BGCodeBook
                 {
                    bgmodel.Update(ycc, ycc.ROI, mask);
  
                    if (learningFrames == 0) //training is completed
                       bgmodel.ClearStale(bgmodel.MCvBGCodeBookModel.t / 2, ycc.ROI, mask);
                    
                    learningFrames--;
                    Image<Gray, Byte> m = bgmodel.ForgroundMask.Clone();
                    if (count == 56)
                    {
                       m = bgmodel.ForgroundMask.Clone();
                    }
                    //m._EqualizeHist();
                    viewer.Image = m;
                    //viewer.Image = img;
                    System.Threading.Thread.Sleep(100);
                 }
  
                 img.Dispose();
              };
  
              Application.Idle += processFrame;
  
              viewer.ShowDialog();
           }
        }
  
        /*
        public void TestArrayChangeDimension()
        {
           float[] vec = new float[10];
           for (int i = 0; i < vec.Length; i++)
              vec[i] = (float)i;
  
           float[,] vec2 = new float[vec.Length, 1];
  
  
gt:          GCHandle hdl1 = GCHandle.Alloc(vec, GCHandleType.Pinned);