204_Gradient.py 1.2 KB

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