I am working with geospatial shapes and looking at the centroid algorithm here,
http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon
I have implemented the
For 3d Points, I created a method in C # I hope I can help you:
public static double[] GetCentroid(List<double[]> listOfPoints)
{
// centroid[0] = X
// centroid[1] = Y
// centroid[2] = Z
double[] centroid = new double[3];
// List iteration
// Link reference:
// https://en.wikipedia.org/wiki/Centroid
foreach (double[] point in listOfPoints)
{
centroid[0] += point[0];
centroid[1] += point[1];
centroid[2] += point[2];
}
centroid[0] /= listOfPoints.Count;
centroid[1] /= listOfPoints.Count;
centroid[2] /= listOfPoints.Count;
return centroid;
}
This answer is inspired by the answer by Jer2654 and this source: http://coding-experiments.blogspot.com/2009/09/xna-quest-for-centroid-of-polygon.html
/// <summary>
/// Method to compute the centroid of a polygon. This does NOT work for a complex polygon.
/// </summary>
/// <param name="poly">points that define the polygon</param>
/// <returns>centroid point, or PointF.Empty if something wrong</returns>
public static PointF GetCentroid(List<PointF> poly)
{
float accumulatedArea = 0.0f;
float centerX = 0.0f;
float centerY = 0.0f;
for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
{
float temp = poly[i].X * poly[j].Y - poly[j].X * poly[i].Y;
accumulatedArea += temp;
centerX += (poly[i].X + poly[j].X) * temp;
centerY += (poly[i].Y + poly[j].Y) * temp;
}
if (Math.Abs(accumulatedArea) < 1E-7f)
return PointF.Empty; // Avoid division by zero
accumulatedArea *= 3f;
return new PointF(centerX / accumulatedArea, centerY / accumulatedArea);
}
public static Point GetCentroid( Point[ ] nodes, int count )
{
int x = 0, y = 0, area = 0, k;
Point a, b = nodes[ count - 1 ];
for( int i = 0; i < count; i++ )
{
a = nodes[ i ];
k = a.Y * b.X - a.X * b.Y;
area += k;
x += ( a.X + b.X ) * k;
y += ( a.Y + b.Y ) * k;
b = a;
}
area *= 3;
return ( area == 0 ) ? Point.Empty : new Point( x /= area, y /= area );
}
You may check if .NET 4.5 DbSpatialServices functions, like DbSpatialServices.GetCentroid