Skip to content

Instantly share code, notes, and snippets.

@jterrace
Created November 3, 2011 19:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jterrace/1337531 to your computer and use it in GitHub Desktop.
Save jterrace/1337531 to your computer and use it in GitHub Desktop.
Removing duplicate triangles with numpy
import numpy as np
def remove_duplicates(array_data, return_index=False, return_inverse=False):
"""Removes duplicate rows of a multi-dimensional array. Returns the
array with the duplicates removed. If return_index is True, also
returns the indices of array_data that result in the unique array.
If return_inverse is True, also returns the indices of the unique
array that can be used to reconstruct array_data."""
unique_array_data, index_map, inverse_map = np.unique(
array_data.view([('', array_data.dtype)] * \
array_data.shape[1]), return_index=True,
return_inverse=True)
unique_array_data = unique_array_data.view(
array_data.dtype).reshape(-1, array_data.shape[1])
# unique returns as int64, so cast back
index_map = np.cast['uint32'](index_map)
inverse_map = np.cast['uint32'](inverse_map)
if return_index and return_inverse:
return unique_array_data, index_map, inverse_map
elif return_index:
return unique_array_data, index_map
elif return_inverse:
return unique_array_data, inverse_map
return unique_array_data
vert_indices = np.array([[0,1,2], [2,3,4], [5,6,7], [2,3,4], [1,3,5]])
normal_indices = np.array([[9,8,7], [6,5,4], [3,2,1], [10,11,12], [13,14,15]])
print 'Original indices:'
print vert_indices
print normal_indices
unique_vert_indices, index_map = remove_duplicates(vert_indices, return_index=True)
print
print 'After removing duplicates:'
print unique_vert_indices
print normal_indices[index_map]
@lordi
Copy link

lordi commented Nov 26, 2013

Thanks, also very helpful for unique'ing rows in a numpy array...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment