Example #1
0
        // -----------------------
        // Public Constructors
        // -----------------------

        /// <summary>
        ///	Rectangle Constructor
        /// </summary>
        ///
        /// <remarks>
        ///	Creates a Rectangle from Point and Size values.
        /// </remarks>

        public Rectangle(Point location, Size size)
        {
            x      = location.X;
            y      = location.Y;
            width  = size.Width;
            height = size.Height;
        }
        /// <summary>
        /// Gets the center location of the match.
        /// </summary>
        /// <param name="m">Match.</param>
        /// <returns>The center point of the match.</returns>
        public static Point GetCenter(Match <ITemplate> m)
        {
            Rectangle matchRect   = Match.GetBoundingRect(m);
            Point     matchCenter = new Point(matchRect.X + matchRect.Width / 2, matchRect.Y + matchRect.Height / 2);

            return(matchCenter);
        }
        public static List <AForge.IntPoint> ClusterHullPoints(this List <AForge.IntPoint> points)
        {
            List <Cluster> Clusters = new List <Cluster>();

            while (points.Count > 0)
            {
                AForge.IntPoint pt = points[0];
                points.RemoveAt(0);

                Cluster cluster = new Cluster(pt);

                points.RemoveAll((p) =>
                {
                    if (cluster.CheckPoint(p))
                    {
                        cluster.Add(p);
                        return(true);
                    }

                    return(false);
                });

                Clusters.Add(cluster);
            }

            return(Clusters.Centroids());
        }
        /// <summary>
        /// Adds two 8-bit gray images.
        /// <para>Source and destination image must have the size.</para>
        /// </summary>
        /// <param name="src">Source image.</param>
        /// <param name="dst">Destination image.</param>
        /// <param name="srcOffset">The point in source image.</param>
        public static void AddTo(this Image<Gray, byte> src, Image<Gray, byte> dst, Point srcOffset)
        {
            Debug.Assert(src.Width == dst.Width && src.Height == dst.Height);

            byte* srcRow = (byte*)src.GetData(srcOffset.Y);
            byte* dstRow = (byte*)dst.ImageData;

            if (src.Stride == src.Width && dst.Stride == dst.Width)
            {
                int numElemsToAdd = src.Width * src.Height - (srcOffset.Y * src.Width + srcOffset.X);
                AddByteToByteVector(srcRow + srcOffset.X, dstRow, numElemsToAdd);
            }
            else
            {
                //first row
                int nElemsToAddFirstRow = src.Width - srcOffset.X;
                AddByteToByteVector(srcRow + srcOffset.X, dstRow, nElemsToAddFirstRow);

                //other rows
                srcRow += src.Stride;
                dstRow += dst.Stride;

                for (int r = srcOffset.Y + 1; r < src.Height; r++)
                {
                    AddByteToByteVector(srcRow, dstRow, src.Width);
                    srcRow += src.Stride;
                    dstRow += dst.Stride;
                }
            }
        }
Example #5
0
        /// <summary>
        /// Converts Imaging.NET points to AForge.NET representation.
        /// </summary>
        /// <param name="point">Points.</param>
        /// <returns>Converted points.</returns>
        public static AForge.IntPoint[] ToPoints(this Point[] points)
        {
            var result = new AForge.IntPoint[points.Length];

            Array.Copy(points, result, points.Length);

            return(result);
        }
        public override void OnMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || !this.IsSelected || isDrawn)
            {
                return;
            }

            ptFirst      = Element.ToImageCoordinate(e.Location).ToPt().Round();
            roi.Location = ptFirst; //if user draws MIN_RECT_SIZE, add it to click location
        }
Example #7
0
        /// <summary>
        /// Flips an input image horizontally / vertically / both directions / or none (data copy).
        /// </summary>
        /// <typeparam name="TColor">Color type.</typeparam>
        /// <param name="source">Input image.</param>
        /// <param name="flipDirection">Flip direction.</param>
        /// <returns>Returns flipped image.</returns>
        public static TColor[,] FlipImage <TColor>(this TColor[,] source, FlipDirection flipDirection)
        where TColor : struct
        {
            TColor[,] dest = source.CopyBlank();
            var sourceArea        = new Rectangle(0, 0, source.Width(), source.Height());
            var destinationOffset = new Point();
            source.FlipImage(sourceArea, dest, destinationOffset, flipDirection);

            return(dest);
        }
Example #8
0
        /// <summary>
        /// Draws rectangle annotation.
        /// </summary>
        /// <param name="image">Image.</param>
        /// <param name="rect">User specified area to annotate.</param>
        /// <param name="text">Label.</param>
        /// <param name="font">Font to use. Default is "Arial" of size 10, style: Bold.</param>
        public static void DrawAnnotation(this Bgr <byte>[,] image, Rectangle rect, string text, Font font)
        {
            const int VERTICAL_OFFSET = 5;

            image.Draw(rect, Bgr <byte> .Red, 1);

            var textSize     = font.GetTextSize(text, 0);
            var bottomLeftPt = new Point(rect.X + rect.Width / 2 - textSize.Width / 2, rect.Top - VERTICAL_OFFSET);

            image.Draw(text, font, new Point(), Bgr <byte> .Black);
        }
Example #9
0
        /// <summary>
        /// Draws circle.
        /// </summary>
        /// <param name="image">Input image.</param>
        /// <param name="circle">Circle</param>
        /// <param name="color">Circle color.</param>
        /// <param name="thickness">Contours thickness.</param>
        public unsafe static void Draw(this Bgr <byte>[,] image, Circle circle, Bgr <byte> color, int thickness)
        {
            using (var img = image.Lock())
            {
                var iplImage = img.AsOpenCvImage();
                var center   = new Point(circle.X, circle.Y);

                CvCoreInvoke.cvCircle(&iplImage, center, circle.Radius, color.ToCvScalar(),
                                      thickness, LineTypes.EightConnected, 0);
            }
        }
Example #10
0
        /// <summary>
        /// Copies the specified source image to the destination image.
        /// <para>Source and destination image must have the same size.</para>
        /// </summary>
        /// <typeparam name="T">Element type.</typeparam>
        /// <param name="source">Source image.</param>
        /// <param name="destination">Destination image.</param>
        /// <param name="destinationOffset">Destination location.</param>
        public static void CopyTo <T>(this T[,] source, T[,] destination, Point destinationOffset)
            where T : struct
        {
            var destRect = new Rectangle(destinationOffset, source.Size());

            using (var srcImg = source.Lock())
                using (var dstImg = destination.Lock(destRect))
                {
                    UnsafeCopy(srcImg.ImageData, dstImg.ImageData, srcImg.Stride, dstImg.Stride, dstImg.Height);
                }
        }
        private static void mirrorBorders <TColor>(TColor[,] image, TColor[,] destImage, int mirrorWidth, int mirrorHeight)
            where TColor : struct
        {
            //top
            Rectangle srcTop       = new Rectangle(0, 0, image.Width(), mirrorHeight);
            Point     dstTopOffset = new Point(srcTop.X + mirrorWidth, srcTop.Y + 0);

            image.FlipImage(srcTop, destImage, dstTopOffset, FlipDirection.Vertical);

            //bottom
            Rectangle srcBottom       = new Rectangle(0, image.Height() - mirrorHeight, image.Width(), mirrorHeight);
            Point     dstBottomOffset = new Point(srcBottom.X + mirrorWidth, srcBottom.Y + 2 * mirrorHeight);

            image.FlipImage(srcBottom, destImage, dstBottomOffset, FlipDirection.Vertical);

            //left
            Rectangle srcLeft       = new Rectangle(0, 0, mirrorWidth, image.Height());
            Point     dstLeftOffset = new Point(srcLeft.X + 0, srcLeft.Y + mirrorHeight);

            image.FlipImage(srcLeft, destImage, dstLeftOffset, FlipDirection.Horizontal);

            //right
            Rectangle srcRight       = new Rectangle(image.Width() - mirrorWidth, 0, mirrorWidth, image.Height());
            Point     dstRightOffset = new Point(srcRight.X + 2 * mirrorWidth, srcRight.Y + mirrorHeight);

            image.FlipImage(srcRight, destImage, dstRightOffset, FlipDirection.Horizontal);


            //top-left
            Rectangle srcTopLeft       = new Rectangle(0, 0, mirrorWidth, mirrorHeight);
            Point     dstTopLeftOffset = new Point(srcTopLeft.X + 0, srcTopLeft.Y + 0);

            image.FlipImage(srcTopLeft, destImage, dstTopLeftOffset, FlipDirection.All);

            //bottom-left
            Rectangle srcBottomLeft       = new Rectangle(0, image.Height() - mirrorHeight, mirrorWidth, mirrorHeight);
            Point     dstBottomLeftOffset = new Point(srcBottomLeft.X + 0, srcBottomLeft.Y + 2 * mirrorHeight);

            image.FlipImage(srcBottomLeft, destImage, dstBottomLeftOffset, FlipDirection.All);

            //top-right
            Rectangle srcTopRight       = new Rectangle(image.Width() - mirrorWidth, 0, mirrorWidth, mirrorHeight);
            Point     dstTopRightOffset = new Point(srcTopRight.X + 2 * mirrorWidth, srcTopRight.Y + 0);

            image.FlipImage(srcTopRight, destImage, dstTopRightOffset, FlipDirection.All);

            //bottom-right
            Rectangle srcBottomRight       = new Rectangle(image.Width() - mirrorWidth, image.Height() - mirrorHeight, mirrorWidth, mirrorHeight);
            Point     dstBottomRightOffset = new Point(srcBottomRight.X + 2 * mirrorWidth, srcBottomRight.Y + 2 * mirrorHeight);

            image.FlipImage(srcBottomRight, destImage, dstBottomRightOffset, FlipDirection.All);
        }
        /// <summary>
        ///  Maximum cross-correlation feature point matching algorithm.
        /// </summary>
        /// <param name="correlationMatching"> Maximum cross-correlation feature point matching algorithm.</param>
        /// <param name="image1">First image.</param>
        /// <param name="image2">Second image.</param>
        /// <param name="points1">Points from the first image.</param>
        /// <param name="points2">Points from the second image.</param>
        /// <returns>Matched point-pairs.</returns>
        public static Point[][] Match(this CorrelationMatching correlationMatching,
            Image<Gray, byte> image1, Image<Gray, byte> image2, Point[] points1, Point[] points2)
        {
            var result = correlationMatching.Match
                (
                  image1.ToBitmap(copyAlways: false, failIfCannotCast: true),
                  image2.ToBitmap(copyAlways: false, failIfCannotCast: true),
                  points1,
                  points2
                );

            return result;
        }
