204_Gradient.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # This file is part of libigl, a simple c++ geometry processing library.
  2. #
  3. # Copyright (C) 2017 Sebastian Koch <s.koch@tu-berlin.de> and Daniele Panozzo <daniele.panozzo@gmail.com>
  4. #
  5. # This Source Code Form is subject to the terms of the Mozilla Public License
  6. # v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. # obtain one at http://mozilla.org/MPL/2.0/.
  8. import sys, os
  9. # Add the igl library to the modules search path
  10. sys.path.insert(0, os.getcwd() + "/../")
  11. import pyigl as igl
  12. from shared import TUTORIAL_SHARED_PATH, check_dependencies
  13. dependencies = ["viewer"]
  14. check_dependencies(dependencies)
  15. V = igl.eigen.MatrixXd()
  16. F = igl.eigen.MatrixXi()
  17. # Load a mesh in OFF format
  18. igl.readOFF(TUTORIAL_SHARED_PATH + "cheburashka.off", V, F)
  19. # Read scalar function values from a file, U: #V by 1
  20. U = igl.eigen.MatrixXd()
  21. igl.readDMAT(TUTORIAL_SHARED_PATH + "cheburashka-scalar.dmat", U)
  22. U = U.col(0)
  23. # Compute gradient operator: #F*3 by #V
  24. G = igl.eigen.SparseMatrixd()
  25. igl.grad(V, F, G)
  26. # Compute gradient of U
  27. GU = (G * U).MapMatrix(F.rows(), 3)
  28. # Compute gradient magnitude
  29. GU_mag = GU.rowwiseNorm()
  30. viewer = igl.viewer.Viewer()
  31. viewer.data.set_mesh(V, F)
  32. # Compute pseudocolor for original function
  33. C = igl.eigen.MatrixXd()
  34. igl.jet(U, True, C)
  35. # Or for gradient magnitude
  36. # igl.jet(GU_mag,True,C)
  37. viewer.data.set_colors(C)
  38. # Average edge length divided by average gradient (for scaling)
  39. max_size = igl.avg_edge_length(V, F) / GU_mag.mean()
  40. # Draw a black segment in direction of gradient at face barycenters
  41. BC = igl.eigen.MatrixXd()
  42. igl.barycenter(V, F, BC)
  43. black = igl.eigen.MatrixXd([[0.0, 0.0, 0.0]])
  44. viewer.data.add_edges(BC, BC + max_size * GU, black)
  45. # Hide wireframe
  46. viewer.core.show_lines = False
  47. viewer.launch()