Search code examples
pythonc++math3dmesh

How to compute the centroid of a mesh with triangular faces?


I want to compute a new centroid for my meshes given the following description. But I do not want to use Blender's built-in functions for computing centroids as explained here as it seems that they do not give me the kind of centroid I expect to get. First, I want to compute the centers of faces (triangle) of a mesh centroid of a mesh. Then I need to compute the faces area. The new centroid is the average of the mesh faces' centers, weighted by their area. How can I do this in Python (but not necessarily using Blender's Python API)?


Solution

  • let define each triangle with 3 vertexes p0,p1,p2 the center is easy

    center = (p0+p1+p2) /3
    

    it is just the average of all vertices which forms it. The area can be computed by cross product as:

    area = 0.5 * | (p1-p0) x (p2-p0) |
    area = 0.5 * length(cross( p1-p0, p2-p0 ))
    

    Both are the same just in different notation... So the centroid you are describing should be computed like this (in C++):

    float area_sum=0.0;
    vec3 centroid=vec3(0.0,0.0,0.0);
    for (int i=0;i<triangles;i++)
     {
     t = triangle[i];
     vec3  center = (t.p0+t.p1+t.p2) /3; 
     float area = 0.5 * length(cross(t.p1-t.p0, t.p2-t.p0));
     centroid += area*center;
     area_sum += area;
     }
    centroid /= area_sum;
    

    where triangle[trianges] is array of your faces where each face has p0,p1,p2 as 3D vectors. Sorry I do not use Python so you need to adapt the vector math to your style/environment. If you do not know how to compute cross product look here:

    vector math is at the bottom ...