python3dmeshtrimesh

mesh subset with trimesh


Is there a way to turn a subset of vertices and their associated faces into a mesh using trimesh? Is it as easy as getting the subset of vertices and faces, and then directly creating a mesh to then save out? Or would there be another step?

I already have code to find the subset of vertices and faces using trimesh, but I'm unsure about the creation of a new mesh part.

General pseudo code of what I'm thinking bellow.

#Load the mesh
mesh = load("cube.obj")

#Get the total vertices and faces
vertices = mesh.vertices
faces = mesh.faces

#Code to get sub set of vertices and associated faces
subVertices = vertSubsetGenerator(vertices)
subFaces = faceSubsetGenerator(vertices, faces)

#Create and save mesh
meshOut = createMesh(subVertices, subFaces)
save(meshOut)

Solution

  • What you're trying to do here is to return a subset of the original mesh (the term segmentation in your original title is a little bit misleading). Trimesh does indeed provide a built-in solution for this:

    import trimesh
    
    # Cube mesh 
    vertices = [
        [0., 0., 0.], [0., 0., 1.], [0., 1., 0.], [0., 1., 1.],
        [1., 0., 0.], [1., 0., 1.], [1., 1., 0.], [1., 1., 1.]
    ]
    faces = [
        [0, 6, 4], [0, 2, 6], [0, 3, 2], [0, 1, 3],
        [2, 7, 6], [2, 3, 7], [4, 6, 7], [4, 7, 5],
        [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 3]
    ]
    mesh = trimesh.Trimesh(vertices, faces)
    mesh.show()
    
    # Submesh
    subfaces = [2, 3]
    submesh = mesh.submesh([subfaces], append=True)
    submesh.show()
    
    

    As stated in the Trimesh documentation it requires the indices of the faces you wish to keep.

    Remember that your subVertices and subFaces are linked. If you "delete" a vertex you must also delete the faces that contain it (the opposite is not necessarily true). In other words, you have either to use subFaces or deduce the faces that contain your subVertices.

    Cheers!