Skip to content

Instantly share code, notes, and snippets.

@thomasweng15
Last active September 26, 2023 23:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasweng15/a46f7c92c88f92b9e0424953495ce9cb to your computer and use it in GitHub Desktop.
Save thomasweng15/a46f7c92c88f92b9e0424953495ce9cb to your computer and use it in GitHub Desktop.
3D Interactive Visualizations with Plotly
# Save html to the specified path
fig.write_html("plotly_sphere_pts.html")
# Save to wandb (call wandb.init() first)
# html = plotly.io.to_html(fig)
# wandb.log(
# {
# f"plotly_sphere_pts": wandb.Html(html),
# }
# )
import trimesh
import numpy as np
import plotly.graph_objects as go
import plotly.figure_factory as ff
# Make a mesh sphere
mesh = trimesh.primitives.Sphere(radius=1, center=(0, 0, 0))
x, z, y = mesh.vertices.T
# Plot mesh
fig = ff.create_trisurf(
x=x,
y=y,
z=z,
simplices=mesh.faces,
aspectratio={"x": 1.0, "y": 1.0, "z": 1.0},
show_colorbar=False,
title="",
height=500, # in pixels
width=500 # in pixels
)
fig.update_layout(
margin=dict(
l=5,
r=5,
b=5,
t=5,
)
)
fig.show() # Render result in the browser
# Add point cloud to figure
pts = np.random.uniform(low=-1, high=1, size=(100, 3))
fig.add_trace(
go.Scatter3d(
x=pts[:, 0],
y=pts[:, 2],
z=pts[:, 1],
mode="markers",
marker=dict(size=3, color="blue", opacity=0.8),
)
)
fig.show() # Show the result in the browser
@WangYixuan12
Copy link

WangYixuan12 commented Sep 26, 2023

Hi Thomas, thanks a lot for sharing! This is exactly what I am looking for! I optimized it a bit so that it could visualize any trimesh mesh. I would love to share it here in case it might be helpful.

def vis_mesh_plotly(mesh, save_name, up=None, center=None, eye=None):
    x, z, y = mesh.vertices.T
    i, j, k = mesh.faces.T
    facecolors = mesh.visual.face_colors # RGBA in uint8

    # Plot mesh
    go_mesh = go.Figure(data=[go.Mesh3d(x=x,
                                        y=y,
                                        z=z,
                                        i=i,
                                        j=j,
                                        k=k,
                                        facecolor=facecolors[:, :3])],
                        layout=go.Layout(scene=dict(aspectmode='data'),))
    
    if up is not None:
        camera = dict(
            up=dict(x=up[0], y=up[1], z=up[2]),
            center=dict(x=center[0], y=center[1], z=center[2]),
            eye=dict(x=eye[0], y=eye[1], z=eye[2])
        )

        go_mesh.update_layout(scene_camera=camera)
    
    go_mesh.show()
    
    go_mesh.write_html(save_name)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment