shortest.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from vedo import show
  2. import trimesh
  3. import networkx as nx
  4. # test on a sphere mesh
  5. mesh = trimesh.primitives.Sphere()
  6. # edges without duplication
  7. edges = mesh.edges_unique
  8. # the actual length of each unique edge
  9. length = mesh.edges_unique_length
  10. # create the graph with edge attributes for length
  11. g = nx.Graph()
  12. for edge, L in zip(edges, length):
  13. g.add_edge(*edge, length=L)
  14. # alternative method for weighted graph creation
  15. ga = nx.from_edgelist([(e[0], e[1], {"length": L}) for e, L in zip(edges, length)])
  16. # arbitrary indices of mesh.vertices to test with
  17. start = 0
  18. end = int(len(mesh.vertices) / 2.0)
  19. # run the shortest path query using length for edge weight
  20. path = nx.shortest_path(g, source=start, target=end, weight="length")
  21. ################################### VISUALIZE RESULT
  22. # make the sphere transparent-ish
  23. mesh.visual.face_colors = [150, 150, 180, 255]
  24. # Path3D with the path between the points
  25. path_visual = trimesh.load_path(mesh.vertices[path])
  26. # visualizable two points
  27. points_visual = trimesh.points.PointCloud(mesh.vertices[[start, end]])
  28. txt = 'Shortest path query\nusing length for edge weight'
  29. show(mesh, points_visual, path_visual, txt, axes=6).close()