Search code examples
c#bitmappixel

Find the center coordinate of a circle from a list of pixel coordinates C#


I have a BitMap image where the image contains a black circle. I have found all the pixels from the image that are black which represent the circle and have saved the points into a List.

Where I am lost is finding the center of the circle from coordinates saved in the list. I am thinking that I need to find the diameter of the circle somehow but how do I loop though the pixels to do that to determine that?


Solution

  • One naive approach could be to find the bounding box for the circle.

    Seeing as you already have all of the points in a list you can find the top, bottom, left and right.

    Assuming the (0,0) is the top left of the co-ordinate system:

    • The top is the point with min Y.
    • The bottom is the point with max Y.
    • The left is the point with min X.
    • The right is the point with max X.

    The center of the bounding box is the center of the circle. Similarly the width/height of the bounding box is its diameter.

    Edit: an alternative solution

    Find the mean of all the points in the circle. This will then give you the center of the circle.

    var aggregate = points.Aggregate((point, result) => new Point{ X = point.X + result.X, Y = point.Y + result.Y });
    var center = new Point { X = aggregate.X / points.Count, Y = aggregate.Y / points.Count }; 
    

    This may be a more optimal solution because it could be done while you are scanning the image for the black pixels. Rather than finding the black pixels and then using LINQ.