204_Gradient.py 1.8 KB

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