Example #13
0
        public override void OnMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || !this.IsSelected || isDrawn)
            {
                return;
            }

            pt = Element.ToImageCoordinate(e.Location.ToPt()).Round();

            var imageSize = Element.Image.Size.ToSize();

            this.Annotation.Polygon = new Point[] { pt.Clamp(imageSize) };
            isDrawn = true;
        }
Example #14
0
        public bool CheckPoint(AForge.IntPoint pt)
        {
            float radius = 20.0f;

            return(Points.FindAll((p) =>
            {
                if (p.DistanceTo(pt) <= 2 * radius)
                {
                    return true;
                }

                return false;
            }).Count > 0);
        }
Example #15
0
        private static Gray <short>[,] calculateSimilarityMap(ITemplate template, LinearizedMaps maps, Rectangle searchArea)
        {
            Debug.Assert(searchArea.Right <= maps.ImageSize.Width &&
                         searchArea.Bottom <= maps.ImageSize.Height);
            Debug.Assert(template.Size.Width + searchArea.X < maps.ImageSize.Width &&
                         template.Size.Height + searchArea.Y < maps.ImageSize.Height);

            int width  = searchArea.Width / maps.NeigborhoodSize;
            int height = searchArea.Height / maps.NeigborhoodSize;

            Gray <short>[,] similarityMap = new Gray <short> [height, width]; //performance penalty (alloc, dealloc)!!!
            Gray <byte>[,] buffer         = new Gray <byte> [height, width];

            using (var uSimilarityMap = similarityMap.Lock())
                using (var uBuffer = buffer.Lock())
                {
                    int nAddsInBuffer = 0;
                    foreach (var feature in template.Features)
                    {
                        var position = new Point(feature.X + searchArea.X, feature.Y + searchArea.Y); //shifted position

                        Point mapPoint;
                        var   neighbourMap = maps.GetMapElement(position, feature.AngleIndex, out mapPoint);

                        neighbourMap.AddTo(uBuffer, mapPoint);
                        nAddsInBuffer++;

                        if (nAddsInBuffer / GlobalParameters.MAX_SUPPORTED_NUM_OF_FEATURES_ADDDED_AS_BYTE != 0)
                        {
                            uBuffer.AddTo(uSimilarityMap);
                            buffer.Clear(); //clear buffer

                            nAddsInBuffer = 0;
                        }
                    }

                    bool finalAdd = (template.Features.Length % GlobalParameters.MAX_SUPPORTED_NUM_OF_FEATURES_ADDDED_AS_BYTE != 0) ? true : false;
                    if (finalAdd)
                    {
                        uBuffer.AddTo(uSimilarityMap);
                    }
                }

            return(similarityMap);
        }
Example #16
0
        public Image <Gray <byte> > GetMapElement(Point position, int angleIndex, out Point mapPoint)
        {
            //find corresponding linearized map for neighbor
            int gridX = position.X % this.NeigborhoodSize;
            int gridY = position.Y % this.NeigborhoodSize;

            //find corresponding position
            int elemX = position.X / this.NeigborhoodSize;
            int elemY = position.Y / this.NeigborhoodSize;

            //get corresponding map and (row, col)
            var map = this.LinearMaps[angleIndex][gridY, gridX];

            //corresponding point in returned map
            mapPoint = new Point(elemX, elemY);

            return(map);
        }
Example #17
0
        public void gazedMarkerHistory_Update(ExtractedGlyphData glyph, AForge.Point gaze)
        {
            gazedMarkerHistory_Shift();

            gazedMarkerHistory[0].name = "";
            gazedMarkerHistory[0].tag  = "";

            if (glyph != null)
            {
                AForge.IntPoint minXY, maxXY;
                PointsCloud.GetBoundingRectangle(glyph.Quadrilateral, out minXY, out maxXY);
                AForge.IntPoint center = (minXY + maxXY) / 2;
                gazedMarkerHistory[0].tag          = "";
                gazedMarkerHistory[0].gaze         = gaze;
                gazedMarkerHistory[0].markerCenter = new Point(center.X, center.Y);
                gazedMarkerHistory[0].name         = glyph.RecognizedGlyph != null? glyph.RecognizedGlyph.Name:"";
            }
        }
Example #18
0
        /// <summary>
        /// distance is metured in Marker diameter unit. e.g. 1 diameter 2 diameter ....
        /// </summary>
        /// <param name="glyph"></param>
        /// <param name="gaze"></param>
        /// <returns></returns>
        public double  getGazeDistance(ExtractedGlyphData glyph, AForge.Point gaze)
        {
            double dis = 0;

            AForge.IntPoint minXY, maxXY;
            PointsCloud.GetBoundingRectangle(glyph.Quadrilateral, out minXY, out maxXY);
            AForge.IntPoint center = (minXY + maxXY) / 2;
            dis = GetDistance(new Point(center.X, center.Y), new Point((int)gaze.X, (int)gaze.Y));


            PointsCloud.GetBoundingRectangle(glyph.Quadrilateral, out minXY, out maxXY);
            double glyphDiameter = Math.Sqrt(2) * ((maxXY - minXY).X);


            dis = dis / glyphDiameter;

            return(dis);
        }
Example #19
0
        /// <summary>
        /// Gets closest point to the <paramref name="ptIdx"/>.
        /// </summary>
        /// <param name="contour">Contour.</param>
        /// <param name="ptIdx">Point index for which to find the closest point.</param>
        /// <param name="searchSegment">Contour segment to search.</param>
        /// <param name="distance">Distance from <paramref name="ptIdx"/> to returned point index.</param>
        /// <returns>Closest point index regarding <paramref name="ptIdx"/>.</returns>
        public static int GetClosestPoint(this IList <Point> contour, int ptIdx, Range searchSegment, out double distance)
        {
            double minDist   = Double.MaxValue;
            int    closestPt = -1;

            Point pt  = contour[ptIdx];
            int   idx = (int)searchSegment.Min;

            while (idx != (int)searchSegment.Max)
            {
                var dist = ((PointF)pt).DistanceTo(contour[idx]);
                if (dist < minDist)
                {
                    minDist   = dist;
                    closestPt = idx;
                }

                idx = (idx + 1) % contour.Count;
            }

            distance = minDist;
            return(closestPt);
        }
Example #20
0
        /// <summary>
        ///  anglebetween gazepoint, glyph center and top point of the glyph
        /// </summary>
        /// <param name="glyph"></param>
        /// <param name="gaze"></param>
        /// <returns></returns>
        public int getGazeAngle(ExtractedGlyphData glyph, AForge.Point gaze)
        {
            int angle = 0;

            //gaze
            AForge.IntPoint g = new AForge.IntPoint(Convert.ToInt32(gaze.X), Convert.ToInt32(gaze.Y));

            //top point
            Point topCenter = new Point(0, 0);
            int   i = 0, j = 1;

            topCenter.X = (glyph.Quadrilateral[i].X + glyph.Quadrilateral[j].X) / 2;
            topCenter.Y = (glyph.Quadrilateral[i].Y + glyph.Quadrilateral[j].Y) / 2;
            AForge.IntPoint top = new AForge.IntPoint(topCenter.X, topCenter.Y);

            //center
            AForge.IntPoint minXY, maxXY;
            PointsCloud.GetBoundingRectangle(glyph.Quadrilateral, out minXY, out maxXY);
            AForge.IntPoint center = (minXY + maxXY) / 2;
            AForge.IntPoint cnt    = new AForge.IntPoint(center.X, center.Y);

            angle = (int)(AForge.Math.Geometry.GeometryTools.GetAngleBetweenVectors(cnt, g, top));

            int direc = 1;

            if ((cnt.X - top.X) != 0 && (g.Y - cnt.Y - ((cnt.Y - top.Y) / (cnt.X - top.X)) * (g.X - cnt.X)) < 0)
            {
                direc = -1;
            }

            // if (top.X < cnt.X) direc *= -1;

            angle *= direc;


            return(angle);
        }
Example #21
0
        private static List <Match> matchTemplate(this LinearizedMaps linMaps, ITemplate template, Rectangle searchArea, int minMatchingPercentage, bool filterPartialObjects = true)
        {
            //just do matching for templates that can fit into query image
            if (template.Size.Width > linMaps.ImageValidSize.Width ||
                template.Size.Height > linMaps.ImageValidSize.Height)
            {
                return(new List <Match>());
            }

            var similarityMap = calculateSimilarityMap(template, linMaps, searchArea);

            float rawScoreScale       = 100f / (GlobalParameters.MAX_FEATURE_SIMILARITY * template.Features.Length);
            short minMatchingRawScore = (short)System.Math.Round(minMatchingPercentage * (1 / rawScoreScale));

            List <short> rawScores;
            var          foundMatchPoints = searchSimilarityMap(similarityMap, minMatchingRawScore, out rawScores);

            var offset          = new Point(searchArea.X, searchArea.Y);
            var foundCandidates = createMatches(template, linMaps.NeigborhoodSize, foundMatchPoints, offset, rawScores, rawScoreScale);

            filterPartialShownObjects(ref foundCandidates, linMaps.ImageSize);

            return(foundCandidates);
        }
Example #22
0
        /// <summary>
        /// Gets closest point to the <paramref name="ptIdx"/> starting from a <paramref name="startIdx"/> moving in the <paramref name="direction"/>.
        /// Scale <paramref name="scale"/> is used to avoid local minima if contour is noisy.
        /// </summary>
        /// <param name="contour">Contour.</param>
        /// <param name="ptIdx">Point index for which to find the closest point.</param>
        /// <param name="startIdx">Start point from which the search begins.</param>
        /// <param name="direction">Search direction. If &gt; 0 then search continues in the positive direction, if &lt; 0 then search is continued toward negative indexes.</param>
        /// <param name="scale">A good value is ~15. A specified region will be searched every time to avoid local minima.</param>
        /// <param name="distance">Distance from <paramref name="ptIdx"/> to returned point index.</param>
        /// <returns>Closest point index regarding <paramref name="ptIdx"/>.</returns>
        public static int GetClosestPoint(this IList <Point> contour, int ptIdx, int startIdx, int direction, int scale, out double distance)
        {
            double minDist   = Double.MaxValue;
            int    closestPt = -1;

            Point pt  = contour[ptIdx];
            int   idx = startIdx;

            while (true)
            {
                var idxB = (idx + direction * scale) % contour.Count;
                if (idxB < 0)
                {
                    idxB += contour.Count;
                }

                double foundDist;
                var    searchRange = (direction > 0) ? new Range(idx, idxB) : new Range(idxB, idx);
                int    foundPt     = GetClosestPoint(contour, ptIdx, searchRange, out foundDist);

                idx = idxB;

                if (foundDist < minDist)
                {
                    minDist   = foundDist;
                    closestPt = foundPt;
                }
                else
                {
                    break;
                }
            }

            distance = minDist;
            return(closestPt);
        }
Example #23
0
        /// <summary>
        /// Flips an input image horizontally / vertically / both directions / or none (data copy).
        /// </summary>
        /// <typeparam name="TColor">Color type.</typeparam>
        /// <param name="source">Input image.</param>
        /// <param name="sourceArea">Source area.</param>
        /// <param name="destination">Destination image.</param>
        /// <param name="destinationOffset">Destination image offset.</param>
        /// <param name="flipDirection">Flip direction.</param>
        public static void FlipImage <TColor>(this TColor[,] source, Rectangle sourceArea, TColor[,] destination, Point destinationOffset, FlipDirection flipDirection)
        {
            int startDstRow = 0; int vDirection = 1;
            int startDstCol = 0; int hDirection = 1;

            if ((flipDirection & FlipDirection.Vertical) != 0)
            {
                startDstRow = (destinationOffset.Y + sourceArea.Height) - 1; vDirection = -1;
            }
            if ((flipDirection & FlipDirection.Horizontal) != 0)
            {
                startDstCol = (destinationOffset.X + sourceArea.Width) - 1; hDirection = -1;
            }

            for (int srcRow = 0, dstRow = startDstRow; srcRow < sourceArea.Bottom; srcRow++, dstRow += vDirection)
            {
                for (int srcCol = 0, dstCol = startDstCol; srcCol < sourceArea.Right; srcCol++, dstCol += hDirection)
                {
                    destination[dstRow, dstCol] = source[srcRow, srcCol];
                }
            }
        }
        public override void OnMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || !this.IsSelected || isDrawn)
                return;

            ptFirst = Element.ToImageCoordinate(e.Location.ToPt()).Round();
            roi.Location = ptFirst; //if user draws MIN_RECT_SIZE, add it to click location
        }
