0

i want to plot a STL file. I've allready got my Vertex's of the STL-File. The Aim is to get the faces of each triangulation which will done by

vtx=np.vstack((Vertex1[i],Vertex2[i],Vertex3[i]))

so you can see every n'th entry of Vertex1[n],Vertex2[n],Vertex3[n] belongs to the same face.

By

tri = a3d.art3d.Poly3DCollection([vtx])

we are getting a collection of 3D polygons and combine it with add_collection3d to plot all 3D polygons.

So now my Question is: Is there a way to do the Operation below without a for loop in the sense of making the code faster?

import numpy as np
import mpl_toolkits.mplot3d as a3d
import matplotlib.colors as colors
import matplotlib.pyplot as plt

Vertex1 = np.random.rand(9000,3)
Vertex2 = np.random.rand(9000,3)
Vertex3 = np.random.rand(9000,3)

ax = a3d.Axes3D(plt.figure())    

for i in range(Vertex1.shape[0]):
    vtx=np.vstack((Vertex1[i],Vertex2[i],Vertex3[i]))
    tri = a3d.art3d.Poly3DCollection([vtx])
    tri.set_color(colors.rgb2hex([0.9,0.6,0.]))
    tri.set_edgecolor('k')
    ax.add_collection3d(tri)
plt.show() 

Thanks!

Search898
  • 69
  • 6

1 Answers1

1

Instead of creating 9000 collections with one triangle in each, it is for sure more efficient to create one single collection with 9000 triangles in it.

import numpy as np
import mpl_toolkits.mplot3d as a3d
import matplotlib.colors as colors
import matplotlib.pyplot as plt

Vertex1 = np.random.rand(9000,3)
Vertex2 = np.random.rand(9000,3)
Vertex3 = np.random.rand(9000,3)

ax = a3d.Axes3D(plt.figure())    

v = np.stack((Vertex1,Vertex2,Vertex3),axis=2)

tri = a3d.art3d.Poly3DCollection(v)
tri.set_color(colors.rgb2hex([0.9,0.6,0.]))
tri.set_edgecolor('k')
ax.add_collection3d(tri)
plt.show() 
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Sure you're right. I've thought especially about the part with the loop: `for i in range(Vertex1.shape[0]): vtx=np.vstack((Vertex1[i],Vertex2[i],Vertex3[i])) v.append(vtx)` Is it in python possible to vectorize this for loop? – Search898 Dec 02 '17 at 20:11
  • Ok, I edited the answer. However, this may save you some 0.05 seconds, which is nothing compared to the draw time. And draw time is significantly reduced by using one single collection, instead of 9000 of them. So the main point of the answer still applies here. – ImportanceOfBeingErnest Dec 02 '17 at 20:24