Exemplo n.º 1
0
 public void drawPoint(Image<Bgr,Byte> img)
 {
     for (int i=0;i<4;i++) {
         CircleF c = new CircleF(pktList[i], 3);
         img.Draw(c, colorList[i], 2);
     }
     drawLine(img);
 }
Exemplo n.º 2
0
        public void CircleF_IsConstructedProperly()
        {
            var result = new CircleF(123.45f, 456.78f, 100.10f);

            TheResultingValue(result)
                .ShouldHavePosition(123.45f, 456.78f)
                .ShouldHaveRadius(100.10f);
        }
Exemplo n.º 3
0
        public void CircleF_EqualsObject()
        {
            var circle1 = new CircleF(123.45f, 456.78f, 100.10f);
            var circle2 = new CircleF(123.45f, 456.78f, 100.10f);

            TheResultingValue(circle1.Equals((Object)circle2)).ShouldBe(true);
            TheResultingValue(circle1.Equals("This is a test")).ShouldBe(false);
        }
        public void TestNotRectangleIntersectsCircle()
        {
            // ARRANGE.
            var rectangle = new RectangleF(new Vector2F(0.0f, 0.0f), new Vector2F(1.0f, 1.0f));
            var circle = new CircleF(new Vector2F(2.0f, 2.0f), 0.5f);

            // ASSERT.
            Assert.IsFalse(rectangle.Intersects(circle));
        }
Exemplo n.º 5
0
        public override void ImageGrabbedHandler(object sender, EventArgs e)
        {
            using (var matCaptured = new Mat())
            {
                var retrieveElapsed = Stopwatch.StartNew();
                CameraCapture.Retrieve(matCaptured);
                retrieveElapsed.Stop();

                if (_readyRectangle.IsEmpty)
                {
                    _detectorInput.ErodeDilateIterations = (int) spinDilateIterations.Value;
                    _detectorInput.Settings.Roi = GetRegionOfInterestFromControls();
                    _detectorInput.Captured = matCaptured;

                    var output = _colorDetector.Process(_detectorInput);

                    DrawReticle(output.CapturedImage, output.CentralPoint.ToPoint(), Color.Aqua);

                    if (output.IsDetected)
                    {
                        var radius = 50;
                        var circle = new CircleF(output.CentralPoint, radius);
                        var color = new Bgr(Color.Yellow);
                        output.CapturedImage.Draw(circle, color, 3);
                        var ballTextLocation = output.CentralPoint.ToPoint();
                        ballTextLocation.X += radius;
                        //  output.CapturedImage.Draw("ball", ballTextLocation, FontFace.HersheyPlain, 3, color);
                    }

                    if (checkBoxRoi.Checked)
                    {
                        output.CapturedImage.Draw(_detectorInput.Settings.Roi, Color.Green.ToBgr(), 3);
                    }

                    if (!_imageBoxSelector.SeedingRectangle.IsEmpty)
                    {
                        output.CapturedImage.Draw(_imageBoxSelector.SeedingRectangle, new Bgr(Color.Chartreuse));
                    }

                    imageBoxCaptured.Image = output.CapturedImage;
                    imageBoxFiltered.Image = output.ThresholdImage;

                    NotifyStatus(
                        "Retrieved frame in {0}, {1}"
                        , retrieveElapsed.Elapsed.ToHumanReadable(HumanReadableTimeSpanOptions.Abbreviated)
                        , output);
                }
                else
                {
                    DoAutoThresholding(matCaptured);
                }

                ResizeImageControls();

            }
        }
Exemplo n.º 6
0
 public Spaceship(TextureRegion2D textureRegion, IBulletFactory bulletFactory)
 {
     _bulletFactory = bulletFactory;
     _sprite = new Sprite(textureRegion)
     {
         Scale = Vector2.One * 0.5f,
         Position = new Vector2(400, 240)
     };
     _boundingCircle = new CircleF(_sprite.Position, 20);
 }
Exemplo n.º 7
0
        public void CircleF_EqualsCircleF()
        {
            var circle1 = new CircleF(123.45f, 456.78f, 100.10f);
            var circle2 = new CircleF(123.45f, 456.78f, 100.10f);
            var circle3 = new CircleF(123.45f, 555.55f, 100.10f);
            var circle4 = new CircleF(222.22f, 456.78f, 100.10f);

            TheResultingValue(circle1.Equals(circle2)).ShouldBe(true);
            TheResultingValue(circle1.Equals(circle3)).ShouldBe(false);
            TheResultingValue(circle1.Equals(circle4)).ShouldBe(false);
        }
Exemplo n.º 8
0
        public Meteor(TextureRegion2D textureRegion, Vector2 position, Vector2 velocity, float rotationSpeed, int size)
        {
            _sprite = new Sprite(textureRegion);
            _boundingCircle = new CircleF(_sprite.Position, _radius * size);

            Position = position;
            Velocity = velocity;
            RotationSpeed = rotationSpeed;
            HealthPoints = 1;
            Size = size;
        }
Exemplo n.º 9
0
        public void SpawnNewMeteor(Vector2 playerPosition)
        {
            var rotationSpeed = _random.Next(-10, 10) * 0.1f;
            var spawnCircle = new CircleF(playerPosition, 630);
            var spawnAngle = MathHelper.ToRadians(_random.Next(0, 360));
            var spawnPosition = spawnCircle.GetPointAlongEdge(spawnAngle);
            var velocity = (playerPosition - spawnPosition).Rotate(MathHelper.ToRadians(_random.Next(-15, 15))) * _random.Next(3, 10) * 0.01f;
            var textureRegion = GetMeteorRegion(4);
            var meteor = new Meteor(textureRegion, spawnPosition, velocity, rotationSpeed, 3);

            _entityManager.AddEntity(meteor);
        }
        public static FeatureVector createFirstHypothesis(Image<Bgr, Byte> imagen)
        {
            List<PointF> fingertips = new List<PointF>();

               fingertips.Add(new PointF(110,220));
               fingertips.Add(new PointF(175, 60));
               fingertips.Add(new PointF(270, 4));
               fingertips.Add(new PointF(410, 26));
               fingertips.Add(new PointF(640, 200));

               PointF punto = new PointF(400, 400);
               //List<PointF> newFingertips = new List<PointF>();
               List<float> angles = calculateFingerAngles(fingertips, punto);

               FeatureVector vector = new FeatureVector(fingertips, angles, punto, 5);

               //dibujar punto central mano
               PointF puntoC = new PointF(400, 400);
               Point punt = new Point(400, 400);
               CircleF centerCircle = new CircleF(puntoC, 5f);
               imagen.Draw(centerCircle, new Bgr(Color.Brown), 3);

               foreach (PointF p in fingertips)
               {

               CircleF circle = new CircleF(p, 5f);

               imagen.Draw(circle, new Bgr(Color.Red), 3);

               Point pun = new Point(int.Parse(p.X.ToString()), int.Parse(p.Y.ToString()));
               LineSegment2D lineaDedoCentro = new LineSegment2D(pun, punt);
               imagen.Draw(lineaDedoCentro, new Bgr(Color.Green), 2);

               }

               Point p1 = new Point(int.Parse((puntoC.X - 90).ToString()), int.Parse((puntoC.Y - 90).ToString()));
               Point p2 = new Point(int.Parse((puntoC.X - 90).ToString()), int.Parse((puntoC.Y + 90).ToString()));
               Point p3 = new Point(int.Parse((puntoC.X + 90).ToString()), int.Parse((puntoC.Y - 90).ToString()));
               Point p4 = new Point(int.Parse((puntoC.X + 90).ToString()), int.Parse((puntoC.Y + 90).ToString()));

               LineSegment2D line = new LineSegment2D(p1, p2);
               LineSegment2D line1 = new LineSegment2D(p1, p3);
               LineSegment2D line2 = new LineSegment2D(p3, p4);
               LineSegment2D line3 = new LineSegment2D(p2, p4);

               imagen.Draw(line, new Bgr(Color.Brown), 3);
               imagen.Draw(line1, new Bgr(Color.Brown), 3);
               imagen.Draw(line2, new Bgr(Color.Brown), 3);
               imagen.Draw(line3, new Bgr(Color.Brown), 3);

               return vector;
        }
Exemplo n.º 11
0
        public void CircleF_OpInequality()
        {
            var circle1 = new CircleF(123.45f, 456.78f, 100.10f);
            var circle2 = new CircleF(123.45f, 456.78f, 100.10f);
            var circle3 = new CircleF(123.45f, 555, 100.10f);
            var circle4 = new CircleF(222, 456.78f, 100.10f);
            var circle5 = new CircleF(123.45f, 456.78f, 200);

            TheResultingValue(circle1 != circle2).ShouldBe(false);
            TheResultingValue(circle1 != circle3).ShouldBe(true);
            TheResultingValue(circle1 != circle4).ShouldBe(true);
            TheResultingValue(circle1 != circle5).ShouldBe(true);
        }
Exemplo n.º 12
0
        private static void DrawSet(Image<Bgr, Byte> table, Dictionary<Card, System.Drawing.Point> cards, Random rnd, List<Card> set)
        {
            Bgr setcolor = new Bgr(rnd.Next(255), rnd.Next(255), rnd.Next(255));
            List<System.Drawing.Point> centers = new List<System.Drawing.Point>();

            foreach (Card card in set)
            {
                System.Drawing.Point p = cards[card];
                PointF center = new PointF(p.X, p.Y);
                centers.Add(p);
                CircleF circle = new CircleF(center, 50);
                table.Draw(circle, setcolor, 2);
            }

            table.DrawPolyline(centers.ToArray(), true, setcolor, 5);
        }
Exemplo n.º 13
0
        private static void DrawMotion(Image<Bgr, Byte> image, System.Drawing.Rectangle motionRegion, double angle, Bgr color)
        {
            float circleRadius = (motionRegion.Width + motionRegion.Height) >> 2;
             Point center = new Point(motionRegion.X + motionRegion.Width >> 1, motionRegion.Y + motionRegion.Height >> 1);

             CircleF circle = new CircleF(
            center,
            circleRadius);

             int xDirection = (int)(Math.Cos(angle * (Math.PI / 180.0)) * circleRadius);
             int yDirection = (int)(Math.Sin(angle * (Math.PI / 180.0)) * circleRadius);
             Point pointOnCircle = new Point(
             center.X + xDirection,
             center.Y - yDirection);
             LineSegment2D line = new LineSegment2D(center, pointOnCircle);

             image.Draw(circle, color, 1);//
             image.Draw(line, color, 2);
        }
