BLOG.CSHARPHELPER.COM: Find a Region's centroid in C#
Find a Region's centroid in C#
The example Find the area where two or more circles overlap in C# shows how to find a Region representing the area where two or more circles overlap. This example shows how to find the centroid of that Region to get a point that is in the "center" of the Region.
The Region object's GetRegionData method returns information about the Region's shape. Unfortunately this data comes as an array of bytes and it's not obvious what to do with it.
The Region object's GetRegionScans method, however, returns an array of rectangles representing the region, and rectangles are much easier to understand.
This example uses the RegionCentroid method shown in the following code to find the centroid of a Region by using its scan rectangles.
// Return the centroid of the region. private PointF RegionCentroid(Region region, Matrix transform) { float mx = 0; float my = 0; float total_weight = 0; foreach (RectangleF rect in region.GetRegionScans(transform)) { float rect_weight = rect.Width * rect.Height; mx += rect_weight * (rect.Left + rect.Width / 2f); my += rect_weight * (rect.Top + rect.Height / 2f); total_weight += rect_weight; }
return new PointF(mx / total_weight, my / total_weight); }
The code initializes moment values mx and my, and the region's total weight. It then loops through the rectangles, adding the moments of each to mx and my, and adding the rectangle's weight to the total. When it finishes, the code divides the moments by the total weight to get the centroid's coordinates.
Comments