1
$\begingroup$

I am trying to access the triangle count of an object with Python. All other python code displays itself when I hover my mouse over the corresponding button in the interface. When I go to the info bar and hover my mouse over the triangle count, nothing appears. When looking in the documentation around data, there doesn't appear to be any clear function to call to get this info.

$\endgroup$
2
$\begingroup$

You can access the polygons of a mesh, then calculate the triangles from the number of vertices per polygon.

import bpy

obj = bpy.context.scene.objects.active
data = obj.data

# FACES, TRIANGLES
total_triangles = 0

for face in data.polygons:
    vertices = face.vertices
    triangles = len(vertices) - 2
    total_triangles += triangles

print(total_triangles)

# VERTICES
vertices = []
for vertex in data.vertices:
    pos = [vertex.co[0], vertex.co[1], vertex.co[2]]
    vertices.append(pos)

print(vertices)

# EDGES
edges = []
for edge in data.edges:
    edges.append([edge.vertices[0], edge.vertices[1]])

print(edges)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Nice one. num_tris = sum(len(p.vertices) - 2 for p in me.polygons) is a quick one liner. $\endgroup$ – batFINGER Mar 8 '18 at 14:57
0
$\begingroup$

Scene statistics. Scene.statistics()

enter image description here

Call Scene.statistics() to get the text shown in the info bar.

Example of from python console, called before and after entering edit mode.

>>> C.scene.statistics()
'v2.79.1 | Verts:24 | Faces:18 | Tris:36 | Objects:3/3 | Lamps:0/0 | Mem:24.70M | Cube.003'

>>> C.scene.statistics()
'v2.79.1 | Verts:8/8 | Edges:12/12 | Faces:6/6 | Tris:12 | Mem:25.35M | Cube.003'

Use string methods to grep out the triangles. Tris:12.

Using Bmesh

The bmesh operator bmesh.ops.triangulate() can be called to, generate and then count the number of triangles.

import bpy
import bmesh

ob = bpy.context.object
me = ob.data

bm = bmesh.new()
bm.from_mesh(me)
stats = ["Faces: %d" % len(bm.faces), 
        "Verts: %d" % len(bm.verts), 
        "Edges: %d" % len(bm.edges)]

# triangulate 
bmesh.ops.triangulate(bm, faces=bm.faces[:])
stats.append("Tris: %d" % len(bm.faces))
print(" | ".join(stats))

#Faces: 6 | Verts: 8 | Edges: 12 | Tris: 12

Or using the method outlined in @doakey3's answer

num_tris = sum(len(f.verts) - 2 for f in bm.faces)

removes the need to run the operator.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.