context: //----------------------------------------------------------------------------
  //  Copyright (C) 2004-2015 by EMGU Corporation. All rights reserved.       
  //----------------------------------------------------------------------------
  using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.Drawing;
  using System.IO;
  using System.Linq;
  using System.Runtime.InteropServices;
  using System.Runtime.Serialization;
  using System.Text;
  using System.Xml;
  using System.Xml.Linq;
  using System.Xml.Serialization;
  using Emgu.CV;
  using Emgu.CV.CvEnum;
  using Emgu.CV.Features2D;
  using Emgu.CV.Flann;
  using Emgu.CV.Stitching;
  using Emgu.CV.Text;
  using Emgu.CV.Structure;
  #if !(IOS || NETFX_CORE)
  using Emgu.CV.Cuda;
  using Emgu.CV.Tiff;
  #endif
  using Emgu.CV.Util;
  using Emgu.CV.VideoSurveillance;
  using Emgu.CV.XFeatures2D;
  //using Emgu.CV.Softcascade;
  using Emgu.Util;
  #if NETFX_CORE
  using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
  using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
  using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
  using Windows.UI;
  #else
  using NUnit.Framework;
  #endif
  
  namespace Emgu.CV.Test
  {
     [TestFixture]
     public class AutoTestVarious
     {
        [Test]
        public void TestColorEqual()
        {
           Bgr c1 = new Bgr(0.0, 0.0, 0.0);
           Bgr c2 = new Bgr(0.0, 0.0, 0.0);
           EmguAssert.IsTrue(c1.Equals(c2));
        }
  
        [Test]
        public void TestCvClipLine()
        {
           Point m1 = new Point(-1, 10);
           Point m2 = new Point(100, 10);
           bool inside = CvInvoke.ClipLine(new Rectangle(Point.Empty, new Size(20, 20)), ref m1, ref m2);
           EmguAssert.AreEqual(0, m1.X);
           EmguAssert.AreEqual(19, m2.X);
        }
  
        [Test]
        public void TestRectangleSize()
        {
           EmguAssert.AreEqual(4 * sizeof(int), Marshal.SizeOf(typeof(Rectangle)));
        }
  
        
        [Test]
        public void TestDenseHistogram()
        {
           Image<Gray, Byte> img = new Image<Gray, byte>(400, 400);
           img.SetRandUniform(new MCvScalar(), new MCvScalar(255));
           DenseHistogram hist = new DenseHistogram(256, new RangeF(0.0f, 255.0f));
           hist.Calculate<Byte>(new Image<Gray, byte>[] { img }, true, null);
           float[] binValues = hist.GetBinValues();
           /*
           using (MemoryStream ms = new MemoryStream())
           {
              System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
              formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
              formatter.Serialize(ms, hist);
              Byte[] bytes = ms.GetBuffer();
  
              using (MemoryStream ms2 = new MemoryStream(bytes))
              {
                 Object o = formatter.Deserialize(ms2);
                 DenseHistogram hist2 = (DenseHistogram)o;
                 EmguAssert.IsTrue(hist.Equals(hist2));
              }
           }*/
        }
  
        [Test]
        public void TestLookup()
        {
           double[] b = new double[4] { 0, 1, 2, 3 };
           double[] a = new double[4] { 1, 3, 2, 0 };
           MCvPoint2D64f[] pts = new MCvPoint2D64f[b.Length];
           for (int i = 0; i < pts.Length; i++)
              pts [i] = new MCvPoint2D64f(b [i], a [i]);
  
           IEnumerable<MCvPoint2D64f> interPts = Toolbox.LinearInterpolate(pts, new double[2]
           {
              1.5,
              3.5
           });
           IEnumerator<MCvPoint2D64f> enumerator = interPts.GetEnumerator();
           enumerator.MoveNext();
           EmguAssert.IsTrue(1.5 == enumerator.Current.X);
           EmguAssert.IsTrue(2.5 == enumerator.Current.Y);
           enumerator.MoveNext();
           EmguAssert.IsTrue(3.5 == enumerator.Current.X);
           EmguAssert.IsTrue(-1 == enumerator.Current.Y);
        }
  
        [Test]
        public void TestLineFitting1()
        {
           List<PointF> pts = new List<PointF>();
  
           pts.Add(new PointF(1.0f, 1.0f));
           pts.Add(new PointF(2.0f, 2.0f));
           pts.Add(new PointF(3.0f, 3.0f));
           pts.Add(new PointF(4.0f, 4.0f));
  
           PointF direction, pointOnLine;
           CvInvoke.FitLine(pts.ToArray(), out direction, out pointOnLine, CvEnum.DistType.L2, 0, 0.1, 0.1);
  
           //check if the line is 45 degree from +x axis
           EmguAssert.AreEqual(45.0, Math.Atan2(direction.Y, direction.X) * 180.0 / Math.PI);
        }
  
  #if !WINDOWS_PHONE_APP
        [Test]
        public void TestXmlSerialization()
        {
           MCvPoint2D64f pt2d = new MCvPoint2D64f(12.0, 5.5);
  
           XDocument xdoc = Toolbox.XmlSerialize<MCvPoint2D64f>(pt2d);
           //Trace.WriteLine(xdoc.OuterXml);
           pt2d = Toolbox.XmlDeserialize<MCvPoint2D64f>(xdoc);
  
           CircleF cir = new CircleF(new PointF(0.0f, 1.0f), 2.8f);
           xdoc = Toolbox.XmlSerialize<CircleF>(cir);
           //Trace.WriteLine(xdoc.OuterXml);
           cir = Toolbox.XmlDeserialize<CircleF>(xdoc);
  
           Image<Bgr, Byte> img1 = EmguAssert.LoadImage<Bgr, byte>("stuff.jpg");
           xdoc = Toolbox.XmlSerialize(img1);
           //Trace.WriteLine(xdoc.OuterXml);
           Image<Bgr, Byte> img2 = Toolbox.XmlDeserialize<Image<Bgr, Byte>>(xdoc);
  
           Byte[] a1 = img1.Bytes;
           Byte[] a2 = img2.Bytes;
           EmguAssert.AreEqual(a1.Length, a2.Length);
           for (int i = 0; i < a1.Length; i++)
           {
              EmguAssert.AreEqual(a1 [i], a2 [i]);
           }
  
           img1.Dispose();
           img2.Dispose();
        }
  #endif
  
        [Test]
        public void TestRotationMatrix3D()
        {
           double[] rod = new double[] { 0.2, 0.5, 0.3 };
           RotationVector3D rodVec = new RotationVector3D(rod);
  
           RotationVector3D rodVec2 = new RotationVector3D();
           rodVec2.RotationMatrix = rodVec.RotationMatrix;
           Matrix<double> diff = rodVec - rodVec2;
           EmguAssert.IsTrue(diff.Norm < 1.0e-8);
        }
  
        
        [Test]
        public void TestContour()
        {
           //Application.EnableVisualStyles();
           //Application.SetCompatibleTextRenderingDefault(false);
           using (Image<Gray, Byte> img = new Image<Gray, Byte>(100, 100, new Gray()))
           {
              Rectangle rect = new Rectangle(10, 10, 80 - 10, 50 - 10);
              img.Draw(rect, new Gray(255.0), -1);
              //ImageViewer.Show(img);
              PointF pIn = new PointF(60, 40);
              PointF pOut = new PointF(80, 100);
  
              using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint() )
              
              {
                 CvInvoke.FindContours(img, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                 using (VectorOfPoint firstContour = contours[0])
                 {
                    EmguAssert.IsTrue( CvInvoke.IsContourConvex(firstContour )  );
                 }
              }
              /*
              using (MemStorage stor = new MemStorage())
              {
                 //Contour<Point> cs = img.FindContours(CvEnum.ChainApproxMethod.ChainApproxSimple, CvEnum.RetrType.List, stor);
                 //EmguAssert.IsTrue(cs.MCvContour.elem_size == Marshal.SizeOf(typeof(Point)));
                 //EmguAssert.IsTrue(rect.Width * rect.Height == cs.Area);
  
                 //EmguAssert.IsTrue(cs.Convex);
                 //EmguAssert.IsTrue(rect.Width * 2 + rect.Height * 2 == cs.Perimeter);
                 Rectangle rect2 = cs.BoundingRectangle;
                 rect2.Width -= 1;
                 rect2.Height -= 1;
                 //rect2.Center.X -= 0.5;
                 //rect2.Center.Y -= 0.5;
                 //EmguAssert.IsTrue(rect2.Equals(rect));
                 EmguAssert.IsTrue(cs.InContour(pIn) > 0);
                 EmguAssert.IsTrue(cs.InContour(pOut) < 0);
                 //EmguAssert.IsTrue(cs.Distance(pIn) == 10);
                 //EmguAssert.IsTrue(cs.Distance(pOut) == -50);
                 img.Draw(cs, new Gray(100), new Gray(100), 0, 1);
  
                 MCvPoint2D64f rectangleCenter = new MCvPoint2D64f(rect.X + rect.Width / 2.0, rect.Y + rect.Height / 2.0);
  
                 using (VectorOfPoint vp = new VectorOfPoint(cs.ToArray()))
                 {    
                    MCvMoments moment = CvInvoke.Moments(vp, false);
                    MCvPoint2D64f center = moment.GravityCenter;
                    //EmguAssert.IsTrue(center.Equals(rectangleCenter));
                 }
                 
              }
  
              using (MemStorage stor = new MemStorage())
              {
                 Image<Gray, Byte> img2 = new Image<Gray, byte>(300, 200);
                 Contour<Point> c = img2.FindContours(Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple, Emgu.CV.CvEnum.RetrType.List, stor);
                 EmguAssert.IsTrue(c == null);
              }*/
           }
  
           int s1 = Marshal.SizeOf(typeof(MCvSeq));
           int s2 = Marshal.SizeOf(typeof(MCvContour));
           int sizeRect = Marshal.SizeOf(typeof(Rectangle));
           EmguAssert.IsTrue(s1 + sizeRect + 4 * Marshal.SizeOf(typeof(int)) == s2);
        }
        /*
        [Test]
        public void TestConvexityDefacts()
        {
           Image<Gray, Byte> image = new Image<Gray, byte>(300, 300);
           Point[] polyline = new Point[] {
              new Point(10, 10),
              new Point(10, 250),
              new Point(100, 100),
              new Point(250, 250),
              new Point(250, 10)};
  
           using (MemStorage stor = new MemStorage())
           {
              Seq<Point> contour = new Seq<Point>(stor);
              contour.PushMulti(polyline, Emgu.CV.CvEnum.BackOrFront.Front);
              image.Draw(contour, new Gray(255), 1);
              Seq<MCvConvexityDefect> defactSeq =
                 contour.GetConvexityDefacts(
                    stor,
                    Emgu.CV.CvEnum.PageOrientation.Clockwise);
              MCvConvexityDefect[] defacts = defactSeq.ToArray();
              EmguAssert.IsTrue(1 == defacts.Length);
              EmguAssert.IsTrue(new Point(100, 100).Equals(defacts [0].DepthPoint));
  
              EmguAssert.IsTrue(contour.InContour(new PointF(90, 90)) > 0);
              EmguAssert.IsTrue(contour.InContour(new PointF(300, 300)) < 0);
              EmguAssert.IsTrue(contour.InContour(new PointF(10, 10)) == 0);
           }
        }*/
  
        [Test]
        public void TestException()
        {
           for (int i = 0; i < 10; i++)
           {
              bool exceptionCaught = false;
              Matrix<Byte> mat = new Matrix<byte>(20, 30);
              try
              {
                 double det = mat.Det;
              } catch (CvException excpt)
              {
                 EmguAssert.AreEqual(-215, excpt.Status);
                 exceptionCaught = true;
              }
              EmguAssert.IsTrue(exceptionCaught);
           }
        }
  
        [Test]
        public void TestProjectPoints()
        {
           Mat cameraMatrix = new Mat(3, 3, DepthType.Cv64F, 1);
           CvInvoke.SetIdentity(cameraMatrix, new MCvScalar(1));
  
           Mat distortionCoeff = new Mat(8, 1, DepthType.Cv64F, 1);
           distortionCoeff.SetTo(new MCvScalar());
  
           VectorOfDouble rotationVector = new VectorOfDouble(new double[]{0,0,0});
           VectorOfDouble translationVector = new VectorOfDouble(new double[] { 0, 0, 0 });
                   
           MCvPoint3D32f point = new MCvPoint3D32f(12, 32, 9);
  
           PointF[] points = CvInvoke.ProjectPoints(
              new MCvPoint3D32f[] { point }, 
              rotationVector, 
              translationVector, 
              cameraMatrix, 
              distortionCoeff);
        }
  
        /*
        [Test]
        public void TestBlobDetector()
        {
           int width = 300;
           int height = 400;
           Image<Gray, Byte> img = new Image<Gray, byte>(width, height);
           //bg.SetRandNormal(new MCvScalar(), new MCvScalar(100, 100, 100));
           Size size = new Size(width / 5, height / 5);
           Point topLeft = new Point((width >> 1) - (size.Width >> 1), (height >> 1) - (size.Height >> 1));
           Rectangle rect = new Rectangle(topLeft, size);
  
           BlobDetector detector = new BlobDetector(CvEnum.BlobDetectorType.Simple);
           //Image<Gray, Byte> forground = new Image<Gray,byte>(bg.Size);
           //forground.SetValue(255);
           BlobSeq newSeq = new BlobSeq();
           BlobSeq oldSeq = new BlobSeq();
           using (Image<Gray, Byte> forgroundMask = img.Copy())
           {
              rect.Offset(5, 0); //shift the rectangle 5 pixels horizontally
              forgroundMask.Draw(rect, new Gray(255), -1);
              //TODO: Find out why BlobDetector cannot detect new Blob.
              bool detected = detector.DetectNewBlob(forgroundMask, newSeq, oldSeq);
              //ImageViewer.Show(forgroundMask);
              //Assert.IsTrue(detected);
           }
        }
  
        [Test]
        public void TestBlobColor()
        {
           int width = 300;
           int height = 400;
           Image<Bgr, Byte> bg = new Image<Bgr, byte>(width, height);
           bg.SetRandNormal(new MCvScalar(), new MCvScalar(100, 100, 100));
  
           Size size = new Size(width / 10, height / 10);
           Point topLeft = new Point((width >> 1) - (size.Width >> 1), (height >> 1) - (size.Height >> 1));
  
           Rectangle rect = new Rectangle(topLeft, size);
  
           BlobTrackerAutoParam<Bgr> param = new BlobTrackerAutoParam<Bgr>();
           param.BlobDetector = new BlobDetector(Emgu.CV.CvEnum.BlobDetectorType.CC);
           //param.FGDetector = new FGDetector<Gray>(Emgu.CV.CvEnum.FORGROUND_DETECTOR_TYPE.FGD);
           param.BlobTracker = new BlobTracker(Emgu.CV.CvEnum.BlobTrackerType.MSFGS);
           param.FGTrainFrames = 5;
           BlobTrackerAuto<Bgr> tracker = new BlobTrackerAuto<Bgr>(param);
  
           //ImageViewer viewer = new ImageViewer();
           //viewer.Show();
           for (int i = 0; i < 20; i++)
           {
              using (Image<Bgr, Byte> img1 = bg.Copy())
              {
                 rect.Offset(5, 0); //shift the rectangle 5 pixels horizontally
                 img1.Draw(rect, new Bgr(Color.Red), -1);
                 tracker.Process(img1);
                 //viewer.Image = img1;
              }
           }
  
           //MCvBlob blob = tracker[0];
           //int id = blob.ID;
           //ImageViewer.Show(forground);
        }
  
        [Test]
        public void TestBlobGray()
        {
           int width = 300;
           int height = 400;
           Image<Bgr, Byte> bg = new Image<Bgr, byte>(width, height);
           bg.SetRandNormal(new MCvScalar(), new MCvScalar(100, 100, 100));
  
           Size size = new Size(width / 10, height / 10);
           Point topLeft = new Point((width >> 1) - (size.Width >> 1), (height >> 1) - (size.Height >> 1));
  
           Rectangle rect = new Rectangle(topLeft, size);
  
           BlobTrackerAutoParam<Gray> param = new BlobTrackerAutoParam<Gray>();
           param.BlobDetector = new BlobDetector(Emgu.CV.CvEnum.BlobDetectorType.CC);
           //param.FGDetector = new FGDetector<Gray>(Emgu.CV.CvEnum.FORGROUND_DETECTOR_TYPE.FGD);
           param.BlobTracker = new BlobTracker(Emgu.CV.CvEnum.BlobTrackerType.MSFGS);
           param.FGTrainFrames = 5;
           BlobTrackerAuto<Gray> tracker = new BlobTrackerAuto<Gray>(param);
  
           //ImageViewer viewer = new ImageViewer();
           //viewer.Show();
           for (int i = 0; i < 20; i++)
           {
              using (Image<Bgr, Byte> img1 = bg.Copy())
              {
                 rect.Offset(5, 0); //shift the rectangle 5 pixels horizontally
                 img1.Draw(rect, new Bgr(Color.Red), -1);
                 tracker.Process(img1.Convert<Gray, Byte>());
                 //viewer.Image = img1;
                 //viewer.Refresh();
              }
           }
  
           //MCvBlob blob = tracker[0];
           //int id = blob.ID;
           //ImageViewer.Show(foreground);
        }
  
        [Test]
        public void TestEigenObjects()
        {
           String[] fileNames = new string[]
           {
              "stuff.jpg",
              "squares.gif",
              "lena.jpg"
           };
  
           int width = 100, height = 100;
           MCvTermCriteria termCrit = new MCvTermCriteria(3, 0.001);
  
           #region using batch method
           Image<Gray, Byte>[] imgs = Array.ConvertAll<String, Image<Gray, Byte>>(fileNames,
               delegate(String file)
           {
              return EmguAssert.LoadImage<Gray, Byte>(file).Resize(width, height, CvEnum.Inter.Linear);
           });
  
           EigenObjectRecognizer imgRecognizer1 = new EigenObjectRecognizer(imgs, ref termCrit);
           for (int i = 0; i < imgs.Length; i++)
           {
              EmguAssert.AreEqual(i.ToString(), imgRecognizer1.Recognize(imgs[i]).Label);
           }
  
           XDocument xDoc = Toolbox.XmlSerialize<EigenObjectRecognizer>(imgRecognizer1);
           EigenObjectRecognizer imgRecognizer2 = Toolbox.XmlDeserialize<EigenObjectRecognizer>(xDoc);
  
           for (int i = 0; i < imgs.Length; i++)
           {
              EmguAssert.AreEqual(i.ToString(), imgRecognizer2.Recognize(imgs[i]).Label);
           }
  
           System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
               formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  
           Byte[] bytes;
           using (MemoryStream ms = new MemoryStream())
           {
              formatter.Serialize(ms, imgRecognizer1);
              bytes = ms.GetBuffer();
           }
           using (MemoryStream ms2 = new MemoryStream(bytes))
           {
              EigenObjectRecognizer imgRecognizer3 = (EigenObjectRecognizer) formatter.Deserialize(ms2);
              for (int i = 0; i < imgs.Length; i++)
              {
                 EmguAssert.AreEqual(i.ToString(), imgRecognizer3.Recognize(imgs[i]).Label);
              }
           }
           #endregion
        }
  
        [Test]
        public void StressMemoryTestHaar()
        {
           Image<Bgr, Byte> img;
           for (int i = 0; i < 10000; i++)
           {
              //HaarCascade cascade = new HaarCascade("haarcascade_frontalface_alt2.xml");
              img = new Image<Bgr, Byte>("lena.jpg");
              //MCvAvgComp[] comps = img.DetectHaarCascade(cascade)[0];
           }
        }*/
  
        private static float[,] ProjectPoints(float[,] points3D, RotationVector3D rotation, Matrix<double> translation, float focalLength)
        {
           using (Matrix<float> imagePointMat = new Matrix<float>(points3D.GetLength(0), 2))
           {
              CvInvoke.ProjectPoints(new Matrix<float>(points3D), rotation, translation,
              new Matrix<double>(new double[,] { 
                 {focalLength, 0, 0},
                 {0, focalLength, 0}, 
                 {0,0,1}}),
              null, imagePointMat);
              return imagePointMat.Data;
           }
        }
        
        [Test]
        public void TestIntrisicParameters()
        {
           #if !(IOS || __ANDROID__ || NETFX_CORE)
           System.Diagnostics.PerformanceCounter memCounter = new PerformanceCounter("Memory", "Available MBytes");
           Trace.WriteLine(String.Format("Available mem before: {0} Mb", memCounter.NextValue()));
           #endif
           IntrinsicCameraParameters[] paramArr = new IntrinsicCameraParameters[100000];
           for (int i = 0; i < paramArr.Length; i++)
           {
              paramArr[i] = new IntrinsicCameraParameters(8);
           }
           #if !(IOS || __ANDROID__ || NETFX_CORE)
           Trace.WriteLine(String.Format("Available mem after: {0} Mb", memCounter.NextValue()));
           #endif
        }
  
        /*
        [Test]
        public void TestPOSIT()
        {
           float[] rotation = new float[9];
           float[] translation = new float[3];
           float focalLength = 1.0f;
  
           float cubeSize = 200.0f;
  
           float[,] points3D = new float[,] {
              {0, 0, 0},
              {0, 0, cubeSize},
              {0, cubeSize, cubeSize}, 
              {0, cubeSize, 0},
              {cubeSize, 0, 0}, 
              {cubeSize, cubeSize, 0},
              { cubeSize, cubeSize, cubeSize }, 
              { cubeSize, 0, cubeSize } };
  
           IntPtr posit = CvInvoke.cvCreatePOSITObject(points3D, points3D.GetLength(0));
  
           #region caculate the image point assuming we know the rotation and translation
           RotationVector3D realRotVec = new RotationVector3D(new double[3] { 0.1f, 0.2f, 0.3f });
           Matrix<double> realTransVec = new Matrix<double>(new double[3] { 0.0f, 0.0f, -50.0f });
           
           float[,] imagePoint = ProjectPoints(points3D, realRotVec, realTransVec, focalLength);
           GCHandle handle1 = GCHandle.Alloc(imagePoint, GCHandleType.Pinned);
           #endregion
  
           RotationVector3D rotVecGuess = new RotationVector3D(new double[3] { 0.3f, 0.1f, 0.2f });
           Matrix<double> rotMatGuess = rotVecGuess.RotationMatrix;
           
           //float[] rotFVecGuess = new float[] { (float)rotMatGuess[0, 0], (float) rotMatGuess[1, 0], (float) rotMatGuess[2, 0], (float)rotMatGuess[0, 1], (float)rotMatGuess[1, 1], (float)rotMatGuess[2, 1], (float)rotMatGuess[0, 2], (float)rotMatGuess[1, 2], (float)rotMatGuess[2, 2] };
           Matrix<float> tranFVecGuess = new Matrix<float>( new float[] { 0, 0, 5 });
           CvInvoke.cvPOSIT(posit, handle1.AddrOfPinnedObject(), 0.5, new MCvTermCriteria(200, 1.0e-5), rotMatGuess.MCvMat.data, tranFVecGuess.MCvMat.data);
           
           //Matrix<double> rotMatEst = new Matrix<double>(new double[,] { 
           //   {rotFVecGuess[0], rotFVecGuess[3], rotFVecGuess[6]},
           //   {rotFVecGuess[1], rotFVecGuess[4], rotFVecGuess[7]},
           //   {rotFVecGuess[2], rotFVecGuess[5], rotFVecGuess[8]}});
           RotationVector3D rotVecEst = new RotationVector3D();
           Matrix<double> tranMatEst = tranFVecGuess.Convert<double>();
  
           rotVecEst.RotationMatrix = rotMatGuess;
           //At this point rotVecEst should be similar to realRotVec, but it is not...
  
           float[,] projectionFromEst = ProjectPoints(points3D, rotVecEst, tranMatEst, focalLength);
  
           for (int i = 0; i < projectionFromEst.GetLength(0); i++)
           {
              float x = imagePoint[i, 0] - projectionFromEst[i, 0];
              float y = imagePoint[i, 1] - projectionFromEst[i, 1];
              Trace.WriteLine(String.Format("Projection Distance: {0}", Math.Sqrt(x * x + y * y)));
           }
  
           CvInvoke.cvReleasePOSITObject(ref posit);
        }*/
  
  
        [Test]
        public void TestXmlSerialize()
        {
           PointF p = new PointF(0.0f, 0.0f);
           XDocument xDoc = Toolbox.XmlSerialize<PointF>(p, new Type[] { typeof(Point) });
           PointF p2 = Toolbox.XmlDeserialize<PointF>(xDoc, new Type[] { typeof(Point) });
           EmguAssert.IsTrue(p.Equals(p2));
  
  
           Rectangle rect = new Rectangle(3, 4, 5, 3);
           XDocument xDoc2 = Toolbox.XmlSerialize<Rectangle>(rect);
           Rectangle rect2 = Toolbox.XmlDeserialize<Rectangle>(xDoc2);
           EmguAssert.IsTrue(rect.Equals(rect2));
  
        }
  
        [Test]
        public void TestFileStorage1()
        {
           FileStorage fs = new FileStorage("haarcascade_eye.xml", FileStorage.Mode.Read);
           
        }
  
        [Test]
        public void TestFileStorage2()
        {
           Mat m = new Mat(40, 30, DepthType.Cv8U, 3);
           
           using (ScalarArray lower = new ScalarArray(new MCvScalar(0, 0, 0)))
           using (ScalarArray higher = new ScalarArray(new MCvScalar(255, 255, 255)))
              CvInvoke.Randu(m, lower, higher );
  
           int intValue = 10;
           float floatValue = 213.993f;
           double doubleValue = 32.314;
  
           using (FileStorage fs = new FileStorage(".xml", FileStorage.Mode.Write | FileStorage.Mode.Memory))
           {
              fs.Write(m, "m");
              fs.Write(intValue, "int");
              fs.Write(floatValue, "float");
              fs.Write(doubleValue, "double");
              string s = fs.ReleaseAndGetString();
  
              using (FileStorage fs2 = new FileStorage(s, FileStorage.Mode.Read | FileStorage.Mode.Memory))
              {
                 
                 using (FileNode node = fs2.GetFirstTopLevelNode())
                 {
                    Mat m2 = new Mat();
                    node.ReadMat(m2);
                    EmguAssert.IsTrue(m.Equals(m2));
                 }
  
                 using (FileNode node = fs2.GetNode("m"))
                 {
                    Mat m2 = new Mat();
                    node.ReadMat(m2);
                    EmguAssert.IsTrue(m.Equals(m2));
                 }
  
                 using (FileNode node = fs2.GetNode("int"))
                 {
                    EmguAssert.IsTrue(intValue.Equals(node.ReadInt()));   
                 }
  
                 using (FileNode node = fs2.GetNode("float"))
                 {
                    EmguAssert.IsTrue(floatValue.Equals(node.ReadFloat()));
                 }
  
                 using (FileNode node = fs2.GetNode("double"))
                 {
                    EmguAssert.IsTrue(doubleValue.Equals(node.ReadDouble()));
                 }
              }
           }
        }
  
  
        [Test]
        public void TestTriangle()
        {
           PointF p1 = new PointF(0, 0);
           PointF p2 = new PointF(1, 0);
           PointF p3 = new PointF(0, 1);
           Triangle2DF tri = new Triangle2DF(p1, p2, p3);
           double epsilon = 1e-12;
           //Trace.WriteLine(tri.Area);
           //Trace.WriteLine(((p2.X - p1.X) * (p3.Y - p1.Y) - (p2.Y - p1.Y) * (p3.X - p1.X))*0.5);
           EmguAssert.IsTrue(Math.Abs(tri.Area - 0.5) < epsilon);
        }
  
        [Test]
        public void TestLine()
        {
           PointF p1 = new PointF(0, 0);
           PointF p2 = new PointF(1, 0);
           PointF p3 = new PointF(0, 1);
           LineSegment2DF l1 = new LineSegment2DF(p1, p2);
           LineSegment2DF l2 = new LineSegment2DF(p1, p3);
           double angle = l1.GetExteriorAngleDegree(l2);
           EmguAssert.AreEqual(angle, 90.0);
        }
  
        [Test]
        public void TestGetBox2DPoints()
        {
           RotatedRect box = new RotatedRect(
              new PointF(3.0f, 2.0f),
              new SizeF(4.0f, 6.0f),
              0.0f);
           PointF[] vertices = box.GetVertices();
           //TODO: Find out why the following test fails. (x, y) convention changed.
           //Assert.IsTrue(vertices[0].Equals(new PointF(0.0f, 0.0f)));
           //Assert.IsTrue(vertices[1].Equals(new PointF(6.0f, 0.0f)));
        }
  
  #if !(IOS || __ANDROID__ || NETFX_CORE)
        [Test]
        public void TestGrayscaleBitmapConstructor()
        {
           Image<Bgra, Byte> img = new Image<Bgra, byte>(320, 240);
           img.SetRandUniform(new MCvScalar(), new MCvScalar(255, 255, 255, 255));
           img.Save("tmp.png");
  
           Stopwatch stopwatch = Stopwatch.StartNew();
           Image<Bgra, Byte> img2 = new Image<Bgra, byte>("tmp.png");
           stopwatch.Stop();
           Trace.WriteLine(string.Format("Time: {0} milliseconds", stopwatch.ElapsedMilliseconds));
           Image<Bgra, Byte> absDiff = new Image<Bgra, Byte>(320, 240);
           CvInvoke.AbsDiff(img, img2, absDiff);
           double[] min, max;
           Point[] minLoc, maxLoc;
           double eps = 1;
           absDiff.MinMax(out min, out max, out minLoc, out maxLoc); //ImageViewer.Show(absDiff);
           EmguAssert.IsTrue(max[0] < eps);
           EmguAssert.IsTrue(max[1] < eps);
           EmguAssert.IsTrue(max[2] < eps);
  
           stopwatch.Reset();
           stopwatch.Start();
           using (Bitmap bmp = new Bitmap("tmp.png"))
           using (Image bmpImage = Bitmap.FromFile("tmp.png"))
           {
              EmguAssert.AreEqual(System.Drawing.Imaging.PixelFormat.Format32bppArgb, bmpImage.PixelFormat);
  
              Image<Gray, Byte> img3 = new Image<Gray, byte>(bmp);
              stopwatch.Stop();
              Trace.WriteLine(string.Format("Time: {0} milliseconds", stopwatch.ElapsedMilliseconds));
              Image<Gray, Byte> diff = img.Convert<Gray, Byte>().AbsDiff(img3);
              EmguAssert.AreEqual(0, CvInvoke.CountNonZero(diff));
              EmguAssert.IsTrue(img.Convert<Gray, Byte>().Equals(img3));
           }
        }
  #endif
        /*
        [Test]
        public void TestAlgorithmGetList()
        {
           String[] list = AlgorithmExtensions.AlgorithmList;
        }*/
  
        [Test]
        public void TestMorphEx()
        {
           Mat kernel1 = CvInvoke.GetStructuringElement(Emgu.CV.CvEnum.ElementShape.Cross, new Size(3, 3), new Point(1, 1));
           Matrix<byte> kernel2 = new Matrix<byte>(new Byte[3, 3] { { 0, 1, 0 }, { 1, 0, 1 }, { 0, 1, 0 } });
           //StructuringElementEx element2 = new StructuringElementEx(new int[3, 3] { { 0, 1, 0 }, { 1, 0, 1 }, { 0, 1, 0 } }, 1, 1);
           Image<Bgr, Byte> tmp = new Image<Bgr, byte>(100, 100);
           Image<Bgr, Byte> tmp2 = tmp.MorphologyEx(Emgu.CV.CvEnum.MorphOp.Gradient, kernel1, new Point(-1, -1), 1, CvEnum.BorderType.Default, new MCvScalar());
           Image<Bgr, Byte> tmp3 = tmp.MorphologyEx(Emgu.CV.CvEnum.MorphOp.Gradient, kernel2, new Point(-1, -1), 1, CvEnum.BorderType.Default, new MCvScalar());
           //Image<Bgr, Byte> tmp2 = tmp.MorphologyEx(element1, Emgu.CV.CvEnum.CV_MORPH_OP.CV_MOP_GRADIENT, 1);
           //Image<Bgr, Byte> tmp3 = tmp.MorphologyEx(element2, Emgu.CV.CvEnum.CV_MORPH_OP.CV_MOP_BLACKHAT, 1);
        }
  
        /*
        [Test]
        public void TestBGModel()
        {
           int width = 300;
           int height = 400;
           Image<Bgr, Byte> bg = new Image<Bgr, byte>(width, height);
           bg.SetRandNormal(new MCvScalar(), new MCvScalar(100, 100, 100));
  
           Size size = new Size(width / 10, height / 10);
           Point topLeft = new Point((width >> 1) - (size.Width >> 1), (height >> 1) - (size.Height >> 1));
  
           Rectangle rect = new Rectangle(topLeft, size);
  
           Image<Bgr, Byte> img1 = bg.Copy();
           img1.Draw(rect, new Bgr(Color.Red), -1);
  
           Image<Bgr, Byte> img2 = bg.Copy();
           rect.Offset(10, 0);
           img2.Draw(rect, new Bgr(Color.Red), -1);
  
           BGStatModel<Bgr> model1 = new BGStatModel<Bgr>(img1, Emgu.CV.CvEnum.BgStatType.GaussianBgModel);
           model1.Update(img2);
  
           BGStatModel<Bgr> model2 = new BGStatModel<Bgr>(img1, Emgu.CV.CvEnum.BgStatType.FgdStatModel);
           model2.Update(img2);
  
           //ImageViewer.Show(model2.Foreground);
           //ImageViewer.Show(model1.Background);
        }*/
  
        /*
        public void TestPlanarSubdivisionHelper(int pointCount)
        {
           #region generate random points
           PointF[] points = new PointF[pointCount];
           Random r = new Random((int) DateTime.Now.Ticks);
           for (int i = 0; i < points.Length; i++)
           {
              points[i] = new PointF((float) (r.NextDouble() * 20), (float) (r.NextDouble() * 20));
           }
           #endregion
  
           Subdiv2D division;
  
           Stopwatch watch = Stopwatch.StartNew();
           division = new Subdiv2D(points, true);
           Triangle2DF[] triangles = division.GetDelaunayTriangles(false);
           watch.Stop();
           EmguAssert.WriteLine(String.Format("delaunay triangulation: {2} points, {0} milli-seconds, {1} triangles", watch.ElapsedMilliseconds, triangles.Length, points));
           watch.Reset();
  
           EmguAssert.IsTrue(CvInvoke.icvSubdiv2DCheck(division));
  
           watch.Start();
           division = new Subdiv2D(points);
           VoronoiFacet[] facets = division.GetVoronoiFacets();
           watch.Stop();
           EmguAssert.WriteLine(String.Format("Voronoi facets: {2} points, {0} milli-seconds, {1} facets", watch.ElapsedMilliseconds, facets.Length, points));
  
           //foreach (Triangle2DF t in triangles)
           //{
           //int equalCount = triangles.FindAll(delegate(Triangle2DF t2) { return t2.Equals(t); }).Count;
           //Assert.AreEqual(1, equalCount, "Triangle duplicates");
  
           //int overlapCount = triangles.FindAll(delegate(Triangle2D t2) { return Util.IsConvexPolygonInConvexPolygon(t2, t);}).Count;
           //Assert.AreEqual(1, overlapCount, "Triangle overlaps");
           //}
        }
  
        [Test]
        public void TestPlanarSubdivision1()
        {
           //TestPlanarSubdivisionHelper(10000);
           TestPlanarSubdivisionHelper(27);
           TestPlanarSubdivisionHelper(83);
           TestPlanarSubdivisionHelper(139);
           TestPlanarSubdivisionHelper(363);
  
           TestPlanarSubdivisionHelper(13);
           TestPlanarSubdivisionHelper(41);
           TestPlanarSubdivisionHelper(69);
        }*/
  
        [Test]
        public void TestPlanarSubdivision2()
        {
           PointF[] pts = new PointF[33];
  
           pts[0] = new PointF(224, 432);
           pts[1] = new PointF(368, 596);
           pts[2] = new PointF(316, 428);
           pts[3] = new PointF(244, 596);
           pts[4] = new PointF(224, 436);
           pts[5] = new PointF(224, 552);
  
gt:          pts[6] = new PointF(276, 568);