4

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

HB87
  • 413
  • 7
  • 16
  • Regarding OBJ file format: https://en.wikipedia.org/wiki/Wavefront_.obj_file . `vn` are vertex normal coordinates, `vt` are vertex texture coordinates. – 0x5453 Jan 30 '18 at 16:17

2 Answers2

8

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 ')])
ababak
  • 1,685
  • 1
  • 11
  • 23
  • Amazing great. Also it gives the same numbers as in Meshlab. So If I understand correctly, v, vn and vt are all lines for vertices that should be counted also. Thanks for the clarification! – HB87 Jan 30 '18 at 16:27
  • 1
    No, vertices are represented only with "v", that's why I specify "v" followed by space in my code. "vt" is for texture coordinates and "vn" for normals. – ababak Jan 30 '18 at 16:33
  • Sorry I did not pay attention to the space. Thanks again – HB87 Jan 30 '18 at 16:34
2

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)