Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate accurately the total number of vertices and faces in Wavefront .obj file in Python?

Dragging a 3D object as .obj file (Wavefront .obj file) to MeshLab or any other 3D graphics tells you the exact total number of faces and total number of vertices the model has. Vertices could be triangular or polygonal.

Is there any way to calculate accurately these 2 numbers programmatically? by reading the Obj file and outputting these numbers. Now some tools like MeshLab output a comment section in the obj file produced, saying how many faces, vertices etc... other tools don't do that.

I tried to count the number of 'v' and 'f' but that does not always give accurate results when compared to MeshLab results. What about vn and vt? sorry I am not that knowledgeable in obj file structure and what these letters really mean.

Any way of doing that in Python? It would be cool if there is a library that can do that and output also resolutions of textures used?

Thanks for any suggestions

like image 514
HB87 Avatar asked Oct 17 '25 14:10

HB87


2 Answers

This code shows the same numbers as Autodesk Maya

with open('test.obj') as f:
    lines = f.readlines()

vertices = len([line for line in lines if line.startswith('v ')])
faces = len([line for line in lines if line.startswith('f ')])
like image 174
ababak Avatar answered Oct 20 '25 03:10

ababak


There is a cool library called trimesh:

https://github.com/mikedh/trimesh

import trimesh
# load mesh
mesh = trimesh.load_mesh('path_to_mesh.obj')
print(mesh.vertices.shape)
print(mesh.faces.shape)
like image 43
user1863479 Avatar answered Oct 20 '25 03:10

user1863479



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!