Example #25
0
        private static List <Match> createMatches(ITemplate template, int neigborhood, List <Point> mapPositions, Point offset, List <short> rawScores, float rawScoreScale)
        {
            var matches    = new List <Match>();
            int allignment = neigborhood / 2;

            for (int i = 0; i < mapPositions.Count; i++)
            {
                var match = new Match
                {
                    X        = mapPositions[i].X * neigborhood + allignment + offset.X,
                    Y        = mapPositions[i].Y * neigborhood + allignment + offset.Y,
                    Score    = rawScores[i] * rawScoreScale,
                    Template = template
                };

                matches.Add(match);
            }

            return(matches);
        }
 /// <summary>
 ///   Computes the distance from circle to point.
 /// </summary>
 /// 
 /// <param name="point">The point to have its distance from the circle computed.</param>
 /// 
 /// <returns>The distance from <paramref name="point"/> to this circle.</returns>
 /// 
 public double DistanceToPoint(Point point)
 {
     var centerDiff = Accord.Math.Distance.Euclidean(X, Y, point.X, point.Y);
     return System.Math.Abs(centerDiff - Radius);
 }
 /// <summary>
 ///	Contains Method
 /// </summary>
 ///
 /// <remarks>
 ///	Checks if a Point lies within this Rectangle.
 /// </remarks>
 public bool Contains(Point pt)
 {
     return Contains(pt.X, pt.Y);
 }
        private static List<Match> createMatches(ITemplate template, int neigborhood, List<Point> mapPositions, Point offset, List<short> rawScores, float rawScoreScale)
        {
            var matches = new List<Match>();
            int allignment = neigborhood / 2;

            for (int i = 0; i < mapPositions.Count; i++)
            {
                var match = new Match
                {
                    X = mapPositions[i].X * neigborhood + allignment + offset.X,
                    Y = mapPositions[i].Y * neigborhood + allignment + offset.Y,
                    Score = rawScores[i] * rawScoreScale,
                    Template = template
                };

                matches.Add(match);
            }

            return matches;
        }
Example #29
0
        /// <summary>
        ///	Offset Method
        /// </summary>
        ///
        /// <remarks>
        ///	Moves the Rectangle a specified distance.
        /// </remarks>

        public void Offset(Point pos)
        {
            x += pos.X;
            y += pos.Y;
        }
Example #30
0
 /// <summary>
 /// Creates a new instance of an <see cref="CircleF"/> structure.
 /// </summary>
 /// <param name="position">Center position.</param>
 /// <param name="radius">Circle radius.</param>
 public Circle(Point position, int radius)
     : this(position.X, position.Y, radius)
 {
 }
        private static List<Match> matchTemplate(this LinearizedMaps linMaps, ITemplate template, Rectangle searchArea, int minMatchingPercentage, bool filterPartialObjects = true)
        {
            //just do matching for templates that can fit into query image
            if (template.Size.Width > linMaps.ImageValidSize.Width ||
                template.Size.Height > linMaps.ImageValidSize.Height)
                return new List<Match>();

            var similarityMap = calculateSimilarityMap(template, linMaps, searchArea);

            float rawScoreScale = 100f / (GlobalParameters.MAX_FEATURE_SIMILARITY * template.Features.Length);
            short minMatchingRawScore = (short)System.Math.Round(minMatchingPercentage * (1 / rawScoreScale));

            List<short> rawScores;
            var foundMatchPoints = searchSimilarityMap(similarityMap, minMatchingRawScore, out rawScores);

            var offset = new Point(searchArea.X, searchArea.Y);
            var foundCandidates = createMatches(template, linMaps.NeigborhoodSize, foundMatchPoints, offset, rawScores, rawScoreScale);

            filterPartialShownObjects(ref foundCandidates, linMaps.ImageSize);

            return foundCandidates;
        }
