1
votes

What I want to do:

I want to get the minimal amount of points from a polygon that will create the same polygon:

For example, if I had this polygon:

(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (0,4), (4,4)

It will create a polygon that its location is 0, 0, its width 4 and its height 4.

If I were to enter this polygon to the hypothetical algorithm it will return:

(0, 0), (4, 0), (0, 4), (4, 4)

Why I want to do it:

I'm creating a game, and the game has animations, each animation has its own images and polygons (the bounds of the images), I already have the images for the animations, but I don't have the polygons for them, of course, I could just create the polygons myself but it would be exhausting to create polygons manually for 100+ images, not to talk about adding/modifying animations.

What I've tried:

My idea was this:

Scan the image, pixel by pixel, check if the pixel is blank, and if it isn't, add it to a list, once this is done use some sort of algorithm to get the minimal amount of points to create the same polygon.

I did some research and I thought the LLTS (Long Live The Square) algorithm was what I needed, so I've written this code using cansik's implementation of it in C#:

    private readonly Bitmap _image;
    private Point[] _result;

    private void Calculate()
    {
        List<Vector2D> points = new List<Vector2D>();
        for (int x = 0; x < _image.Width; x++)
        {
            for (int y = 0; y < _image.Height; y++)
            {
                // Check if the pixel is blank
                if (_image.GetPixel(x, y).ToArgb() != 16777215)
                {
                    // If the pixel isn't blank, add it to the list
                    points.Add(new Vector2D(x, y));
                }

            }
        }
        Vector2D[] resultInVectors = GeoAlgos.MonotoneChainConvexHull(points.ToArray());
        _result = new Point[resultInVectors.Length];
        for (int i = 0; i < resultInVectors.Length; i++)
        {
            _result[i] = new Point((int)resultInVectors[i].X, (int)resultInVectors[i].Y);
        }
    }

I added the paint code:

private void Form_Paint(object sender, PaintEventArgs e)
    {

        e.Graphics.DrawPolygon(Pens.Black, _result);
        e.Graphics.DrawImage(_image, new Point(100, 0));
    }

In the end, I run the program and this is what I got:

The result

This is not exactly what I've had in mind, to say the least, I expected it to be something like this:

What I expected

Any ideas?

EDIT - FINALLY SOLVED IT

I used Wowa's answer to Trevor Elliott's question, then, I minimized the number of points in the result by using this function that I created:

    private static List<Point> MinimizePoints(List<Point> points)
    {
        if (points.Count < 3)
        {
            return points;
        }
        List<Point> minimumPoints = new List<Point>(points);

        for (int i = minimumPoints.Count - 1; i > 2; i -= 3)
        {
            List<Point> currentPoints = minimumPoints.GetRange(i - 3, 3);
            try
            {
                if ((currentPoints[2].X - currentPoints[0].X) / (currentPoints[1].X - currentPoints[0].X) ==
                    (currentPoints[2].Y - currentPoints[0].Y) / (currentPoints[1].Y - currentPoints[0].Y))
                {
                    minimumPoints.Remove(minimumPoints[i + 1]);
                }
            }
            catch (DivideByZeroException)
            {
                // Ignore
            }
        }
        return minimumPoints;
    }

I used Oliver Charlesworth's answer to Prashant C's question.

SECOND EDIT - A MORE OPTIMIZED SOLUTION

Instead of using my own meh algorithm for reducing points I used the Ramer–Douglas–Peucker algorithm and set ε (the tolerance) to 0. Here's the implementation that I used:

private static class DouglasPeuckerReduction
    {
        public static Point[] ReducePoints(Point[] existingPolygon)
        {
            if (existingPolygon == null || existingPolygon.Length < 3)
                return existingPolygon;

            int firstPoint = 0;
            int lastPoint = existingPolygon.Length - 1;
            List<int> pointIndexsToKeep = new List<int>();

            //Add the first and last index to the keepers
            pointIndexsToKeep.Add(firstPoint);
            pointIndexsToKeep.Add(lastPoint);

            //The first and the last point cannot be the same
            while (existingPolygon[firstPoint].Equals(existingPolygon[lastPoint]))
            {
                lastPoint--;
            }

            ReducePoints(existingPolygon, firstPoint, lastPoint,
                0, ref pointIndexsToKeep);

            pointIndexsToKeep.Sort();
            return pointIndexsToKeep.Select(index => existingPolygon[index]).ToArray();
        }

        /// <summary>
        /// Douglases the peucker reduction.
        /// </summary>
        /// <param name="points">The points.</param>
        /// <param name="firstPoint">The first point.</param>
        /// <param name="lastPoint">The last point.</param>
        /// <param name="tolerance">The tolerance.</param>
        /// <param name="pointIndexesToKeep">The point index to keep.</param>
        private static void ReducePoints(IReadOnlyList<Point> points, int firstPoint, int lastPoint, double tolerance,
            ref List<int> pointIndexesToKeep)
        {
            double maxDistance = 0;
            int indexFarthest = 0;

            for (int index = firstPoint; index < lastPoint; index++)
            {
                double distance = PerpendicularDistance
                    (points[firstPoint], points[lastPoint], points[index]);
                if (distance > maxDistance)
                {
                    maxDistance = distance;
                    indexFarthest = index;
                }
            }

            if (maxDistance > tolerance && indexFarthest != 0)
            {
                //Add the largest point that exceeds the tolerance
                pointIndexesToKeep.Add(indexFarthest);

                ReducePoints(points, firstPoint,
                    indexFarthest, tolerance, ref pointIndexesToKeep);
                ReducePoints(points, indexFarthest,
                    lastPoint, tolerance, ref pointIndexesToKeep);
            }
        }

        /// <summary>
        /// The distance of a point from a line made from point1 and point2.
        /// </summary>
        /// <param name="pt1">The PT1.</param>
        /// <param name="pt2">The PT2.</param>
        /// <param name="p">The p.</param>
        /// <returns></returns>
        private static double PerpendicularDistance
            (Point Point1, Point Point2, Point Point)
        {
            //Area = |(1/2)(x1y2 + x2y3 + x3y1 - x2y1 - x3y2 - x1y3)|   *Area of triangle
            //Base = v((x1-x2)²+(x1-x2)²)                               *Base of Triangle*
            //Area = .5*Base*H                                          *Solve for height
            //Height = Area/.5/Base

            double area = Math.Abs(.5 * (Point1.X * Point2.Y + Point2.X *
                                         Point.Y + Point.X * Point1.Y - Point2.X * Point1.Y - Point.X *
                                         Point2.Y - Point1.X * Point.Y));
            double bottom = Math.Sqrt(Math.Pow(Point1.X - Point2.X, 2) +
                                      Math.Pow(Point1.Y - Point2.Y, 2));
            double height = area / bottom * 2;

            return height;

        }
    }
1
It feels like you are looking for Image Edge Detection algorithm here e.g. softwarebydefault.com/2013/05/11/image-edge-detectionEugene Komisarenko

1 Answers

1
votes

I think the answer by @ShashwatKumar misunderstood your question? If not, then I am misunderstanding it!

The way I read your post, you are looking to find a polygonal outline of your figure. This is called tracing the contour/outline of a binary image, whose first step, as @EugeneKomisarenko says in a comment, is "edge detection" (but then there are further steps). Searching for variations on these phrases will hit many algorithms, e.g.:


Contour
Image from this link.
Given a set of 2D vertices, how to create a minimum-area polygon which contains all the given vertices?