Exemplo n.º 14
0
        private static void DrawMotion(IInputOutputArray image, Rectangle motionRegion, double angle, Bgr color)
        {
            //CvInvoke.Rectangle(image, motionRegion, new MCvScalar(255, 255, 0));
            float circleRadius = (motionRegion.Width + motionRegion.Height) >> 2;
            Point center       = new Point(motionRegion.X + (motionRegion.Width >> 1), motionRegion.Y + (motionRegion.Height >> 1));

            CircleF circle = new CircleF(
                center,
                circleRadius);

            int   xDirection    = (int)(Math.Cos(angle * (Math.PI / 180.0)) * circleRadius);
            int   yDirection    = (int)(Math.Sin(angle * (Math.PI / 180.0)) * circleRadius);
            Point pointOnCircle = new Point(
                center.X + xDirection,
                center.Y - yDirection);
            LineSegment2D line = new LineSegment2D(center, pointOnCircle);

            CvInvoke.Circle(image, Point.Round(circle.Center), (int)circle.Radius, color.MCvScalar);
            CvInvoke.Line(image, line.P1, line.P2, color.MCvScalar);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Draws a partially defined graph edge</summary>
        /// <param name="fromNode">Source node, or null</param>
        /// <param name="fromRoute">Source route, or null</param>
        /// <param name="toNode">Destination node, or null</param>
        /// <param name="toRoute">Destination route, or null</param>
        /// <param name="label">Edge label</param>
        /// <param name="endPoint">Endpoint to substitute for source or destination, if either is null</param>
        /// <param name="g">Graphics object</param>
        public override void Draw(
            TNode fromNode,
            NumberedRoute fromRoute,
            TNode toNode,
            NumberedRoute toRoute,
            string label,
            Point endPoint,
            Graphics g)
        {
            Matrix inverse = g.Transform;

            inverse.Invert();
            PointF end = GdiUtil.Transform(inverse, endPoint);

            TNode   node     = (fromNode != null) ? fromNode : toNode;
            CircleF boundary = GetBoundary(node);
            Vec2F   proj     = new Vec2F();

            if (CircleF.Project(new Vec2F(end), boundary, ref proj))
            {
                PointF start = new PointF(proj.X, proj.Y);
                g.DrawLine(m_theme.OutlinePen, start, end);

                if (fromNode == null)
                {
                    PointF temp = end;
                    end   = start;
                    start = temp;
                }
                Vec2F endTangent    = new Vec2F(end.X - start.X, end.Y - start.Y);
                Vec2F arrowPosition = new Vec2F(end);
                DrawArrow(arrowPosition, endTangent, m_theme.OutlinePen, g);

                if (!string.IsNullOrEmpty(label))
                {
                    PointF     textPoint = new PointF((end.X + start.X) * 0.5f, (end.Y + start.Y) * 0.5f);
                    RectangleF textBox   = new RectangleF(textPoint.X - 512, textPoint.Y, 1024, m_theme.Font.Height);
                    g.DrawString(label, m_theme.Font, m_theme.TextBrush, textBox, m_theme.CenterStringFormat);
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a mask for masking out the horizon region and circlea around each currently tracked feature.
        /// </summary>
        /// <param name="currentlyTrackedFeatures"></param>
        /// <param name="skyBottom"></param>
        /// <param name="groundTop"></param>
        private void UpdateMaskImage(Size size, List <TrackedFeature> currentlyTrackedFeatures, int skyRegionBottom, int groundRegionTop)
        {
            Gray blockedAreaColor     = new Gray(0);         // black
            Gray transparentAreaColor = new Gray(255);       // white

            m_MaskImage.SetValue(transparentAreaColor);      // fill

            // We mask out the area between the top of the ground region and the bottom of the sky region
            Rectangle rectangle = new Rectangle(0, skyRegionBottom, m_MaskImage.Width, groundRegionTop - skyRegionBottom);

            m_MaskImage.Draw(rectangle, blockedAreaColor, -1);

            // We also mask out a circle around each currently tracked feature to avoid the we find a new feature too close to an already tracked feature.
            int circleRadius = (int)(m_MinDistance + 0.5);

            for (int i = 0; i < currentlyTrackedFeatures.Count; i++)
            {
                CircleF circle = new CircleF(currentlyTrackedFeatures[i][0], circleRadius);
                m_MaskImage.Draw(circle, blockedAreaColor, -1);
            }
        }
Exemplo n.º 17
0
        private void UpdateMaskImage(Size size, List <TrackedFeature> currentlyTrackedFeatures, int skyRegionBottom, int groundRegionTop)
        {
            Gray blockedAreaColor     = new Gray(0);
            Gray transparentAreaColor = new Gray(255);

            m_MaskImage.SetValue(transparentAreaColor);


            Rectangle rectangle = new Rectangle(0, skyRegionBottom, m_MaskImage.Width, groundRegionTop - skyRegionBottom);

            m_MaskImage.Draw(rectangle, blockedAreaColor, -1);


            int circleRadius = (int)(m_MinDistance + 0.5);

            for (int i = 0; i < currentlyTrackedFeatures.Count; i++)
            {
                CircleF circle = new CircleF(currentlyTrackedFeatures[i][0], circleRadius);
                m_MaskImage.Draw(circle, blockedAreaColor, -1);
            }
        }
        private Boolean isInHands(CircleF circle)
        {
            DepthImagePoint point = new DepthImagePoint();

            point.X     = (int)circle.Center.X;
            point.Y     = (int)circle.Center.Y;
            point.Depth = depthRawValues[point.Y * 640 + point.X]; // 640 means the width of the frame.
            point.Depth = point.Depth >> 3;
            Console.WriteLine(point.Depth);
            SkeletonPoint spoint = myKinect.CoordinateMapper.MapDepthPointToSkeletonPoint(DepthImageFormat.Resolution640x480Fps30, point);

            if (firstSkeleton != null && Math.Abs(spoint.X - handLeft.X) < 0.1 && Math.Abs(spoint.Y - handLeft.Y) < 0.1 && Math.Abs(spoint.Z - handLeft.Z) < 0.1)
            {
                return(true);
            }
            else if (firstSkeleton != null && Math.Abs(spoint.X - handRight.X) < 0.1 && Math.Abs(spoint.Y - handRight.Y) < 0.1 && Math.Abs(spoint.Z - handRight.Z) < 0.1)
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 19
0
        private static void DrawMotion(Image <Bgr, Byte> image, System.Drawing.Rectangle motionRegion, double angle, Bgr color)
        {
            float circleRadius = (motionRegion.Width + motionRegion.Height) >> 2;

            System.Drawing.Point center = new System.Drawing.Point(motionRegion.X + motionRegion.Width >> 1, motionRegion.Y + motionRegion.Height >> 1);

            CircleF circle = new CircleF(
                center,
                circleRadius);

            int xDirection = (int)(Math.Cos(angle * (Math.PI / 180.0)) * circleRadius);
            int yDirection = (int)(Math.Sin(angle * (Math.PI / 180.0)) * circleRadius);

            System.Drawing.Point pointOnCircle = new System.Drawing.Point(
                center.X + xDirection,
                center.Y - yDirection);
            LineSegment2D line = new LineSegment2D(center, pointOnCircle);

            image.Draw(circle, color, 1);
            image.Draw(line, color, 2);
        }
        /// <summary>
        /// Starts the ball following logic
        /// </summary>
        /// <param name="sender">not needed</param>
        public void BallFollowing(object sender = null)
        {
            Image <Bgr, byte> original = _currentVideoCapture.QueryFrame().ToImage <Bgr, Byte>();
            double            max_x    = original.Width;
            double            middle_x = max_x / 2;
            double            entity   = 1000 / middle_x;

            using (Image <Hsv, byte> imageFrame = _currentVideoCapture.QueryFrame().ToImage <Hsv, Byte>())
            {
                if (imageFrame != null)
                {
                    CircleF detectedCircle = SearchCircle(imageFrame);

                    if (detectedCircle.Radius >= GetProperties().MinRadius)
                    {
                        original.Draw(detectedCircle, new Bgr(0, 255, 255), 2);
                        original.Draw(new CircleF(detectedCircle.Center, 2), new Bgr(0, 255, 255), 2);

                        double current_x = detectedCircle.Center.X;
                        double p         = 0;

                        if (current_x >= middle_x)
                        {
                            p = entity * (current_x - middle_x); // p = 1000 => ganz rechts vom roboter
                        }
                        else
                        {
                            p = -entity * (middle_x - current_x); // p = -1000 => ganz links vom roboter
                        }
                        WriteMotorCommand(p, detectedCircle.Radius);
                    }
                    else
                    {
                        log.Debug("anhalten");
                        Motor.Instance.PullUp();
                    }
                }
                PublishFrame(1, original, "Original Input");
            }
        }
Exemplo n.º 21
0
        private void DetectSecondRule(CircleF currentFrameBall, CircleF lastFrameBall, CircleF lastFrameBallInHand, VectorOfPoint hand, Mat image)
        {
            // compare last frame ball coordinates with current frame ball coordinates

            // if y axis is highier in current frame - loop again
            if (currentFrameBall.Center.Y < lastFrameBall.Center.Y)
            {
                //recordedHeight = ((lastFrameBallInHand.Center.Y - currentFrameBall.Center.Y) * 2) / lastFrameBall.Radius;
                return;
            }

            if (currentFrameBall.Center.Y > lastFrameBall.Center.Y && currentFrameBall.Center.Y > lastFrameBallInHand.Center.Y)
            {
                rule           = InitiateRule.FirstRule;
                recordedHeight = -1;
                //recordedHeight = ((lastFrameBallInHand.Center.Y - currentFrameBall.Center.Y) * 2) / lastFrameBall.Radius;
                return;
            }

            // if y axis is highier than when ball was in hand but lower that last frame - calculate height (last frame - last fame in hand
            if (currentFrameBall.Center.Y > lastFrameBall.Center.Y && currentFrameBall.Center.Y < lastFrameBallInHand.Center.Y)
            {
                float height = lastFrameBallInHand.Center.Y - lastFrameBall.Center.Y;
                if (height >= (lastFrameBall.Radius * 2 * 4))
                {
                    line = new LineSegment2D(new System.Drawing.Point(
                                                 (int)lastFrameBall.Center.X,
                                                 (int)lastFrameBall.Center.Y),
                                             new System.Drawing.Point((int)lastFrameBallInHand.Center.X,
                                                                      (int)lastFrameBallInHand.Center.Y)
                                             );
                }
                recordedHeight = (height * 2) / lastFrameBall.Radius;
                rule           = InitiateRule.FirstRule;
                return;
            }
            // if ball is not recognized for 1 second - count as failed pass - go to first rule.

            // need logging
        }
Exemplo n.º 22
0
        public static void CircleX(Image <Gray, byte> img, CircleF circle, double targetRatio)
        {
            double centerX = circle.Center.X;
            double centerY = circle.Center.Y;
            double r       = circle.Radius;
            int    sum     = 0;

            #region point values(center -> left)
            List <int> values = new List <int>();
            for (int x = (int)System.Math.Ceiling(centerX); x >= (int)System.Math.Floor(centerX - r); x--)
            {
                values.Add(img.Data[(int)System.Math.Ceiling(centerY), x, 0]);
            }
            new Logger("Analyzer").Debug($"CountPixels(point):  [{Utils.String.FromList<int>(values)}]';");
            #endregion

            for (int x = (int)System.Math.Floor(centerX - r); x <= (int)System.Math.Ceiling(centerX); x++)
            {
                sum += img.Data[(int)System.Math.Ceiling(centerY), x, 0];
            }

            List <int> SumOnRadius = new List <int>();
            for (int radius = AnalyzerIntf.CfgMinRadiusFor865 - 1; radius <= circle.Radius; radius++)
            {
                int rsum = 0;

                for (int x = (int)System.Math.Floor(centerX - radius); x <= (int)System.Math.Ceiling(centerX); x++)
                {
                    rsum += img.Data[(int)System.Math.Ceiling(centerY), x, 0];
                }
                SumOnRadius.Add(rsum);

                //new Logger("Analyzer").Debug($"r {radius} rXsum {rsum} Xsum {sum} ratio {(double)rsum / sum:F3}");
                if ((double)rsum / sum > targetRatio)
                {
                    break;
                }
            }
            new Logger("Analyzer").Debug($"CountPixels(Xsum): [{Utils.String.FromList<int>(SumOnRadius)}]';");
        }
Exemplo n.º 23
0
        public override Vector2 Calculate()
        {
            // The detection box is the current velocity divided by the max velocity of the entity
            // range is the maximum size of the box
            Vector2 viewBox = this.Entity.Velocity / this.Entity.MaxSpeed * this.range;

            // Add the check points in front of the entity
            IEnumerable <Vector2> checkpoints = new[]
            {
                this.Entity.Position,
                this.Entity.Position + viewBox / 2f, // Halfway
                this.Entity.Position + viewBox,      // At the end
                this.Entity.Position + viewBox * 2   // Double
            };

            foreach (Rock o in this.world.Entities.OfType <Rock>())
            {
                // Add a circle around the obstacle which can't be crossed
                CircleF notAllowedZone = new CircleF(o.Position, o.Scale);

                if (checkpoints.Any(checkpoint => notAllowedZone.Contains(checkpoint)))
                {
                    Vector2 dist          = new Vector2(o.Position.X - this.Entity.Position.X, o.Position.X - this.Entity.Position.Y);
                    Vector2 perpendicular = Vector2Helper.PerpendicularRightAngleOf(dist);

                    Vector2 perpendicularPositivePos = o.Position + perpendicular;
                    Vector2 perpendicularNegativePos = o.Position - perpendicular;

                    float perpDistPositive = Vector2.DistanceSquared(this.Entity.Position + this.Entity.Velocity, perpendicularPositivePos);
                    float perpDistNegative = Vector2.DistanceSquared(this.Entity.Position + this.Entity.Velocity, perpendicularNegativePos);

                    Vector2 targetRelative = (perpDistPositive > perpDistNegative ? perpendicularNegativePos : perpendicularPositivePos) - this.Entity.Position;

                    return(Vector2Helper.PerpendicularRightAngleOf(targetRelative));
                }
            }

            // Return identity vector if there will be no collision
            return(new Vector2());
        }
Exemplo n.º 24
0
        public void FindPoles(Image <Gray, byte> thresholdedPerspImage, Image <Bgr, byte> perspImage)
        {
            // Use a convolution to sharpen it such that the centre of the bar is a peak
            Image <Gray, float> convImage = thresholdedPerspImage.Convolution(m_KernelPole);

            //DebugImage = ThresholdedPerspImage.Convert<Bgr, byte>();
            DebugImage = perspImage;

            for (int poleNum = 0; poleNum < 8; poleNum++)
            {
                Pole pole = m_Poles[poleNum];
                for (int sliceNum = 0; sliceNum < 2; sliceNum++)
                {
                    for (int mx = pole.SearchX - 20; mx < pole.SearchX + 20; mx++)
                    {
                        int   y         = pole.SliceYs[sliceNum];
                        float intensity = convImage.Data[y, mx, 0];
                        if (intensity > 400)
                        {
                            CircleF circ = new CircleF(new PointF(mx, y), 3);
                            DebugImage.Draw(circ, new Bgr(0, intensity / 3, 150), 2);
                            m_Poles[poleNum].AddPoint(sliceNum, new PointF(mx, pole.SliceYs[sliceNum]));
                        }
                    }
                }
            }

            //return;

            for (int poleNum = 0; poleNum < 8; poleNum++)
            {
                Pole pole = m_Poles[poleNum];
                if (pole.IsFound)
                {
                    pole.FindMen(perspImage);
                    var line = pole.CalcLine();
                    DebugImage.Draw(line, new Bgr(20, 250, 50), 4);
                }
            }
        }
        private static Vector2 PenetrationVector(CircleF circ1, CircleF circ2)
        {
            Debug.Assert(circ1.Intersects(circ2));

            var displacement = PointF.Displacement(circ1.Center, circ2.Center);

            Vector2 desiredDisplacement;

            if (displacement != Vector2.Zero)
            {
                desiredDisplacement = displacement.NormalizedCopy() * (circ1.Radius + circ2.Radius);
            }
            else
            {
                desiredDisplacement = -Vector2.UnitY * (circ1.Radius + circ2.Radius);
            }


            var penetration = displacement - desiredDisplacement;

            return(penetration);
        }
Exemplo n.º 26
0
        private void colorBubbles(AnswerLine a, Bitmap source, int row)
        {
            int   i           = 0;
            float quickRadius = (float)(1.25 * base.avRadius);
            int   halfRadius  = (int)(quickRadius / 2);

            CircleF[] bubbles = new CircleF[12];
            int[]     pixels  = new int[12];

            foreach (AnswerLine b in base.xLines)
            {
                CircleF bubble = new CircleF(new Point(b.grabAverage(), a.grabAverage()), quickRadius);

                bubbles[i] = bubble;

                //Calculate the amount of colored pixels to detect colored in circles
                int totalPixel = 0;
                for (int x = b.grabAverage() - halfRadius; x <= b.grabAverage() + halfRadius; x++)
                {
                    for (int y = a.grabAverage() - halfRadius; y <= a.grabAverage() + halfRadius; y++)
                    {
                        if (Math.Pow((double)(x - b.grabAverage()), 2) + Math.Pow((double)(y - a.grabAverage()), 2) <= Math.Pow((1.25) * base.avRadius, 2))
                        {
                            totalPixel = totalPixel + (255 - source.GetPixel(x, y).R) + (255 - source.GetPixel(x, y).B) + (255 - source.GetPixel(x, y).G);
                        }
                    }
                }
                pixels[i] = (int)(totalPixel / bubble.Area);
                i         = i + 1;
            }
            while (this.colorArray[row] != pixels)
            {
                this.colorArray[row] = pixels;
            }
            while (this.centerCircles[row] != bubbles)
            {
                this.centerCircles[row] = bubbles;
            }
        }
Exemplo n.º 27
0
        /// <summary>
        ///   Checks whether the specified rectangle intersects the passed circle.
        /// </summary>
        /// <param name="rectangle">
        ///   Rectangle to check.
        /// </param>
        /// <param name="circle">
        ///   Circle to check.
        /// </param>
        /// <returns>
        ///   <c>true</c>, if rectangle and circle intersect each other, and <c>false</c> otherwise.
        /// </returns>
        public static bool Intersects(this RectangleF rectangle, CircleF circle)
        {
            // Check if rectangle contains center.
            if (rectangle.Contains(circle.Center))
            {
                return true;
            }

            // Check each edge.
            var topLeft = new Vector2F(rectangle.X, rectangle.Y);
            var bottomLeft = new Vector2F(rectangle.X, rectangle.MaxY);
            var topRight = new Vector2F(rectangle.MaxX, rectangle.Y);
            var bottomRight = new Vector2F(rectangle.MaxX, rectangle.MaxY);

            var left = new LineSegment2F(topLeft, bottomLeft);
            var right = new LineSegment2F(topRight, bottomRight);
            var top = new LineSegment2F(topLeft, topRight);
            var bottom = new LineSegment2F(bottomLeft, bottomRight);

            return left.Intersects(circle) || right.Intersects(circle) || top.Intersects(circle)
                   || bottom.Intersects(circle);
        }
Exemplo n.º 28
0
        private bool Pick(TEdge edge, Vec2F p)
        {
            bool  result  = false;
            Vec2F nearest = new Vec2F();

            Vec2F   startPoint  = new Vec2F();
            Vec2F   endPoint    = new Vec2F();
            CircleF c           = new CircleF();
            bool    moreThan180 = false;
            int     route       = edge.FromRoute.Index;

            if (GetEdgeGeometry(edge, route, ref startPoint, ref endPoint, ref c, ref moreThan180))
            {
                Seg2F seg = new Seg2F(startPoint, endPoint);
                nearest = Seg2F.Project(seg, p);
                if (Vec2F.Distance(nearest, p) < m_theme.PickTolerance)
                {
                    result = true;
                }
            }
            else
            {
                if (CircleF.Project(p, c, ref nearest))
                {
                    if (Vec2F.Distance(nearest, p) < m_theme.PickTolerance)
                    {
                        Vec2F startToEnd    = endPoint - startPoint;
                        Vec2F startToCenter = c.Center - startPoint;
                        Vec2F startToP      = p - startPoint;
                        float pdp1          = Vec2F.PerpDot(startToCenter, startToEnd);
                        float pdp2          = Vec2F.PerpDot(startToP, startToEnd);
                        bool  side          = pdp1 * pdp2 < 0;
                        result = moreThan180 ^ side;
                    }
                }
            }

            return(result);
        }
Exemplo n.º 29
0
        private static bool TryFindCircleInFullFrame(IndicatorData data, out CircleF ret)
        {
            ret = default(CircleF);

            if (RollIndicator.TryFindRollCircleInFullFrame(data, out var circle))
            {
                circle.Center = new PointF(circle.Center.X + 140, circle.Center.Y + 70);
                circle.Radius = 55;
                var firstCrop = Math2.CropCircle(circle, 10);
                var focus     = data.Frame.SafeCopy(firstCrop);

                var circles = CvInvoke.HoughCircles(focus.Convert <Hsv, byte>()[2], HoughType.Gradient, 2.0, 20, 10, 180, 45, 55);
                if (circles.Length == 1)
                {
                    circles[0].Center = circles[0].Center.Add(firstCrop.Location);
                    circles[0].Radius = 50;
                    ret = circles[0];
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 30
0
        public override void ActionExcute()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            _imageInput = VisionManage.listScene[VisionManage.iCurrSceneIndex].listAction[actionData.imageSrc - 1].imageResult.Clone();


            Image <Gray, byte> _image = imageInput.Clone();

            if (0 != actionSimpleBlobData.InputAOIWidth && 0 != actionSimpleBlobData.InputAOIHeight)
            {
                _image.ROI = new Rectangle(actionSimpleBlobData.InputAOIX, actionSimpleBlobData.InputAOIY, actionSimpleBlobData.InputAOIWidth, actionSimpleBlobData.InputAOIHeight);
            }
            Mat mask = new Mat(_image.Size, DepthType.Cv16S, 1);
            VectorOfKeyPoint vectorOfKeyPoint = new VectorOfKeyPoint();

            MKeyPoint[] keyPoint;

            keyPoint = sBDetector.Detect(_image);


            for (int i = 0; i < keyPoint.Length; i++)
            {
                CircleF cf1 = new CircleF(keyPoint[i].Point, 6);
                _image.Draw(cf1, new Gray(100), 2, Emgu.CV.CvEnum.LineType.EightConnected, 0);
            }


            _imageResult = _imageInput.Clone();

            _image.CopyTo(_imageResult);
            if (actionSimpleBlobData.bROIReset)
            {
                CvInvoke.cvResetImageROI(_imageResult);
            }
            CvInvoke.cvResetImageROI(_imageInput);
            sw.Stop();
        }
Exemplo n.º 31
0
 public static VectorOfVectorOfPoint FindContours(Image <Bgr, Byte> scr)
 {
     using (Image <Gray, byte> Gray_Image = scr.Convert <Gray, byte>())
     {
         using (Image <Gray, byte> Threshold_Image = new Image <Gray, byte>(Gray_Image.Size))
         {
             CvInvoke.Threshold(Gray_Image, Threshold_Image, Threshold_Value, 255, ThresholdType.BinaryInv);
             VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
             CvInvoke.FindContours(Threshold_Image, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
             for (int i = 0; i < contours.Size; i++)
             {
                 CircleF cir = CvInvoke.MinEnclosingCircle(contours[i]);
                 //System.Console.WriteLine(cir.Radius);
                 if (cir.Radius < 80)
                 {
                     contours[i].Dispose();
                 }
             }
             return(contours);
         }
     }
 }
Exemplo n.º 32
0
        private static void Animation_tick(object sender, EventArgs e)
        {
            // primitive for now
            // creates 200 x 200 pixel picture, with a circle moving across it
            Image <Bgr, byte> img = new Image <Bgr, byte> (200, 200, new Bgr(255, 0, 0));

            // circle has touched top edge last, going downwards
            if (!backwards)
            {
                xfCirc = xfCirc + 1.0f;
                yfCirc = yfCirc + 1.0f;
            }
            // circle has last touched the bottom edge, going upwards
            else
            {
                xfCirc -= 1.0f;
                yfCirc -= 1.0f;
            }



            if (xfCirc > 190f)
            {
                // reached the bottom!
                backwards = true;
            }
            else if (xfCirc < 10.0f)
            {
                // reached the top!;
                backwards = false;
            }
            PointF  circleCenter = new PointF(xfCirc, yfCirc);
            CircleF circle       = new CircleF(circleCenter, 20f);

            img.Draw(circle, new Bgr(255, 255, 0), 10);
            CvInvoke.cvShowImage("Animation", img);
            CvInvoke.cvWaitKey(1);
        }
Exemplo n.º 33
0
        public void FindPoles(Image<Gray, byte> thresholdedPerspImage, Image<Bgr, byte> perspImage)
        {
            // Use a convolution to sharpen it such that the centre of the bar is a peak
            Image<Gray, float> convImage = thresholdedPerspImage.Convolution(m_KernelPole);

            //DebugImage = ThresholdedPerspImage.Convert<Bgr, byte>();
            DebugImage = perspImage;

            for (int poleNum = 0; poleNum < 8; poleNum++)
            {
                Pole pole = m_Poles[poleNum];
                for (int sliceNum = 0; sliceNum < 2; sliceNum++)
                    for (int mx = pole.SearchX - 20; mx < pole.SearchX + 20; mx++)
                    {
                        int y = pole.SliceYs[sliceNum];
                        float intensity = convImage.Data[y, mx, 0];
                        if (intensity > 400)
                        {
                            CircleF circ = new CircleF(new PointF(mx, y), 3);
                            DebugImage.Draw(circ, new Bgr(0, intensity / 3, 150), 2);
                            m_Poles[poleNum].AddPoint(sliceNum, new PointF(mx, pole.SliceYs[sliceNum]));
                        }
                    }
            }

            //return;

            for (int poleNum = 0; poleNum < 8; poleNum++)
            {
                Pole pole = m_Poles[poleNum];
                if (pole.IsFound)
                {
                    pole.FindMen(perspImage);
                    var line = pole.CalcLine();
                    DebugImage.Draw(line, new Bgr(20, 250, 50), 4);
                }
            }
        }
Exemplo n.º 34
0
    public static Vector2 CalculatePenetrationVector(Point2 point, CircleF otherCircle, Vector2 velocity,
                                                     Vector2 otherVelocity, Vector2 oldDistance)
    {
        var a = velocity.Dot(velocity);
        var b = 2 * velocity.Dot(oldDistance);
        var c = oldDistance.Dot(oldDistance);

        if (c < 0)
        {
            // already overlapping
            return(new CircleF(point, 0).CalculatePenetrationVector(otherCircle));
        }

        if (SolveQuadraticFormula(a, b, c, out var u0, out var u1))
        {
            var maxPenetrationAt = (u0 + u1) / 2;
            point += velocity * maxPenetrationAt;
            otherCircle.Position += otherVelocity * maxPenetrationAt;
            return(new CircleF(point, 0).CalculatePenetrationVector(otherCircle));
        }

        return(Vector2.Zero);
    }
Exemplo n.º 35
0
        private void DrawPupil(Rectangle roi)
        {
            if (FoundPupil)
            {
                CircleF pCircleMin = new CircleF(this.pupilCenter.ToPoint(), GTSettings.Current.ProcessingSettings.PupilSizeMinimum);
                CircleF pCircleMax = new CircleF(this.pupilCenter.ToPoint(), GTSettings.Current.ProcessingSettings.PupilSizeMaximum);

                switch (GTSettings.Current.ProcessingSettings.VideoMode)
                {
                case VideoModeEnum.Normal:
                    this.DrawCross(this.gray, this.pupilCenter.ToPoint(), 800, pupilCrossGray, 1);
                    this.DrawCircle(this.gray, pCircleMin, new Gray(155), 1);
                    this.DrawCircle(this.gray, pCircleMax, new Gray(155), 1);
                    break;

                case VideoModeEnum.Processed:
                    this.DrawCross(this.processed, this.pupilCenter.ToPoint(), 800, System.Drawing.Color.DarkGreen, 1);
                    this.DrawCircle(this.processed, pCircleMin, pupilCircleMinColor, 1);
                    this.DrawCircle(this.processed, pCircleMax, pupilCircleMaxColor, 1);
                    break;
                }
            }
        }
Exemplo n.º 36
0
        public static float[] shapeFeatures(Image <Bgr, Byte> src)
        {
            List <float>  vectorOfFeatures = new List <float>();
            VectorOfPoint maxContour       = getMaxContour(src);

            if (maxContour != null)
            {
                // Shape features
                Rectangle   bounds       = CvInvoke.BoundingRectangle(maxContour);
                CircleF     circle       = CvInvoke.MinEnclosingCircle(maxContour);
                RotatedRect ellipse      = CvInvoke.FitEllipse(maxContour);
                float       area         = Convert.ToSingle(CvInvoke.ContourArea(maxContour, false));
                float       perimeter    = Convert.ToSingle(CvInvoke.ArcLength(maxContour, true));
                float       shape        = Convert.ToSingle((4 * Math.PI * area) / Math.Pow(perimeter, 2));
                int         npoints      = maxContour.Size;
                float       width        = bounds.Width;
                float       height       = bounds.Height;
                float       centroideY   = circle.Center.Y;
                float       centroideX   = circle.Center.X;
                float       radius       = circle.Radius;
                float       aspectRatio  = width / height;
                float       extent       = Convert.ToSingle(area / (width * height));
                float       eccentricity = Convert.ToSingle(ellipse.Size.Height / ellipse.Size.Width);
                //float density = Convert.ToSingle(CvInvoke.CountNonZero(mask));
                //float equivDiameter = Convert.ToSingle(Math.Sqrt(4 * area / Math.PI));
                PointF[] hull     = CvInvoke.ConvexHull(maxContour.ToArray().Select(pt => new PointF(pt.X, pt.Y)).ToArray());
                float    solidity = 0;
                using (VectorOfPoint hullContourn = new VectorOfPoint(hull.Select(pt => new Point((int)pt.X, (int)pt.Y)).ToArray()))
                    solidity = Convert.ToSingle(area / CvInvoke.ContourArea(hullContourn, false));

                vectorOfFeatures.AddRange(new float[] {
                    area, shape, perimeter, npoints, width, height, centroideY, centroideX, radius, aspectRatio, extent
                });
            }

            return(vectorOfFeatures.ToArray());
        }
Exemplo n.º 37
0
        // Paint contour of GOLF BALLS
        private void button5_Click(object sender, EventArgs e)
        {
            if (_inputImage == null)
            {
                return;
            }

            var mainImage = _inputImage;
            // get binary mask of _input image
            var image = GetRedPixelMask(_inputImage);

            // removes pixels on object boundaries.
            image.Erode(2);
            // connecting areas that are separated by spaces
            image.Dilate(2);

            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
            {
                CvInvoke.FindContours(image, contours, null, RetrType.External,
                                      ChainApproxMethod.ChainApproxSimple);

                for (int i = 0; i < contours.Size; i++)
                {
                    using (VectorOfPoint contour = contours[i])
                    {
                        CircleF circle = CvInvoke.MinEnclosingCircle(contour);
                        var     arr    = circle.Area;
                        if (arr > 1000)
                        {
                            CvInvoke.Circle(mainImage, new Point((int)circle.Center.X, (int)circle.Center.Y),
                                            (int)circle.Radius, new MCvScalar(255, 0, 255, 235), 2);
                        }
                        imageBox2.Image = mainImage;
                    }
                }
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Sort marks and fill the property
        /// CallibrationMarks
        /// </summary>
        /// <param name="unsortedMarks">Unsorted callibration marks list</param>
        private void SortCallibrationMarks(List <CircleF> unsortedMarks)
        {
            if (unsortedMarks.Count != 4)
            {
                throw new NotSupportedException("To find diagonal mark pairs exactly 4 marks must be detected!");
            }

            CallibrationMarks = new Dictionary <eCallibrationMark, CircleF>();

            Dictionary <CircleF, CircleF> diagonalPairs = FindDiagonalMarkPairs(unsortedMarks);

            //In each pair find left point, right, buttom and top and set corresponding marks
            foreach (CircleF key in diagonalPairs.Keys)
            {
                CircleF buttom = (key.Center.Y > diagonalPairs[key].Center.Y) ? key : diagonalPairs[key];
                CircleF top    = (key.Center.Y < diagonalPairs[key].Center.Y) ? key : diagonalPairs[key];
                CircleF left   = (key.Center.X < diagonalPairs[key].Center.X) ? key : diagonalPairs[key];
                CircleF right  = (key.Center.X > diagonalPairs[key].Center.X) ? key : diagonalPairs[key];

                if (buttom.Equals(left))
                {
                    CallibrationMarks.Add(eCallibrationMark.ButtomLeft, left);
                }
                if (top.Equals(left))
                {
                    CallibrationMarks.Add(eCallibrationMark.TopLeft, left);
                }
                if (top.Equals(right))
                {
                    CallibrationMarks.Add(eCallibrationMark.TopRight, right);
                }
                if (buttom.Equals(right))
                {
                    CallibrationMarks.Add(eCallibrationMark.ButtomRight, right);
                }
            }
        }
        // Détecte et dessine le nombre de doigts sur l'image traitée
        // Ce code vient en partie de ce projet : https://www.youtube.com/watch?v=Fjj9gqTCTfc
        public void DrawAndComputeFingers()
        {
            fingerNum = 0;

            // Boucle sur tous les "defects"
            for (int i = 0; i < defects.Total; i++)
            {
                // Détecte les points de départ, de fin et de profondeur
                PointF startPoint = new PointF((float)defectArray[i].StartPoint.X,
                                                (float)defectArray[i].StartPoint.Y);
                PointF depthPoint = new PointF((float)defectArray[i].DepthPoint.X,
                                                (float)defectArray[i].DepthPoint.Y);
                PointF endPoint = new PointF((float)defectArray[i].EndPoint.X,
                                                (float)defectArray[i].EndPoint.Y);

                // Lignes entre les différents points (départ - profondeur, profondeur - fin)
                LineSegment2D startDepthLine = new LineSegment2D(defectArray[i].StartPoint, defectArray[i].DepthPoint);
                LineSegment2D depthEndLine = new LineSegment2D(defectArray[i].DepthPoint, defectArray[i].EndPoint);

                // Cercles liés aux points de départ, profondeur et fin
                CircleF startCircle = new CircleF(startPoint, 5f);
                CircleF depthCircle = new CircleF(depthPoint, 5f);
                CircleF endCircle = new CircleF(endPoint, 5f);

                // Heuristique personnalisée d'après diverses expériences pour détecter si il s'agit d'un doigt ou non, d'après la position des points de départ, de profondeur et de fin et la taille de la box qui les contient
                if ((startCircle.Center.Y < box.center.Y || depthCircle.Center.Y < box.center.Y) && (startCircle.Center.Y < depthCircle.Center.Y) && (Math.Sqrt(Math.Pow(startCircle.Center.X - depthCircle.Center.X, 2) + Math.Pow(startCircle.Center.Y - depthCircle.Center.Y, 2)) > box.size.Height / 6.5))
                {
                    fingerNum++;
                    imgProc.Draw(startDepthLine, new Bgr(Color.Green), 2);
                }

                // Dessine les différents points
                imgProc.Draw(startCircle, new Bgr(Color.Red), 2);
                imgProc.Draw(depthCircle, new Bgr(Color.Yellow), 5);
                imgProc.Draw(endCircle, new Bgr(Color.DarkBlue), 4);
            }
        }
Exemplo n.º 40
0
        // Détecte et dessine le nombre de doigts sur l'image traitée
        // Ce code vient en partie de ce projet : https://www.youtube.com/watch?v=Fjj9gqTCTfc
        public void DrawAndComputeFingers()
        {
            fingerNum = 0;

            // Boucle sur tous les "defects"
            for (int i = 0; i < defects.Total; i++)
            {
                // Détecte les points de départ, de fin et de profondeur
                PointF startPoint = new PointF((float)defectArray[i].StartPoint.X,
                                               (float)defectArray[i].StartPoint.Y);
                PointF depthPoint = new PointF((float)defectArray[i].DepthPoint.X,
                                               (float)defectArray[i].DepthPoint.Y);
                PointF endPoint = new PointF((float)defectArray[i].EndPoint.X,
                                             (float)defectArray[i].EndPoint.Y);

                // Lignes entre les différents points (départ - profondeur, profondeur - fin)
                LineSegment2D startDepthLine = new LineSegment2D(defectArray[i].StartPoint, defectArray[i].DepthPoint);
                LineSegment2D depthEndLine   = new LineSegment2D(defectArray[i].DepthPoint, defectArray[i].EndPoint);

                // Cercles liés aux points de départ, profondeur et fin
                CircleF startCircle = new CircleF(startPoint, 5f);
                CircleF depthCircle = new CircleF(depthPoint, 5f);
                CircleF endCircle   = new CircleF(endPoint, 5f);

                // Heuristique personnalisée d'après diverses expériences pour détecter si il s'agit d'un doigt ou non, d'après la position des points de départ, de profondeur et de fin et la taille de la box qui les contient
                if ((startCircle.Center.Y < box.center.Y || depthCircle.Center.Y < box.center.Y) && (startCircle.Center.Y < depthCircle.Center.Y) && (Math.Sqrt(Math.Pow(startCircle.Center.X - depthCircle.Center.X, 2) + Math.Pow(startCircle.Center.Y - depthCircle.Center.Y, 2)) > box.size.Height / 6.5))
                {
                    fingerNum++;
                    imgProc.Draw(startDepthLine, new Bgr(Color.Green), 2);
                }

                // Dessine les différents points
                imgProc.Draw(startCircle, new Bgr(Color.Red), 2);
                imgProc.Draw(depthCircle, new Bgr(Color.Yellow), 5);
                imgProc.Draw(endCircle, new Bgr(Color.DarkBlue), 4);
            }
        }
Exemplo n.º 41
0
    public static Vector2 CalculatePenetrationVector(CircleF circle, CircleF otherCircle, Vector2 velocity,
                                                     Vector2 otherVelocity)
    {
        // Reset the circles to their old positions. Structs, so no external mutation.
        circle.Center      -= velocity;
        otherCircle.Center -= otherVelocity;
        var oldDistance = circle.Center - otherCircle.Center;

        var sumRadius = circle.Radius + otherCircle.Radius;

        if (oldDistance.Dot(oldDistance) <= sumRadius * sumRadius)
        {
            // Already overlapping
            return(circle.CalculatePenetrationVector(otherCircle));
        }

        // make other circle static, expand its radius and do a ray cast
        var relativeVelocity = velocity - otherVelocity;
        // Find quadratic formula coefficients:
        // u^2 coefficient
        var a = relativeVelocity.Dot(relativeVelocity);
        // u coefficient
        var b = 2 * relativeVelocity.Dot(oldDistance);
        // constant
        var c = oldDistance.Dot(oldDistance) - sumRadius * sumRadius;


        if (SolveQuadraticFormula(a, b, c, out var u0, out var u1) && u0.IsBetween(0, 1) && u1.IsBetween(0, 1))
        {
            var maxPenetrationAt = (u0 + u1) / 2;
            circle.Position      += velocity * maxPenetrationAt;
            otherCircle.Position += otherVelocity * maxPenetrationAt;
            return(circle.CalculatePenetrationVector(otherCircle));
        }

        return(Vector2.Zero);
    }
Exemplo n.º 42
0
        public static int CountPixels(Image <Gray, Byte> img, ref CircleF circle, double targetRatio)
        {
            //Calc.CircleX(img, circle, targetRatio);

            List <int> Radius      = new List <int>();
            List <int> SumOnRadius = new List <int>();

            int sum = PixelCount.Circle(img, circle);

            double prevRatio = 0;
            int    prevSum   = 0;

            for (int radius = CfgMinRadiusFor865 - 1; radius <= System.Math.Ceiling(circle.Radius); radius++)
            {
                int rsum = PixelCount.Circle(img, new CircleF(circle.Center, radius));

                Radius.Add(radius);
                SumOnRadius.Add(rsum);

                double ratio = (double)rsum / sum;
                if (ratio < targetRatio)
                {
                    prevRatio = ratio;
                    prevSum   = rsum;
                    continue;
                }

                #region linear calculation
                circle.Radius = (float)((radius - 1) + (targetRatio - prevRatio) / (ratio - prevRatio));
                sum           = (int)(prevSum + (targetRatio - prevRatio) / (ratio - prevRatio));
                #endregion
                break;
            }

            return(sum);
        }
Exemplo n.º 43
0
        private static bool TryFindCircleInFullFrame(IndicatorData data, out CircleF ret)
        {
            ret = default(CircleF);

            if (RollIndicator.TryFindRollCircleInFullFrame(data, out var circle))
            {
                circle.Center = new PointF(circle.Center.X + 1055, circle.Center.Y - 20);
                circle.Radius = 70;
                var firstCrop = Math2.CropCircle(circle, 40);
                var focus     = data.Frame.SafeCopy(firstCrop);
                var focusHsv  = focus.Convert <Hsv, byte>().PyrUp().PyrDown();

                var circles = CvInvoke.HoughCircles(focusHsv[2], HoughType.Gradient, 2.0, 80, 10, 80, 60, 80);
                if (circles.Length == 1)
                {
                    var circ = circles[0];
                    circles[0].Center = circles[0].Center.Add(firstCrop.Location);
                    circles[0].Radius = 64;
                    ret = circles[0];
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 44
0
 /// <summary>
 /// Show calibration mark on screen - circle and coordinates
 /// </summary>
 /// <param name="mark">Calibration mark as CircleF</param>
 /// <param name="key">Calibration mark type</param>
 public void ShowCalibrationMark(CircleF mark, eCallibrationMark key)
 {
     switch (key)
     {
         case eCallibrationMark.BL:
             Marks.DrawCallibrationCircle(eCallibrationMark.BL,
                 new Point(mark.Center.X, mark.Center.Y), Convert.ToInt32(mark.Radius));
             break;
         case eCallibrationMark.TL:
             Marks.DrawCallibrationCircle(eCallibrationMark.TL,
                 new Point(mark.Center.X, mark.Center.Y), Convert.ToInt32(mark.Radius));
             break;
         case eCallibrationMark.TR:
             Marks.DrawCallibrationCircle(eCallibrationMark.TR,
                 new Point(mark.Center.X, mark.Center.Y), Convert.ToInt32(mark.Radius));
             break;
         case eCallibrationMark.BR:
             Marks.DrawCallibrationCircle(eCallibrationMark.BR,
                 new Point(mark.Center.X, mark.Center.Y), Convert.ToInt32(mark.Radius));
             break;
     }
 }
Exemplo n.º 45
0
		private void DrawUsedGroundFeatures()
		{
			List<TrackedFeature> usedGroundFeatures = m_VisualOdometer.TranslationAnalyzer.UsedGroundFeatures;
			// draw previous location
			for (int i = 0; i < usedGroundFeatures.Count; i++)
			{
				TrackedFeature usedGroundFeature = usedGroundFeatures[i];
				CircleF circle = new CircleF(usedGroundFeature[0], 6.0f);
				m_VisualOdometer.CurrentImage.Draw(circle, m_UsedGroundFeatureColor, 4);
			}
		}
Exemplo n.º 46
0
		internal void DrawCurrentFeatureLocation(PointF currentFeatureLocation, bool hasFullHistory, Image<Bgr, Byte> image)
		{
			CircleF circle = new CircleF(currentFeatureLocation, 3.0f);
			if (!hasFullHistory)
			{
				image.Draw(circle, m_FeatureColorCurrentPartialHistory, 2);
			}
			else
			{
				image.Draw(circle, m_FeatureColorCurrentFullHistory, 2);
			}
		}
Exemplo n.º 47
0
		internal void DrawPreviousFeatureLocation(PointF previousFeatureLocation, bool hasFullHistory, Image<Bgr, Byte> image)
		{
			CircleF circle = new CircleF(previousFeatureLocation, 3.0f);
			if (!hasFullHistory)
			{
				image.Draw(circle, m_FeatureColorPreviousPartialHistory, 2);
			}
			else
			{
				image.Draw(circle, m_FeatureColorPreviousFullHistory, 2);
			}
		}
        private void btnMAP_Click(object sender, EventArgs e)
        {
            while (MAPestimationOperations.definiteL > 35)
            {

                FeatureVector newVector = MAPestimationOperations.core(observedImageVector, hypothesisImageVector);
                hypothesisImageVector = newVector;

                // imagen2 = imagen2copia;
                //imgCaja2.Image = imagen2;
                // imgCaja2.Refresh();

                label1.Text = "L = " + MAPestimationOperations.definiteL.ToString();

                label1.Refresh();

                imagen2 = new Image<Bgr, byte>(archivo);
                imgCaja2.Image = imagen2;

                PointF puntoC = hypothesisImageVector.PalmCenter; ;
                Point punt = new Point(int.Parse(puntoC.X.ToString()), int.Parse(puntoC.Y.ToString()));
                CircleF centerCircle = new CircleF(puntoC, 5f);
                imagen2.Draw(centerCircle, new Bgr(Color.Brown), 3);

                Point p1 = new Point(int.Parse((hypothesisImageVector.PalmCenter.X - 90).ToString()), int.Parse((hypothesisImageVector.PalmCenter.Y - 90).ToString()));
                Point p2 = new Point(int.Parse((hypothesisImageVector.PalmCenter.X - 90).ToString()), int.Parse((hypothesisImageVector.PalmCenter.Y + 90).ToString()));
                Point p3 = new Point(int.Parse((hypothesisImageVector.PalmCenter.X + 90).ToString()), int.Parse((hypothesisImageVector.PalmCenter.Y - 90).ToString()));
                Point p4 = new Point(int.Parse((hypothesisImageVector.PalmCenter.X + 90).ToString()), int.Parse((hypothesisImageVector.PalmCenter.Y + 90).ToString()));

                LineSegment2D line = new LineSegment2D(p1,p2);
                LineSegment2D line1 = new LineSegment2D(p1,p3);
                LineSegment2D line2 = new LineSegment2D(p3, p4);
                LineSegment2D line3 = new LineSegment2D(p2, p4);

                imagen2.Draw(line, new Bgr(Color.Brown), 3);
                imagen2.Draw(line1, new Bgr(Color.Brown), 3);
                imagen2.Draw(line2, new Bgr(Color.Brown), 3);
                imagen2.Draw(line3, new Bgr(Color.Brown), 3);

                List<PointF> fingertips = new List<PointF>();

                fingertips.Add(hypothesisImageVector.LocationThumb);
                fingertips.Add(hypothesisImageVector.LocationIndexFinger);
                fingertips.Add(hypothesisImageVector.LocationHeartFinger);
                fingertips.Add(hypothesisImageVector.Location4Finger);
                fingertips.Add(hypothesisImageVector.LocationLittleFinger);

                foreach (PointF p in fingertips)
                {

                    CircleF circle = new CircleF(p, 5f);

                    imagen2.Draw(circle, new Bgr(Color.Red), 3);

                    Point pun = new Point(int.Parse(p.X.ToString()), int.Parse(p.Y.ToString()));
                    LineSegment2D lineaDedoCentro = new LineSegment2D(pun, punt);
                    imagen2.Draw(lineaDedoCentro, new Bgr(Color.Green), 2);

                    imgCaja2.Refresh();
                }

            }

            MessageBox.Show("Done!");
        }
Exemplo n.º 49
0
 public int getDigitFromCode(CircleF circle, LineSegment2D[] pReferenceLines)
 {
     // remember that the first reference line is the horizontal one ,so we do not consider the line in this porocess
     return binarySearch((int)circle.Center.X, pReferenceLines, (pReferenceLines.Count() - 2) / 2);
 }
        //Do Vision
        protected Image AnalyzeImage(Image<Gray, byte> thresh, ToteDetectionType detectionType, bool detectBins)
        {
            angleToBin = NotFoundFloat;

            // Create A Bgr Image So We Could Draw Stuff On The Threshold Image.
            Image<Bgr, Byte> threshToDraw = thresh.Convert<Bgr, byte>();

            float resolutionOffset = ((float)thresh.Width * thresh.Height) / (640.0f * 480.0f);


            List<L_Shape> targets = FindToteVisionTargets(detectionType, thresh, resolutionOffset, thresh.Width);
            foreach (L_Shape l in targets)
            {
                threshToDraw.Draw(l.shape, new Bgr(255, 0, 0), (int)Math.Ceiling(3.0f * Math.Sqrt(resolutionOffset)));
            }

            if (detectBins)
            {
                List<Contour<Point>> bins = FindBins(thresh, resolutionOffset, thresh.Width);
                double maxArea = 0.0f;
                foreach (Contour<Point> bin in bins)
                {
                    // Oz changes start
                    MCvMoments moment = bin.GetMoments();
                    PointF centerOfMass = new PointF((float)moment.GravityCenter.x, (float)moment.GravityCenter.y);
                    CircleF circleOfMass = new CircleF(centerOfMass, 4.590f);
                    threshToDraw.Draw(circleOfMass, new Bgr(0, 0, 255), (int)Math.Ceiling(3.0f * Math.Sqrt(resolutionOffset)));

                    // Check if it's the biggest bin yet, if it is - calculate the angle to it
                    if (maxArea < bin.Area)
                    {
                        maxArea = bin.Area;
                        angleToBin = GetAngleToBin(bin, thresh.Size.Width / 2.0);
                    }

                    Seq<Point> convexHull = bin.GetConvexHull(Emgu.CV.CvEnum.ORIENTATION.CV_CLOCKWISE);
                    threshToDraw.Draw(convexHull, new Bgr(0, 0, 255), (int)Math.Ceiling(3.0f * Math.Sqrt(resolutionOffset)));
                    // Oz changes end
                    threshToDraw.Draw(bin.BoundingRectangle, new Bgr(0, 255, 0), (int)Math.Ceiling(3.0f * Math.Sqrt(resolutionOffset)));
                    PointF center = bin.GetMinAreaRect().center;
                    if (this.LastDepthMap!=null)
                        if ((this.LastDepthMap.GetDepth((Int32)center.X, (Int32)center.Y)) != 4080)
                            ((ProgrammersWindow)ProgrammersWindow.ActiveForm).updateBinDepth(this.LastDepthMap.GetDepth((Int32)center.X, (Int32)center.Y));


                }
            }


            L_Shape[] best_pair = FindBestPair(targets);
            if (best_pair[0] != null && best_pair[1] != null)
            {
                threshToDraw.Draw(best_pair[0].shape, new Bgr(0, 0, 255), (int)Math.Ceiling(3.0f * Math.Sqrt(resolutionOffset)));
                threshToDraw.Draw(best_pair[1].shape, new Bgr(0, 0, 255), (int)Math.Ceiling(3.0f * Math.Sqrt(resolutionOffset)));
            }


            // Draw A Red Cross All Over The Threshold Picture So We'D Know It'S Center
            threshToDraw.Draw(new Cross2DF(new PointF(thresh.Width / 2, thresh.Height / 2) , thresh.Width, thresh.Height), new Bgr(0, 0, 255), 1);

           

            Image ret = threshToDraw.ToBitmap();
            threshToDraw.Dispose();

            return ret;
        }
Exemplo n.º 51
0
 /// <summary>
 /// This method draws a circle at the given position.
 /// </summary>
 /// <param name="image">The input image.</param>
 /// <param name="circle">The position of the circle.</param>
 /// <param name="color">The color of the cross.</param>
 /// <param name="thickness">The thickness of the cross.</param>
 private static void DrawCircle(Image <Gray, byte> image, CircleF circle, int grayScale, int thickness)
 {
     //image.Draw(circle, new Gray(grayScale), thickness);
 }
Exemplo n.º 52
0
      /// <summary>
      /// Finds circles in a grayscale image using the Hough transform
      /// </summary>
      /// <param name="image">8-bit, single-channel, grayscale input image.</param>
      /// <param name="method">Detection method to use. Currently, the only implemented method is CV_HOUGH_GRADIENT , which is basically 21HT</param>
      /// <param name="dp">Inverse ratio of the accumulator resolution to the image resolution. For example, if dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has half as big width and height.</param>
      /// <param name="minDist">Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed.</param>
      /// <param name="param1">First method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny() edge detector (the lower one is twice smaller).</param>
      /// <param name="param2">Second method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first.</param>
      /// <param name="minRadius"> Minimum circle radius.</param>
      /// <param name="maxRadius">Maximum circle radius.</param>
      /// <returns>The circles detected</returns>
      public static CircleF[] HoughCircles(
         IInputArray image,
         CvEnum.HoughType method,
         double dp,
         double minDist,
         double param1 = 100,
         double param2 = 100,
         int minRadius = 0,
         int maxRadius = 0)
      {
         using (Mat circles = new Mat())
         {
            HoughCircles(image, circles, method, dp, minDist, param1, param2, minRadius, maxRadius);
            Size s = circles.Size;
            CircleF[] results = new CircleF[s.Width];
            GCHandle handle = GCHandle.Alloc(results, GCHandleType.Pinned);
            using (Mat tmp = new Mat(s.Height, s.Width, CV.CvEnum.DepthType.Cv32F, 3, handle.AddrOfPinnedObject(), sizeof(float) * 3))
            {
               circles.CopyTo(tmp);
            }
            handle.Free();

            return results;
         }
      }
Exemplo n.º 53
0
		public abstract void DrawCircle(CircleF circle, int sides, Color color, float thickness = 1);
Exemplo n.º 54
0
        public void TestXmlSerialization()
        {
            MCvPoint2D64f pt2d = new MCvPoint2D64f(12.0, 5.5);

             XmlDocument 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 = new Image<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;
             Assert.AreEqual(a1.Length, a2.Length);
             for (int i = 0; i < a1.Length; i++)
             {
            Assert.AreEqual(a1[i], a2[i]);
             }

             img1.Dispose();
             img2.Dispose();
        }
Exemplo n.º 55
0
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


        //:::::::Display the stuff:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        private void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            //---------------------------------------------------------------
            List<Object> returnHandDetectorFrontActual = new List<object>(2);
            List<Object> returnHandDetectorSideActual = new List<object>(2);
            System.Drawing.Rectangle[] RoiKinectFrontActual;
            System.Drawing.Rectangle[] RoiKinectSideActual;
            Image<Gray, Byte> imagenKinectGray1;
            Image<Gray, Byte> imagenKinectGray2;
            Image<Gray, Byte> imageRoi1 = new Image<Gray,Byte>(200, 200);
            Image<Gray, Byte> imageRoi2 = new Image<Gray, Byte>(200, 200);
            
            List<Object> returnGettingSegK1 = new List<object>(); 
            List<Object> returnGettingSegK2 = new List<object>(); 
            
            bool noPositiveFalses;
            bool flag_execute = false;
            bool FrameHandDetected = false; 

            //to get teh position of the hand 
            PointF centerHand; 
            PointF positionRoi1;  
            PointF positionCenterHand = new PointF();         
            //-------------------------------------------------------------------------------

            //-------------------------------------------------------------------------------
            //Get actual frame and the next frame. To delate the frames with positive falses.  
            imagenKinectGray1 = GettingKinectData.PollDepth(0);
            imagenKinectGray2 = GettingKinectData.PollDepth(1);

            returnHandDetectorFrontActual = HandDetection.Detection(imagenKinectGray1);
            returnHandDetectorSideActual = HandDetection.Detection(imagenKinectGray2);


            //Cast the return of each frame
            RoiKinectFrontActual = (System.Drawing.Rectangle[])returnHandDetectorFrontActual[0];
            RoiKinectSideActual = (System.Drawing.Rectangle[])returnHandDetectorSideActual[0];


            if ( (numFrames == 1) || (FrameHandDetected == false) ) 
            {   
                RectArrayPrev = RoiKinectFrontActual; 
            }


            if (RoiKinectFrontActual.Length != 0)
            {
                //check if the roi in the previous frame intesect with the roi in the actual frame 
                noPositiveFalses = RectArrayPrev[0].IntersectsWith(RoiKinectFrontActual[0]);

                if (noPositiveFalses)
                {
                    RectArrayPrev = RoiKinectFrontActual;
                    flag_execute = true;
                    numFrameHandDetected++; 
                }

                if (flag_execute)
                {
                    if ((RoiKinectFrontActual.Length == 1) || (RoiKinectSideActual.Length == 1))
                    {
                        //Comentado hasta que quede el despliege de los datos 
                        returnGettingSegK1 = GettingSegmentationK1.HandConvexHull(imagenKinectGray1, RoiKinectFrontActual[0]); 
                        //if (RoiKinectSideActual.Length != 0)
                        //    returnGettingSegK2 = GettingSegmentationK2.HandConvexHull(imagenKinectGray2, RoiKinectSideActual[0]);
                        
                        if (returnGettingSegK1 != null) 
                        {
                            centerHand = (PointF)returnGettingSegK1[0]; 

                            positionRoi1 = RoiKinectFrontActual[0].Location; 
                            positionCenterHand.X = positionRoi1.X + centerHand.X; 
                            positionCenterHand.Y = positionRoi1.Y + centerHand.Y; 

                            CircleF centrillo = new CircleF(positionCenterHand, 5f);

                            imagenKinectGray1.Draw(centrillo, new Gray(150), 3);

                            //SaveFeaturesText.SaveFeaturesTraining("2", returnGettingSegK1, pathFront+"TrainingFront2.txt"); 
                            SaveFeaturesText.SaveFeaturesTest(numFrames, returnGettingSegK1, pathFront + "Test1.txt"); 

                            //This thing is for count the frames where one hand is detected in every kinect.

                            imagenKinectGray1.Save(pathFront + "Front_" + numFrames.ToString() + "_"+ sec.ToString() + "_" + fps.ToString() + ".png");
                            imagenKinectGray2.Save(pathSide + "Side_" + numFrames.ToString() + "_"+ sec.ToString() + "_" + fps.ToString() + ".png");

                            DepthImageK1.Source = imagetoWriteablebitmap(imagenKinectGray1);
                            DepthImageK2.Source = imagetoWriteablebitmap(imagenKinectGray2); 
                        } 
                    }
                }  
            } 


            if (fps == 30)
            {
                fps = 1;
                sec++;
             }
            fps++;
            numFrames++; 

        } //end CompositionTarget 
Exemplo n.º 56
0
        public void ProcesseFrameToFindCircles(Image<Bgr, Byte> pImage, int iterator)
        {
            #region test_200ppp

            //if (pImg != null)
            //{
            //    //Images where to draw of what is processed
            //    imgProcessedHoughCircle = pImg.Copy();
            //    imgProcessedHoughCircle2 = pImg.Copy();

            //    ////

            //    Image<Bgr, byte> blur = pImg.SmoothBlur(10, 10, true);
            //    //ibOriginal.Image = blur;
            //    Image<Bgr, byte> mediansmooth = pImg.SmoothMedian(3);
            //    //imageBox1.Image = mediansmooth;
            //    Image<Bgr, byte> bilat = pImg.SmoothBilatral(7, 255, 34);
            //    //imageBox2.Image = bilat;
            //    Image<Bgr, byte> gauss = pImg.SmoothGaussian(3, 3, 34.3, 45.3);
            //    //ibHoughCircles2.Image = gauss;

            //    ///

            //    //ranges
            //    imgProcessed = pImg.InRange(new Bgr(B_MIN, G_MIN, R_MIN),
            //                                      new Bgr(B_MAX, G_MAX, R_MAX));
            //    ibOriginal.Image = imgProcessed;

            //    //SmoothGuassian process
            //    imgProcessed = imgProcessed.SmoothGaussian(11);
            //    ibCanny.Image = imgProcessed;

            //    /*
            //    //THRESHOLD_BINARY
            //    imgProcessed = imgProcessed.ThresholdBinary(new Gray(THRESHOLD_BINARY_MIN), new Gray(THRESHOLD_BINARY_MAX)); //ThresholdBinary

            //    ibCanny.Image = imgProcessed;

            //    //Image<Gray,float> imgSobel = imgProcessed.Sobel(1, 0,3);

            //    //ibHoughCircles2.Image = imgSobel;
            //    imgProcessed = imgProcessed.SmoothGaussian(9);
            //    ibHoughCircles.Image = imgProcessed;

            //    */
            //    // canny process
            //    imgProcessedCanny = imgProcessed.Canny(new Gray(THRESH), new Gray(THRESH_LINKING));
            //    ibHoughCircles.Image = imgProcessedCanny;

            //    // finding all circles from image
            //    CircleF[] circles = imgProcessedCanny.HoughCircles(new Gray(CANNY_THRESHOLD),
            //                                                       new Gray(ACUMMULATOR_THRESHOLD),
            //                                                       2,
            //        //imgProcessed.Height / 4,
            //                                                       MIN_DIST,
            //        // de 1 a 4 varia en la cantidad de pixeles a procesar, calidad de la imagen
            //                                                       MIN_RADIO,
            //                                                       MAX_RADIO)[0];

            //    //circles = null;

            //    if (circles != null)
            //    {
            //        txtTotalCircles.Text = circles.Length.ToString();

            //        for (int i = 0; i < circles.Length; i++)
            //        {
            //            CvInvoke.cvCircle(imgProcessedHoughCircle,
            //                              new Point((int)circles[i].Center.X, (int)circles[i].Center.Y),
            //                              2,
            //                              new MCvScalar(0, 255, 0),
            //                              -1,
            //                              LINE_TYPE.CV_AA,
            //                              0);
            //        }

            //        for (int i = 0; i < circles.Length; i++)
            //        {

            //            imgProcessedHoughCircle.Draw(circles[i],
            //                           new Bgr(Color.Red),
            //                           2);
            //            // mostrmo lo Id desordemandos del arreglo de circles
            //            MCvFont f = new MCvFont(FONT.CV_FONT_HERSHEY_COMPLEX, 0.9, 0.9);
            //            imgProcessedHoughCircle.Draw(i.ToString(), ref f, new Point((int)circles[i].Center.X + 10, (int)circles[i].Center.Y + 6), new Bgr(255, 0, 0));
            //        }

            //        ProcesseFrameToFindAnswers(imgProcessedHoughCircle2, circles.ToList());

            //        //ibHoughCircles.Image = imgProcessedHoughCircle;
            //        //ibHoughCircles2.Image = imgProcessedHoughCircle2;
            //        ibHoughCircles2.Image = imgProcessedHoughCircle;
            //        imageBox1.Image = imgProcessedHoughCircle2;

            //    }

            //    //ibOriginal.Image = pImg;
            //    //ibCanny.Image = imgProcessedCanny;

            //}

            #endregion

            switch (iterator)
            {
                #region test_200ppp Better_FOTOS 3 NO inverse  => first iteration     0

                case 0:
                    #region Official

                    if (pImage != null)
                    {

                        Image<Bgr, Byte> pImg = pImage.Copy();
                        //Image<Bgr, Byte> pImgN = pImage.Copy();
                        ////ibCanny.Image = pImgN;

                        ////History equalization and gamma corretion
                        //Image<Bgr, Byte> pImgEH = pImage.Copy();
                        //pImgEH._EqualizeHist();
                        //ibHoughCircles.Image = pImgEH;
                        //Image<Bgr, Byte> pImgG = pImgEH.Copy();
                        //pImgG._GammaCorrect(2.9d);
                        //ibHoughCircles2.Image = pImgG;

                        //ranges
                        imgProcessed = pImg.InRange(new Bgr(B_MIN, G_MIN, R_MIN),
                                                          new Bgr(B_MAX, G_MAX, R_MAX));
                        //Image <Gray, Byte> gi = pImgG.Convert<Gray, Byte>();
                        //imgProcessed = gi.ThresholdBinary(new Gray(240),new Gray(255));
                        //ibCanny.Image = imgProcessed;

                        //Test using expensive filters...not good results
                        //Image<Gray, float> imgSobel = imgProcessed.Sobel(1, 0, 23);
                        //ibHoughCircles.Image = imgSobel;
                        //imgProcessed = imgProcessed.SmoothGaussian(3);
                        //ibHoughCircles2.Image = imgProcessed;

                        //THRESHOLD_BINARY
                        //imgProcessed = imgProcessed.ThresholdBinary(new Gray(THRESHOLD_BINARY_MIN), new Gray(THRESHOLD_BINARY_MAX)); //ThresholdBinary
                        //imgProcessed = imgProcessed.ThresholdBinaryInv(new Gray(THRESHOLD_BINARY_MIN), new Gray(THRESHOLD_BINARY_MAX)); //ThresholdBinary
                        #region MemStorage

                        contoursPositions.Clear();

                        #region Circles

                        using (MemStorage stor = new MemStorage())
                        {
                            //Find contours with no holes try CV_RETR_EXTERNAL to find holes
                            contours = imgProcessed.FindContours(
                             Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
                             Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_EXTERNAL,
                             stor);

                            //contours = imgProcessed.FindContours(
                            //  Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
                            //  Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_CCOMP,
                            //  stor);
                            //markers.Clear();
                            for (int i = 0; contours != null; contours = contours.HNext)
                            {
                                i++;
                                //if ((contours.Area > Math.Pow(17, 2)) && (contours.Area < Math.Pow(45, 2)))
                                if ((contours.Area > Math.Pow(7, 2)) && (contours.Area < Math.Pow(45, 2)))
                                {

                                    MCvBox2D box = contours.GetMinAreaRect();
                                    CountorsPositions cp = new CountorsPositions(box.center.X, box.center.Y,(float)contours.Area);

                                    contoursPositions.Add(cp);

                                    //pImg.Draw(box, new Bgr(System.Drawing.Color.Red), 3);
                                    //blobCount++;

                                    CvInvoke.cvCircle(pImg,
                                                      new System.Drawing.Point((int)box.center.X, (int)box.center.Y),
                                                      2,
                                                      new MCvScalar(0, 255, 0),
                                                      -1,
                                                      LINE_TYPE.CV_AA,
                                                      0);

                                    PointF p = new PointF((int)box.center.X, (int)box.center.Y);

                                    CircleF c = new CircleF(p, (float)Math.Sqrt(contours.Area));
                                    pImg.Draw(c,
                                                 new Bgr(System.Drawing.Color.Orange),
                                                 3);
                                    //markers.Add(new Point((int)box.center.X, (int)box.center.Y));

                                }
                            }
                        }
                        #endregion
            //cleanList();
                        FillingAnswersToAbstractObject();

                        FillingAnswerstToFinalQuestionsList();

                        //if (markers.Count == 4)
                        //{
                        //    DrawLines(markers);
                        //}
                        ////this.outImg.Source = ImageHelpers.ToBitmapSource(openCVImg);
                        ////txtBlobCount.Text = blobCount.ToString();

                        #endregion

                        //ibHoughCircles.Image = imgProcessed;

                        //Image<Gray,float> imgSobel = imgProcessed.Sobel(1, 0,3);
                        //ibHoughCircles2.Image = imgSobel;
                        //imgProcessed = imgProcessed.SmoothGaussian(3);
                        //ibHoughCircles.Image = imgProcessed;

                        // canny process
                        //imgProcessedCanny = imgProcessed.Canny(new Gray(THRESH), new Gray(THRESH_LINKING));
                        //ibHoughCircles2.Image = imgProcessed;

                        // finding all circles from image
                        CircleF[] circles;/* = imgProcessedCanny.HoughCircles(new Gray(CANNY_THRESHOLD),
                                                                           new Gray(ACUMMULATOR_THRESHOLD),
                                                                           2,
                            //imgProcessed.Height / 4,
                                                                           MIN_DIST,
                            // de 1 a 4 varia en la cantidad de pixeles a procesar, calidad de la imagen
                                                                           MIN_RADIO,
                                                                           MAX_RADIO)[0];
                        */
                        circles = null;

                        if (circles != null)
                        {
                            txtTotalCircles.Text = circles.Length.ToString();

                            for (int i = 0; i < circles.Length; i++)
                            {
                                CvInvoke.cvCircle(imgProcessedHoughCircle,
                                                  new Point((int)circles[i].Center.X, (int)circles[i].Center.Y),
                                                  2,
                                                  new MCvScalar(0, 255, 0),
                                                  -1,
                                                  LINE_TYPE.CV_AA,
                                                  0);
                            }

                            for (int i = 0; i < circles.Length; i++)
                            {

                                imgProcessedHoughCircle.Draw(circles[i],
                                               new Bgr(Color.Red),
                                               2);
                                // mostrmo lo Id desordemandos del arreglo de circles
                                MCvFont f = new MCvFont(FONT.CV_FONT_HERSHEY_COMPLEX, 0.9, 0.9);
                                imgProcessedHoughCircle.Draw(i.ToString(), ref f, new Point((int)circles[i].Center.X + 10, (int)circles[i].Center.Y + 6), new Bgr(255, 0, 0));
                            }

                            // call method to make second iteration
                            //ProcesseFrameToFindAnswers(imgProcessedHoughCircle2, circles.ToList(),0);

                            //ibHoughCircles.Image = imgProcessedHoughCircle;
                            //ibHoughCircles2.Image = imgProcessedHoughCircle2;
                            //ibHoughCircles2.Image = imgProcessedHoughCircle;
                            imageBox1.Image = imgProcessedHoughCircle2;

                        }

                       //ibOriginal.Image = pImg;
                        //ibCanny.Image = imgProcessedCanny;

                    }

                    break;
                    #endregion

                #region test_200ppp_Edit

                //if (pImg != null)
                //{
                //    //Images where to draw of what is processed
                //    imgProcessedHoughCircle = pImg.Copy();
                //    imgProcessedHoughCircle2 = pImg.Copy();

                //    ////

                //    //Image<Bgr, byte> blur = pImg.SmoothBlur(10, 10, true);
                //    //ibOriginal.Image = blur;
                //    //Image<Bgr, byte> mediansmooth = pImg.SmoothMedian(3);
                //    //imageBox1.Image = mediansmooth;
                //    //Image<Bgr, byte> bilat = pImg.SmoothBilatral(7, 255, 34);
                //    //imageBox2.Image = bilat;
                //    //Image<Bgr, byte> gauss = pImg.SmoothGaussian(3, 3, 34.3, 45.3);
                //    //ibHoughCircles2.Image = gauss;

                //    ///

                //    //ranges
                //    imgProcessed = pImg.InRange(new Bgr(B_MIN, G_MIN, R_MIN),
                //                                      new Bgr(B_MAX, G_MAX, R_MAX));
                //    ibOriginal.Image = imgProcessed;

                //    //SmoothGuassian process
                //    imgProcessed = imgProcessed.SmoothGaussian(31);
                //    ibCanny.Image = imgProcessed;

                //    //THRESHOLD_BINARY
                //    imgProcessed = imgProcessed.ThresholdBinary(new Gray(THRESHOLD_BINARY_MIN), new Gray(THRESHOLD_BINARY_MAX)); //ThresholdBinary

                //    ibHoughCircles.Image = imgProcessed;

                //    //Image<Gray,float> imgSobel = imgProcessed.Sobel(1, 0,3);

                //    //ibHoughCircles2.Image = imgSobel;
                //    //imgProcessed = imgProcessed.SmoothGaussian(9);

                //    // canny process
                //    imgProcessedCanny = imgProcessed.Canny(new Gray(THRESH), new Gray(THRESH_LINKING));
                //    //ibHoughCircles.Image = imgProcessedCanny;

                //    // finding all circles from image
                //    CircleF[] circles = imgProcessedCanny.HoughCircles(new Gray(CANNY_THRESHOLD),
                //                                                       new Gray(ACUMMULATOR_THRESHOLD),
                //                                                       2,
                //        //imgProcessed.Height / 4,
                //                                                       MIN_DIST,
                //        // de 1 a 4 varia en la cantidad de pixeles a procesar, calidad de la imagen
                //                                                       MIN_RADIO,
                //                                                       MAX_RADIO)[0];

                //    //circles = null;

                //    if (circles != null)
                //    {
                //        txtTotalCircles.Text = circles.Length.ToString();

                //        for (int i = 0; i < circles.Length; i++)
                //        {
                //            CvInvoke.cvCircle(imgProcessedHoughCircle,
                //                              new Point((int)circles[i].Center.X, (int)circles[i].Center.Y),
                //                              2,
                //                              new MCvScalar(0, 255, 0),
                //                              -1,
                //                              LINE_TYPE.CV_AA,
                //                              0);
                //        }

                //        for (int i = 0; i < circles.Length; i++)
                //        {

                //            imgProcessedHoughCircle.Draw(circles[i],
                //                           new Bgr(Color.Red),
                //                           2);
                //            // mostrmo lo Id desordemandos del arreglo de circles
                //            MCvFont f = new MCvFont(FONT.CV_FONT_HERSHEY_COMPLEX, 0.9, 0.9);
                //            imgProcessedHoughCircle.Draw(i.ToString(), ref f, new Point((int)circles[i].Center.X + 10, (int)circles[i].Center.Y + 6), new Bgr(255, 0, 0));
                //        }

                //        ProcesseFrameToFindAnswers(imgProcessedHoughCircle2, circles.ToList(),0);

                //        //ibHoughCircles.Image = imgProcessedHoughCircle;
                //        //ibHoughCircles2.Image = imgProcessedHoughCircle2;
                //        ibHoughCircles2.Image = imgProcessedHoughCircle;
                //        imageBox1.Image = imgProcessedHoughCircle2;

                //    }

                //    //ibOriginal.Image = pImg;
                //    //ibCanny.Image = imgProcessedCanny;

                //}
                //break;

                #endregion

                #endregion

                //#region second iteration   1
                //case 1:
                //    if (pImg != null)
                //    {
                //        InicializeColorConfigurationpPen_200ppp_No_Inverse_Second_Iteration();

                //        //Images where to draw of what is processed
                //        imgProcessedHoughCircle = pImg.Copy();
                //        imgProcessedHoughCircle2 = pImg.Copy();

                //        ////

                //        //Image<Bgr, byte> blur = pImg.SmoothBlur(10, 10, true);
                //        //ibOriginal.Image = blur;
                //        //Image<Bgr, byte> mediansmooth = pImg.SmoothMedian(13);
                //        //imageBox1.Image = mediansmooth;

                //        //imageBox1.Image = mediansmooth;
                //        //Image<Bgr, byte> bilat = pImg.SmoothBilatral(5, 255, 34);
                //        //imageBox2.Image = bilat;
                //        //Image<Bgr, byte> gauss = pImg.SmoothGaussian(7, 7, 34.3, 45.3);
                //        //imageBox1.Image = gauss;

                //        ///

                //        //ranges
                //        imgProcessed = pImg.InRange(new Bgr(B_MIN, G_MIN, R_MIN),
                //                                          new Bgr(B_MAX, G_MAX, R_MAX));

                //        //ibOriginal.Image = imgProcessed;

                //        //SmoothGuassian process
                //        imgProcessed = imgProcessed.SmoothGaussian(31);
                //        ibCanny.Image = imgProcessed;

                //        //THRESHOLD_BINARY
                //        imgProcessed = imgProcessed.ThresholdBinary(new Gray(THRESHOLD_BINARY_MIN), new Gray(THRESHOLD_BINARY_MAX)); //ThresholdBinary

                //        ibHoughCircles.Image = imgProcessed;

                //        //Image<Gray,float> imgSobel = imgProcessed.Sobel(1, 0,3);

                //        //ibHoughCircles2.Image = imgSobel;
                //        imgProcessed = imgProcessed.SmoothGaussian(9);
                //        //ibHoughCircles.Image = imgProcessed;

                //        // canny process
                //        //imgProcessedCanny = imgProcessed.Canny(new Gray(THRESH), new Gray(THRESH_LINKING));
                //        ibHoughCircles2.Image = imgProcessed;

                //        // finding all circles from image
                //        CircleF[] circles = imgProcessedCanny.HoughCircles(new Gray(CANNY_THRESHOLD),
                //                                                           new Gray(ACUMMULATOR_THRESHOLD),
                //                                                           2,
                //            //imgProcessed.Height / 4,
                //                                                           MIN_DIST,
                //            // de 1 a 4 varia en la cantidad de pixeles a procesar, calidad de la imagen
                //                                                           MIN_RADIO,
                //                                                           MAX_RADIO)[0];

                //        //circles = null;

                //        if (circles != null)
                //        {
                //            txtTotalCircles.Text = circles.Length.ToString();

                //            for (int i = 0; i < circles.Length; i++)
                //            {
                //                CvInvoke.cvCircle(imgProcessedHoughCircle,
                //                                  new Point((int)circles[i].Center.X, (int)circles[i].Center.Y),
                //                                  2,
                //                                  new MCvScalar(0, 255, 0),
                //                                  -1,
                //                                  LINE_TYPE.CV_AA,
                //                                  0);
                //            }

                //            for (int i = 0; i < circles.Length; i++)
                //            {

                //                imgProcessedHoughCircle.Draw(circles[i],
                //                               new Bgr(Color.Red),
                //                               2);
                //                // mostrmo lo Id desordemandos del arreglo de circles
                //                MCvFont f = new MCvFont(FONT.CV_FONT_HERSHEY_COMPLEX, 0.9, 0.9);
                //                imgProcessedHoughCircle.Draw(i.ToString(), ref f, new Point((int)circles[i].Center.X + 10, (int)circles[i].Center.Y + 6), new Bgr(255, 0, 0));
                //            }

                //            // call method to make second iteration
                //            ProcesseFrameToFindAnswers(imgProcessedHoughCircle2, circles.ToList(), 1);

                //            //ibHoughCircles.Image = imgProcessedHoughCircle;
                //            //ibHoughCircles2.Image = imgProcessedHoughCircle2;
                //            //ibHoughCircles2.Image = imgProcessedHoughCircle;
                //            imageBox1.Image = imgProcessedHoughCircle2;

                //        }

                //        //ibOriginal.Image = pImg;
                //        //ibCanny.Image = imgProcessedCanny;

                //    }

                //    break;

                //#endregion

                //#region  third iteration    2
                //case 2:
                //    if (pImg != null)
                //    {
                //        InicializeColorConfigurationpPen_200ppp_No_Inverse_Third_Iteration();

                //        //Images where to draw of what is processed
                //        imgProcessedHoughCircle = pImg.Copy();
                //        imgProcessedHoughCircle2 = pImg.Copy();

                //        ////

                //        //Image<Bgr, byte> blur = pImg.SmoothBlur(10, 10, true);
                //        //ibOriginal.Image = blur;
                //        //Image<Bgr, byte> mediansmooth = pImg.SmoothMedian(13);
                //        //imageBox1.Image = mediansmooth;

                //        //imageBox1.Image = mediansmooth;
                //        //Image<Bgr, byte> bilat = pImg.SmoothBilatral(5, 255, 34);
                //        //imageBox2.Image = bilat;
                //        //Image<Bgr, byte> gauss = pImg.SmoothGaussian(7, 7, 34.3, 45.3);
                //        //imageBox1.Image = gauss;

                //        ///

                //        //ranges
                //        imgProcessed = pImg.InRange(new Bgr(B_MIN, G_MIN, R_MIN),
                //                                          new Bgr(B_MAX, G_MAX, R_MAX));

                //        ibOriginal.Image = imgProcessed;

                //        //SmoothGuassian process
                //        imgProcessed = imgProcessed.SmoothGaussian(23);
                //        ibCanny.Image = imgProcessed;

                //        //THRESHOLD_BINARY
                //        imgProcessed = imgProcessed.ThresholdBinary(new Gray(THRESHOLD_BINARY_MIN), new Gray(THRESHOLD_BINARY_MAX)); //ThresholdBinary

                //        ibHoughCircles.Image = imgProcessed;

                //        //Image<Gray,float> imgSobel = imgProcessed.Sobel(1, 0,3);

                //        //ibHoughCircles2.Image = imgSobel;
                //        //imgProcessed = imgProcessed.SmoothGaussian(9);
                //        //ibHoughCircles.Image = imgProcessed;

                //        // canny process
                //        imgProcessedCanny = imgProcessed.Canny(new Gray(THRESH), new Gray(THRESH_LINKING));
                //        ibHoughCircles2.Image = imgProcessedCanny;

                //        // finding all circles from image
                //        CircleF[] circles = imgProcessedCanny.HoughCircles(new Gray(CANNY_THRESHOLD),
                //                                                           new Gray(ACUMMULATOR_THRESHOLD),
                //                                                           2,
                //            //imgProcessed.Height / 4,
                //                                                           MIN_DIST,
                //            // de 1 a 4 varia en la cantidad de pixeles a procesar, calidad de la imagen
                //                                                           MIN_RADIO,
                //                                                           MAX_RADIO)[0];

                //        //circles = null;

                //        if (circles != null)
                //        {
                //            txtTotalCircles.Text = circles.Length.ToString();

                //            for (int i = 0; i < circles.Length; i++)
                //            {
                //                CvInvoke.cvCircle(imgProcessedHoughCircle,
                //                                  new Point((int)circles[i].Center.X, (int)circles[i].Center.Y),
                //                                  2,
                //                                  new MCvScalar(0, 255, 0),
                //                                  -1,
                //                                  LINE_TYPE.CV_AA,
                //                                  0);
                //            }

                //            for (int i = 0; i < circles.Length; i++)
                //            {

                //                imgProcessedHoughCircle.Draw(circles[i],
                //                               new Bgr(Color.Red),
                //                               2);
                //                // mostrmo lo Id desordemandos del arreglo de circles
                //                MCvFont f = new MCvFont(FONT.CV_FONT_HERSHEY_COMPLEX, 0.9, 0.9);
                //                imgProcessedHoughCircle.Draw(i.ToString(), ref f, new Point((int)circles[i].Center.X + 10, (int)circles[i].Center.Y + 6), new Bgr(255, 0, 0));
                //            }

                //            // call method to make second iteration
                //            ProcesseFrameToFindAnswers(imgProcessedHoughCircle2, circles.ToList(), 2);

                //            //ibHoughCircles.Image = imgProcessedHoughCircle;
                //            //ibHoughCircles2.Image = imgProcessedHoughCircle2;
                //            //ibHoughCircles2.Image = imgProcessedHoughCircle;
                //            imageBox1.Image = imgProcessedHoughCircle2;

                //        }

                //        //ibOriginal.Image = pImg;
                //        //ibCanny.Image = imgProcessedCanny;

                //    }

                //    break;

                //#endregion

            }

            #region test_200ppp Better_ VALORES EN FOTOS 1 y 2

            //if (pImg != null)
            //{
            //    //Images where to draw of what is processed
            //    imgProcessedHoughCircle = pImg.Copy();
            //    imgProcessedHoughCircle2 = pImg.Copy();

            //    ////

            //    Image<Bgr, byte> blur = pImg.SmoothBlur(10, 10, true);
            //    ibOriginal.Image = blur;
            //    //Image<Bgr, byte> mediansmooth = pImg.SmoothMedian(13);
            //    //imageBox1.Image = mediansmooth;

            //    //imageBox1.Image = mediansmooth;
            //    //Image<Bgr, byte> bilat = pImg.SmoothBilatral(5, 255, 34);
            //    //imageBox2.Image = bilat;
            //    //Image<Bgr, byte> gauss = pImg.SmoothGaussian(7, 7, 34.3, 45.3);
            //    //imageBox1.Image = gauss;

            //    ///

            //    //ranges
            //    imgProcessed = blur.InRange(new Bgr(B_MIN, G_MIN, R_MIN),
            //                                      new Bgr(B_MAX, G_MAX, R_MAX));

            //    ibCanny.Image = imgProcessed;

            //    //SmoothGuassian process
            //    imgProcessed = imgProcessed.SmoothGaussian(23);
            //    //ibCanny.Image = imgProcessed;

            //    //THRESHOLD_BINARY
            //    imgProcessed = imgProcessed.ThresholdBinaryInv(new Gray(THRESHOLD_BINARY_MIN), new Gray(THRESHOLD_BINARY_MAX)); //ThresholdBinary

            //    ibHoughCircles.Image = imgProcessed;

            //    //Image<Gray,float> imgSobel = imgProcessed.Sobel(1, 0,3);

            //    //ibHoughCircles2.Image = imgSobel;
            //    //imgProcessed = imgProcessed.SmoothGaussian(9);
            //    //ibHoughCircles.Image = imgProcessed;

            //    // canny process
            //    imgProcessedCanny = imgProcessed.Canny(new Gray(THRESH), new Gray(THRESH_LINKING));
            //    ibHoughCircles2.Image = imgProcessedCanny;

            //    // finding all circles from image
            //    CircleF[] circles = imgProcessedCanny.HoughCircles(new Gray(CANNY_THRESHOLD),
            //                                                       new Gray(ACUMMULATOR_THRESHOLD),
            //                                                       2,
            //        //imgProcessed.Height / 4,
            //                                                       MIN_DIST,
            //        // de 1 a 4 varia en la cantidad de pixeles a procesar, calidad de la imagen
            //                                                       MIN_RADIO,
            //                                                       MAX_RADIO)[0];

            //    //circles = null;

            //    if (circles != null)
            //    {
            //        txtTotalCircles.Text = circles.Length.ToString();

            //        for (int i = 0; i < circles.Length; i++)
            //        {
            //            CvInvoke.cvCircle(imgProcessedHoughCircle,
            //                              new Point((int)circles[i].Center.X, (int)circles[i].Center.Y),
            //                              2,
            //                              new MCvScalar(0, 255, 0),
            //                              -1,
            //                              LINE_TYPE.CV_AA,
            //                              0);
            //        }

            //        for (int i = 0; i < circles.Length; i++)
            //        {

            //            imgProcessedHoughCircle.Draw(circles[i],
            //                           new Bgr(Color.Red),
            //                           2);
            //            // mostrmo lo Id desordemandos del arreglo de circles
            //            MCvFont f = new MCvFont(FONT.CV_FONT_HERSHEY_COMPLEX, 0.9, 0.9);
            //            imgProcessedHoughCircle.Draw(i.ToString(), ref f, new Point((int)circles[i].Center.X + 10, (int)circles[i].Center.Y + 6), new Bgr(255, 0, 0));
            //        }

            //        //ProcesseFrameToFindAnswers(imgProcessedHoughCircle2, circles.ToList());

            //        //ibHoughCircles.Image = imgProcessedHoughCircle;
            //        //ibHoughCircles2.Image = imgProcessedHoughCircle2;
            //        imageBox1.Image = imgProcessedHoughCircle;
            //        imageBox2.Image = imgProcessedHoughCircle2;

            //    }

            //    //ibOriginal.Image = pImg;
            //    //ibCanny.Image = imgProcessedCanny;

            //}

            #endregion

            #region test_100ppp so so

            //if (pImg != null)
            //{
            //    //Images where to draw of what is processed
            //    imgProcessedHoughCircle = pImg.Copy();
            //    imgProcessedHoughCircle2 = pImg.Copy();

            //    //ranges
            //    imgProcessed = pImg.InRange(new Bgr(B_MIN, G_MIN, R_MIN),
            //                                            new Bgr(B_MAX, G_MAX, R_MAX));
            //    //SmoothGuassian process
            //    imgProcessed = imgProcessed.SmoothGaussian(9);

            //    // canny process
            //    imgProcessedCanny = imgProcessed.Canny(new Gray(THRESH), new Gray(THRESH_LINKING));

            //    // finding all circles from image
            //    CircleF[] circles = imgProcessedCanny.HoughCircles(new Gray(CANNY_THRESHOLD),
            //                                                       new Gray(ACUMMULATOR_THRESHOLD),
            //                                                       2,
            //        //imgProcessed.Height / 4,
            //                                                       MIN_DIST,
            //        // de 1 a 4 varia en la cantidad de pixeles a procesar, calidad de la imagen
            //        /* =>      */                                  MIN_RADIO,
            //                                                       MAX_RADIO)[0];

            //    //COMENTAR PARA HACER PRUEBAS DE CALIBRACION
            //    //circles = null;

            //    if (circles != null)
            //    {
            //        txtTotalCircles.Text = circles.Length.ToString();

            //        for (int i = 0; i < circles.Length; i++)
            //        {
            //            CvInvoke.cvCircle(imgProcessedHoughCircle,
            //                              new Point((int)circles[i].Center.X, (int)circles[i].Center.Y),
            //                              2,
            //                              new MCvScalar(0, 255, 0),
            //                              -1,
            //                              LINE_TYPE.CV_AA,
            //                              0);
            //        }

            //        for (int i = 0; i < circles.Length; i++)
            //        {

            //            imgProcessedHoughCircle.Draw(circles[i],
            //                           new Bgr(Color.Red),
            //                           2);
            //            // mostrmo lo Id desordemandos del arreglo de circles
            //            MCvFont f = new MCvFont(FONT.CV_FONT_HERSHEY_COMPLEX, 0.9, 0.9);
            //            imgProcessedHoughCircle.Draw(i.ToString(), ref f, new Point((int)circles[i].Center.X + 10, (int)circles[i].Center.Y + 6), new Bgr(255, 0, 0));
            //        }

            //        ProcesseFrameToFindAnswers(imgProcessedHoughCircle2, circles.ToList());

            //        ibHoughCircles.Image = imgProcessedHoughCircle;
            //        ibHoughCircles2.Image = imgProcessedHoughCircle2;
            //    }

            //    ibOriginal.Image = pImg;
            //    ibCanny.Image = imgProcessedCanny;

            //}

            #endregion
        }
Exemplo n.º 57
0
 private static void DrawCircle(Image <Bgr, byte> image, CircleF circle, Color color, int thickness)
 {
     //image.Draw(circle, new Bgr(color), thickness);
 }
Exemplo n.º 58
0
        private List<List<CircleF>> comparePositions(List<List<CircleF>> lsMarkedAnswersPlusCode, List<List<CircleF>> lsLeftAnswers, LineSegment2D[] rflines)
        {
            for (int i = 0; i < lsMarkedAnswersPlusCode.Count - 1; i++)
            {
                for (int j = 0; j < lsMarkedAnswersPlusCode[i].Count - 1; j++)
                {
                    if (lsMarkedAnswersPlusCode[i][j].Center.X == rflines[i].P1.X)
                    {
                        PointF p;
                        CircleF c;

                        if (lsLeftAnswers[i][j].Center.X > rflines[i].P1.X)
                        {
                            p = new PointF(rflines[i].P1.X - 60, lsLeftAnswers[i][j].Center.Y);
                        }
                        else
                        {
                            p = new PointF(rflines[i].P1.X + 60, lsLeftAnswers[i][j].Center.Y);

                        }
                        c = new CircleF(p, 20);

                        lsMarkedAnswersPlusCode[i][j] = c;
                    }
                }
            }
            return lsMarkedAnswersPlusCode;
        }
Exemplo n.º 59
0
        /// <summary>
        /// Find the chessboard corners
        /// </summary>
        /// <param name="InputImage">Input image commpping from video camera.</param>
        /// <param name="OutputImage">Output image comming from image processor.</param>
        public static BoardConfiguration FindBoard(Bitmap InputImage, out Bitmap OutputImage)
        {
            #region Local variables

            // Figure Center
            Point figureCenter;
            // Figure BGR color
            Bgr bgrInFigureColor;
            // Vector image of figure
            CircleF circleFigure;
            //
            Color colorTransformedColor;
            //
            double hueChanel;
            double saturationChanel;
            double valueChanel;
            //
            Color circleColor;

            // Board configuration
            BoardConfiguration currentConfiguration = new BoardConfiguration();

            #endregion

            #region Equalize the image

            // Convert a BGR image to HLS range
            Emgu.CV.Image <Hls, Byte> imageHsi = new Image <Hls, Byte>(InputImage);

            // Equalize the Intensity Channel
            imageHsi[1]._EqualizeHist();
            imageHsi[2]._EqualizeHist();

            // Convert the image back to BGR range
            Emgu.CV.Image <Bgr, Byte> DrawingImage = imageHsi.Convert <Bgr, Byte>();

            // Geometric orientation image
            Emgu.CV.Image <Gray, Byte> BlobImage = imageHsi[1].Convert <Gray, Byte>();

            // Create the font.
            MCvFont TextFont = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_COMPLEX, 1.5, 1.5);

            #endregion

            try
            {
                // Get bord marker points,
                MarkersList = Board.GetBoardMarkers(BlobImage.ToBitmap());

                // If repers are 4 the proseed to describe the board.
                if (MarkersList.Length == MarkersCount)
                {
                    // Set playboard size.
                    Board.SetSize(BoardSize);

                    #region Get perspective flat image.

                    // Get perspective flat image.
                    Image <Bgr, byte> newImage = SupportMethods.GetPerspectiveFlatImage(DrawingImage, BoardSize, MarkersList);

                    #endregion

                    for (int indexFigure = 0; indexFigure < 24; indexFigure++)
                    {
                        // Set the figure center
                        figureCenter = Board.FigurePosition(indexFigure);
                        //
                        bgrInFigureColor = Board.GetFigureColor(newImage, Board.GetBoundingBox(figureCenter));
                        //
                        colorTransformedColor = Color.FromArgb(255, (byte)bgrInFigureColor.Red, (byte)bgrInFigureColor.Green, (byte)bgrInFigureColor.Blue);
                        //
                        SupportMethods.ColorToHSV(colorTransformedColor, out hueChanel, out saturationChanel, out valueChanel);
                        // Preset the color configuration
                        valueChanel      = 1.0;
                        saturationChanel = 1.0;
                        // Find the playr
                        int figure = FigureColorDefinitions.WhoIsThePlayer((int)hueChanel);
                        // Fill the board configuration
                        currentConfiguration.Figure[indexFigure] = figure;

                        #region Draw

                        if (!((hueChanel > HueChanelMin) && (hueChanel < HueChanelMax)) && (figure != -1))
                        {
                            circleColor = SupportMethods.ColorFromHSV(hueChanel, saturationChanel, valueChanel);
                            // Create figure to draw.
                            circleFigure = new CircleF(figureCenter, 10.0f);
                            // Draw circle
                            newImage.Draw(circleFigure, new Bgr(circleColor), 5);
                            // Write text
                            //
                            #region Draw label to the processed image.

                            newImage.Draw(String.Format("{0}", FigureColorDefinitions.WhoIsThePlayer((int)hueChanel)), ref TextFont, figureCenter, new Bgr(0, 0, 0));
                            //drawingImage.Draw(vectorWithSmallestY, RedColor, 2);
                            #endregion
                        }

                        #endregion
                    }

                    // Show unperspective image
                    //CvInvoke.cvShowImage("Perspective", newImage);
                    DrawingImage = newImage;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception: {0}", exception.Message);
            }

            // Apply the output image.
            OutputImage = new Bitmap(DrawingImage.Resize(OutputImageWidth, OutputImageHeight, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR).ToBitmap());

            return(currentConfiguration);
        }
Exemplo n.º 60
0
        private List<List<CircleF>> validateQuestionBoxes(List<List<CircleF>> lsAnswerAndCodeNumbersOrdered, LineSegment2D[] answerReferenceLines)
        {
            List<List<CircleF>> completAnswers = new List<List<CircleF>>();

            for (int k = 0; k < lsAnswerAndCodeNumbersOrdered.Count - 1; k++)
            {
                List<CircleF> completeAnswerPerReferenceLine = new List<CircleF>();

                for (int j = 5; j < 46; j++) //number if horizontal boxes
                {
                    if (j != 10 && j != 16 && j != 22 && j != 28 && j != 34 && j != 40)
                    {
                        int posCircle = isInsideHorizontalBox(lsAnswerAndCodeNumbersOrdered[k], answerReferenceLines[j], answerReferenceLines[j + 1]);
                        if (99999 != posCircle)
                        {
                            completeAnswerPerReferenceLine.Add(lsAnswerAndCodeNumbersOrdered[k][posCircle]);
                        }
                        else
                        {
                            PointF p = new PointF((answerReferenceLines[k].P1.X), (answerReferenceLines[j].P1.Y + answerReferenceLines[j + 1].P1.Y) / 2);
                            CircleF c = new CircleF(p, 12);
                            completeAnswerPerReferenceLine.Add(c);
                        }
                    }
                }

                completAnswers.Add(completeAnswerPerReferenceLine);

            }

            return completAnswers;
        }