Example #32
0
        public void VisualizeGlyph(Bitmap bitmap, Dictionary <string, string> names)
        {
            lock (this)
            {
                if (foundGlyphs.Count > 0)
                {
                    if ((visualizationType == VisualizationType.BorderOnly) ||
                        (visualizationType == VisualizationType.Name))
                    {
                        Graphics g = Graphics.FromImage(bitmap);

                        // highlight each found glyph
                        foreach (ExtractedGlyphData glyphData in foundGlyphs)
                        {
                            if ((glyphData.RecognizedGlyph == null) || (glyphData.RecognizedGlyph.UserData == null))
                            {
                                // highlight with default pen
                                g.DrawPolygon(defaultPen, ToPointsArray(glyphData.Quadrilateral));
                            }
                            else
                            {
                                GlyphVisualizationData visualization =
                                    (GlyphVisualizationData)glyphData.RecognizedGlyph.UserData;

                                Pen pen = new Pen(visualization.Color, 3);

                                // highlight border
                                g.DrawPolygon(pen, ToPointsArray(glyphData.Quadrilateral));

                                // show glyph's name
                                if (visualizationType == VisualizationType.Name)
                                {
                                    // get glyph's center point
                                    AForge.IntPoint minXY, maxXY;
                                    PointsCloud.GetBoundingRectangle(glyphData.Quadrilateral, out minXY, out maxXY);
                                    AForge.IntPoint center = (minXY + maxXY) / 2;


                                    string GyphName = "";
                                    if (names.ContainsKey(glyphData.RecognizedGlyph.Name))
                                    {
                                        GyphName = names[glyphData.RecognizedGlyph.Name];
                                    }

                                    // glyph's name size
                                    SizeF nameSize = g.MeasureString(GyphName, defaultFont);

                                    // paint the name
                                    Brush brush = new SolidBrush(visualization.Color);

                                    g.DrawString(GyphName, defaultFont, brush,
                                                 new Point(center.X - (int)nameSize.Width / 2, center.Y - (int)nameSize.Height / 2));

                                    brush.Dispose( );
                                }

                                pen.Dispose( );
                            }
                        }
                    }
                }
            }
        }
 /// <summary>
 ///	Offset Method
 /// </summary>
 ///
 /// <remarks>
 ///	Moves the Rectangle a specified distance.
 /// </remarks>
 public void Offset(Point pos)
 {
     x += pos.X;
     y += pos.Y;
 }
Example #34
0
        // -----------------------
        // Public Constructors
        // -----------------------

        /// <summary>
        ///	Size Constructor
        /// </summary>
        ///
        /// <remarks>
        ///	Creates a Size from a Point value.
        /// </remarks>

        public Size(Point pt)
        {
            width  = pt.X;
            height = pt.Y;
        }
Example #35
0
        /// <summary>
        /// Adds two 8-bit gray images.
        /// <para>Source and destination image must have the size.</para>
        /// </summary>
        /// <param name="src">Source image.</param>
        /// <param name="dst">Destination image.</param>
        /// <param name="srcOffset">The point in source image.</param>
        public static void AddTo(this Image <Gray, byte> src, Image <Gray, byte> dst, Point srcOffset)
        {
            Debug.Assert(src.Width == dst.Width && src.Height == dst.Height);

            byte *srcRow = (byte *)src.GetData(srcOffset.Y);
            byte *dstRow = (byte *)dst.ImageData;

            if (src.Stride == src.Width && dst.Stride == dst.Width)
            {
                int numElemsToAdd = src.Width * src.Height - (srcOffset.Y * src.Width + srcOffset.X);
                AddByteToByteVector(srcRow + srcOffset.X, dstRow, numElemsToAdd);
            }
            else
            {
                //first row
                int nElemsToAddFirstRow = src.Width - srcOffset.X;
                AddByteToByteVector(srcRow + srcOffset.X, dstRow, nElemsToAddFirstRow);

                //other rows
                srcRow += src.Stride;
                dstRow += dst.Stride;

                for (int r = srcOffset.Y + 1; r < src.Height; r++)
                {
                    AddByteToByteVector(srcRow, dstRow, src.Width);
                    srcRow += src.Stride;
                    dstRow += dst.Stride;
                }
            }
        }
        public override void OnMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || !this.IsSelected || isDrawn)
                return;

            pt = Element.ToImageCoordinate(e.Location.ToPt()).Round();

            var imageSize = Element.Image.Size.ToSize();
            this.Annotation.Polygon = new Point[] { pt.Clamp(imageSize) };
            isDrawn = true;
        }
 /// <summary>
 /// Creates a new instance of an <see cref="CircleF"/> structure.
 /// </summary>
 /// <param name="position">Center position.</param>
 /// <param name="radius">Circle radius.</param>
 public Circle(Point position, int radius)
     : this(position.X, position.Y, radius)
 {
 }
Example #38
0
        /// <summary>
        ///   Computes the distance from circle to point.
        /// </summary>
        ///
        /// <param name="point">The point to have its distance from the circle computed.</param>
        ///
        /// <returns>The distance from <paramref name="point"/> to this circle.</returns>
        ///
        public double DistanceToPoint(Point point)
        {
            var centerDiff = Accord.Math.Distance.Euclidean(X, Y, point.X, point.Y);

            return(System.Math.Abs(centerDiff - Radius));
        }
 // -----------------------
 // Public Constructors
 // -----------------------
 /// <summary>
 ///	Size Constructor
 /// </summary>
 ///
 /// <remarks>
 ///	Creates a Size from a Point value.
 /// </remarks>
 public Size(Point pt)
 {
     width = pt.X;
     height = pt.Y;
 }
Example #40
0
        private static unsafe void convolveFloat(IImage src, Rectangle sourceWorkingArea, IImage dest, Point destLoc, IImage kernel)
        {
            int srcStride  = src.Stride;
            int destStride = dest.Stride;

            float *kernelPtr    = (float *)kernel.ImageData;
            int    kernelWidth  = kernel.Width;
            int    kernelHeight = kernel.Height;
            int    nChannels    = src.ColorInfo.NumberOfChannels;


            for (int channel = 0; channel < nChannels; channel++)
            {
                float *srcPtr  = (float *)src.GetData(sourceWorkingArea.Y, sourceWorkingArea.X) + channel;
                float *destPtr = (float *)dest.GetData(destLoc.Y, destLoc.X) + channel;

                for (int row = sourceWorkingArea.Y; row < sourceWorkingArea.Bottom; row++)
                {
                    int chCol = 0;
                    for (int col = sourceWorkingArea.X; col < sourceWorkingArea.Right; col++)
                    {
                        destPtr[chCol] = applyKernelFloat(kernelPtr, &srcPtr[chCol], kernelWidth, kernelHeight, srcStride, nChannels);
                        chCol         += nChannels;
                    }

                    srcPtr  += srcStride / sizeof(float);
                    destPtr += destStride / sizeof(float);
                }
            }
        }
        public Image<Gray, byte> GetMapElement(Point position, int angleIndex, out Point mapPoint)
        {
            //find corresponding linearized map for neighbour
            int gridX = position.X % this.NeigborhoodSize;
            int gridY = position.Y % this.NeigborhoodSize;

            //find corresponsing position
            int elemX = position.X / this.NeigborhoodSize;
            int elemY = position.Y / this.NeigborhoodSize;

            //get corresponding map and (row, col)
            var map = this.LinearMaps[angleIndex][gridY, gridX];

            //corresponding point in returned map
            mapPoint = new Point(elemX, elemY);

            return map;
        }
Example #42
0
        /// <summary>
        ///	Contains Method
        /// </summary>
        ///
        /// <remarks>
        ///	Checks if a Point lies within this Rectangle.
        /// </remarks>

        public bool Contains(Point pt)
        {
            return(Contains(pt.X, pt.Y));
        }
 // -----------------------
 // Public Constructors
 // -----------------------
 /// <summary>
 ///	Rectangle Constructor
 /// </summary>
 ///
 /// <remarks>
 ///	Creates a Rectangle from Point and Size values.
 /// </remarks>
 public Rectangle(Point location, Size size)
 {
     x = location.X;
     y = location.Y;
     width = size.Width;
     height = size.Height;
 }
        /// <summary>
        /// Converts Imaging.NET points to AForge.NET representation.
        /// </summary>
        /// <param name="point">Points.</param>
        /// <returns>Converted points.</returns>
        public static AForge.IntPoint[] ToPoints(this Point[] points)
        {
            var result = new AForge.IntPoint[points.Length];
            Array.Copy(points, result, points.Length);

            return result;
        }
        private static Image<Gray, short> calculateSimilarityMap(ITemplate template, LinearizedMaps maps, Rectangle searchArea)
        {
            Debug.Assert(searchArea.Right <= maps.ImageSize.Width &&
                         searchArea.Bottom <= maps.ImageSize.Height);
            Debug.Assert(template.Size.Width + searchArea.X < maps.ImageSize.Width &&
                         template.Size.Height + searchArea.Y < maps.ImageSize.Height);

            int width = searchArea.Width / maps.NeigborhoodSize;
            int height = searchArea.Height / maps.NeigborhoodSize;

            Image<Gray, short> similarityMap = new Image<Gray, short>(width, height, LinearizedMaps.MAP_STRIDE_ALLIGNMENT); //performance penalty (alloc, dealloc)!!!

            using (var buffer = new Image<Gray, byte>(width, height, LinearizedMaps.MAP_STRIDE_ALLIGNMENT)) //performance penalty (alloc, dealloc)!!!
            {
                int nAddsInBuffer = 0;

                foreach (var feature in template.Features)
                {
                    var position = new Point(feature.X + searchArea.X, feature.Y + searchArea.Y); //shifted position

                    Point mapPoint;
                    var neighbourMap = maps.GetMapElement(position, feature.AngleIndex, out mapPoint);

                    neighbourMap.AddTo(buffer, mapPoint);
                    nAddsInBuffer++;

                    if (nAddsInBuffer / GlobalParameters.MAX_SUPPORTED_NUM_OF_FEATURES_ADDDED_AS_BYTE != 0)
                    {
                        buffer.AddTo(similarityMap);
                        buffer.Clear();

                        nAddsInBuffer = 0;
                    }
                }

                bool finalAdd = (template.Features.Length % GlobalParameters.MAX_SUPPORTED_NUM_OF_FEATURES_ADDDED_AS_BYTE != 0) ? true : false;
                if (finalAdd)
                {
                    buffer.AddTo(similarityMap);
                }
            }

            return similarityMap;
        }