Skip to content

Instantly share code, notes, and snippets.

@MarilynKeller
Created February 4, 2024 15:31
Show Gist options
  • Save MarilynKeller/ef9c86ae45ffef793b2b67ed31361820 to your computer and use it in GitHub Desktop.
Save MarilynKeller/ef9c86ae45ffef793b2b67ed31361820 to your computer and use it in GitHub Desktop.
Python script to extract a submesh give an input mesh vertices and faces array and a list of vertices or faces to keep.
""" Python script to extract a submesh give an input mesh vertices and faces array and a list of vertices or faces to keep."""
def get_submesh(verts, faces, verts_retained=None, faces_retained=None, min_vert_in_face=2):
'''
Given a mesh, create a (smaller) submesh
indicate faces or verts to retain as indices or boolean
verts : Input mesh vertices (Nx3)
faces : Input mesh faces (Fx3)
verts_retained : list of the vertices indices to keep
@return new_verts: the new array of 3D vertices
new_faces: the new array of faces
bool_faces: the faces indices wrt the input mesh
vetex_ids: the vertex_ids wrt the input mesh
'''
if verts_retained is not None:
# Transform indices into bool array
if verts_retained.dtype != 'bool':
vert_mask = np.zeros(len(verts), dtype=bool)
vert_mask[verts_retained] = True
else:
vert_mask = verts_retained
# Faces with at least min_vert_in_face vertices
bool_faces = np.sum(vert_mask[faces.ravel()].reshape(-1, 3), axis=1) > min_vert_in_face
elif faces_retained is not None:
# Transform indices into bool array
if faces_retained.dtype != 'bool':
bool_faces = np.zeros(len(faces_retained), dtype=bool)
else:
bool_faces = faces_retained
new_faces = faces[bool_faces]
# just in case additional vertices are added
vertex_ids = np.where(vert_mask)[0]
oldtonew = -1 * np.ones([len(verts)])
oldtonew[vertex_ids] = range(0, len(vertex_ids))
new_verts = verts[vertex_ids]
new_faces = oldtonew[new_faces].astype('int32')
return (new_verts, new_faces, bool_faces, vertex_ids)
#Input
input_mesh = None #Load a trimesh mesh here
submesh_verts_indices = None # List of vertex indices to keep
new_verts, new_faces, bool_faces, vertex_ids = get_submesh(input_mesh.vertices, input_mesh.faces, verts_retained=submesh_verts_indices)
# Output
submesh = trimesh.Trimesh(vertices=new_verts, faces=new_faces, process=False, maintain_order=True)
# For each face of the submesh, gives its index in the original mesh (can be usefull)
submesh_global_faces_index = np.where(bool_faces)[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment