204_Gradient.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import sys, os
  2. # Add the igl library to the modules search path
  3. sys.path.insert(0, os.getcwd() + "/../")
  4. import pyigl as igl
  5. from shared import TUTORIAL_SHARED_PATH, check_dependencies
  6. dependencies = ["viewer"]
  7. check_dependencies(dependencies)
  8. V = igl.eigen.MatrixXd()
  9. F = igl.eigen.MatrixXi()
  10. # Load a mesh in OFF format
  11. igl.readOFF(TUTORIAL_SHARED_PATH + "cheburashka.off", V, F)
  12. # Read scalar function values from a file, U: #V by 1
  13. U = igl.eigen.MatrixXd()
  14. igl.readDMAT(TUTORIAL_SHARED_PATH + "cheburashka-scalar.dmat", U)
  15. U = U.col(0)
  16. # Compute gradient operator: #F*3 by #V
  17. G = igl.eigen.SparseMatrixd()
  18. igl.grad(V, F, G)
  19. # Compute gradient of U
  20. GU = (G * U).MapMatrix(F.rows(), 3)
  21. # Compute gradient magnitude
  22. GU_mag = GU.rowwiseNorm()
  23. viewer = igl.viewer.Viewer()
  24. viewer.data.set_mesh(V, F)
  25. # Compute pseudocolor for original function
  26. C = igl.eigen.MatrixXd()
  27. igl.jet(U, True, C)
  28. # Or for gradient magnitude
  29. # igl.jet(GU_mag,True,C)
  30. viewer.data.set_colors(C)
  31. # Average edge length divided by average gradient (for scaling)
  32. max_size = igl.avg_edge_length(V, F) / GU_mag.mean()
  33. # Draw a black segment in direction of gradient at face barycenters
  34. BC = igl.eigen.MatrixXd()
  35. igl.barycenter(V, F, BC)
  36. black = igl.eigen.MatrixXd([[0.0, 0.0, 0.0]])
  37. viewer.data.add_edges(BC, BC + max_size * GU, black)
  38. # Hide wireframe
  39. viewer.core.show_lines = False
  40. viewer.launch()