fast_simpl.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """Use fast-simplification to decimate a mesh and transfer
  2. data defined on the original vertices to the decimated ones."""
  3. # https://github.com/pyvista/fast-simplification
  4. # pip install fast-simplification
  5. # Credits: Louis Pujol, see #992
  6. import numpy as np
  7. import fast_simplification as fs
  8. import vedo
  9. # Load a mesh and define a signal on vertices
  10. mesh = vedo.Sphere()
  11. points = mesh.vertices
  12. faces = mesh.cells
  13. signal = points[:, 0]
  14. mesh.pointdata["signal"] = signal
  15. mesh.cmap("rainbow").lw(1)
  16. # Decimate the mesh and compute the mapping between the original vertices
  17. # and the decimated ones with fast-simplification
  18. points_decim, faces_decim, collapses = fs.simplify(
  19. points, faces, target_reduction=0.9, return_collapses=True
  20. )
  21. points_decim, faces_decim, index_mapping = fs.replay_simplification(
  22. points, faces, collapses
  23. )
  24. # Compute the average of the signal on the decimated vertices (scatter operation)
  25. unique_values, counts = np.unique(index_mapping, return_counts=True)
  26. a = np.zeros(len(unique_values), dtype=signal.dtype)
  27. np.add.at(a, index_mapping, signal) # scatter addition
  28. a /= counts # divide by the counts of each vertex index to get the average
  29. # Create a new mesh with the decimated vertices and the averaged signal
  30. decimated_mesh = vedo.Mesh([points_decim, faces_decim])
  31. decimated_mesh.pointdata["signal"] = a
  32. decimated_mesh.cmap("rainbow").lw(1)
  33. vedo.show([[mesh, __doc__], decimated_mesh], N=2, axes=1).close()