Amir
Amir

Reputation: 11096

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)?

Upvotes: 5

Views: 6743

Answers (2)

Sirius 5
Sirius 5

Reputation: 133

Note that Spektre's answer gives the centroid of the surface area of the mesh, which might be what you want.

If you want the center of the mesh volume instead (like a center of mass assuming constant density), you would need to do the following:

  1. Create a tetrahedron from each triangle using the 3 vertices of the triangle plus the origin point.
  2. Calculate the signed volume and center for each tetrahedron
  3. Total up the volumes and the volume-weighted centers
  4. Get the mesh center by dividing the sum of the volume-weighted centers by the total volume

Pseudocode:

meshVolume = 0
temp = (0,0,0)

for each triangle in mesh (with vertices v1, v2, v3)
  center = (v1 + v2 + v3) / 4          // center of tetrahedron
  volume = dot(v1, cross(v2, v3)) / 6  // signed volume of tetrahedron
  meshVolume += volume
  temp += center * volume

meshCenter = temp / totalVolume

Upvotes: 7

Spektre
Spektre

Reputation: 51845

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 ...

Upvotes: 5

Related Questions