Extracting triangles from Mesh3d figure

Hello all,

This is my first time using the mesh3d and I had a quick question regarding the actual triangles involved in creating the figure. I am working on financial modeling and have a set of x,y,z coordinates in a text file and have created a surface. This part is fine, but I need to be able to see the coordinates of the triangles that are within the mesh. Any ideas? My code is below. Thank you very much for your help.

import plotly.graph_objects as go
import numpy as np

lines = open("data.txt", "r").readlines()
x = []
y = []
z = []

for line in lines:
    if "%" in line:
        z.append(float(line[:-2]))
    elif "." in line:
        x.append(float(line[:-1]))
    else:
        y.append(float(line[:-1]))

fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, color='green', opacity=0.50)])
fig.show()

Hi @mathguy350,

Welcome to forum!
Using this Mesh3d version you cannot extract the triangle vertex coordinates.
In order to get them, project the points of coordinates (x,y,z) onto a 2d plane of equation z=cst. Then triangulate the resulting 2d points, using scipy.spatial.Delaunay, and lift the planar triangulation, back to 3d.
From the 3d points and triangulation faces you can get the coordinates of each triangle vertices.
Example:

from scipy.spatial import Delaunay
import numpy as np
import plotly.graph_objects as go

pts3d = np.vstack((x, y, z)).T
pts2d = pts3d[:, :2]
tri =   Delaunay(pts2d)
i, j, k = tri.simplices.T  #tri.simplices (faces) is an array of integers of shape (no_triangles, 3)
fig = go.Figure(go.Mesh3d(x=x, y=y, z=z,
                          i=i, j=j, k=k, intensity=z, 
                          colorscale='matter_r', 
                          flatshading=True))

The coordinates of triangle vertices are then computed as follows:

tri_coords = pts3d[tri.simplices]

tri_coords[m] (m =0, 1, … number of triangles-1) is an array of shape (3,3)_. Each row contains the coordinates of a triangle vertex.

1 Like

@empet,

Thank you so much for your answer. This has resolved my issue.

Thanks again.