linello
linello

Reputation: 8704

Selecting faces of a mesh based on vertices coordinates in numpy

I have two numpy arrays, one is for 3D vertices of a mesh, call it vert and one is for the triangular faces, call it faces:

The vert array is a N x 3 shape array of float, hence N three dimensional points. The x coordinate of each point can have both positive and negative values. As a pure example this can be the vert array:

[[  2.886495  24.886948  15.909558]
 [ -13.916695 -58.985245  19.655312]
 [ 40.415527   8.968353   8.515955]
 ...
 [ 13.392465 -58.20602   18.752457]
 [ -12.504704 -58.307934  18.912386]
 [ 13.322185 -58.52817   19.165733]]

Since the mesh is centered, the left part of the mesh is the one with positive x component and the corresponding vertex indices are found by a np.where

i_vert_left = np.where(vert[:,0]>0)[0]

I now would like to filter out those faces made of triangles with coordinates entirely in the positive x axis.

However I have a problem in doing this indexing operation correctly. My first attempt was to subset the faces such that their corresponding vertices have x>0

faces_left = np.asarray([f for f in faces if np.all(np.isin(i_vert_left,f)) ])

but the operation is incredibly slow on large meshes. How can I exploit a smart indexing of the faces?

Upvotes: 2

Views: 1172

Answers (1)

javidcf
javidcf

Reputation: 59701

Assuming faces is a Nx3 array of integers indexing the three vertices of each triangle, I think you should just need:

# Check whether each vertex is left or not
vert_left_mask = vert[:, 0] > 0
# Check whether each face has all vertices on left or not
faces_left_mask = np.all(vert_left_mask[faces], axis=1)
# Select resulting left faces
faces_left = faces[faces_left_mask]

The main "trick" here is in vert_left_mask[faces], which replaces each integer vertex number with a boolean indicating whether the vertex is left or not, so it's easy to tell which face is fully left with np.all.

Upvotes: 2

Related Questions