How to extract vertex , face from .stl file

1.8k Views Asked by At

I'm currently working on a project which use PyQt5 to be able to display 3D object using opengl.GLViewWiget

I have already download a .stl file and a base of PyQt5 module

self.Widget3D = opengl.GLViewWidget(self.centralwidget)
self.Widget3D.setGeometry(QtCore.QRect(1000, 100, 351, 271))
self.Widget3D.setObjectName("Widget3D")

I have a problem with .STL file I have install numpy-stl and read through its document but haven't really find a way to extract it and use with GLMeshItem as far as I find is this example code

#Extract vertex points and face faces from the STL file.
points, faces = self.loadSTL(filename)

meshdata = gl.MeshData(vertexes=points, faces=faces)
mesh = gl.GLMeshItem(meshdata=meshdata, smooth=True, drawFaces=False, drawEdges=True, edgeColor=(0, 1, 0, 1))
self.viewer.addItem(mesh)

The self.loadSTL part is unclear for me for how to really use the numpy-stl in this code

1

There are 1 best solutions below

0
On

Here's some code that should allow you to create the GLMeshItem from an stl file. This isn't exactly what you're asking, since I'm not extracting the vertices and faces from the stl. But you don't actually need to do that; the GLMeshItem constructor can take a Nx3x3 array of vertices (where each of N triangular faces is specified by three len-3 arrays), and this is exactly what numpy-stl gives you when you load an stl from file.

import numpy as np
import stl

my_mesh =  stl.mesh.Mesh.from_file('my_stl_file.stl')
face_clr = np.array([[[1.0, 0.0, 0.0, 0.5]] * 3] * np.shape(my_mesh.vectors)[0])
mesh_item = gl.GLMeshItem(vertexes=my_mesh.vectors,  # Nx3x3
                          faceColors=face_clr,  # Nx3x4
                          drawEdges=True,
                          smooth=False)

If you did want to extract the vertices and faces separately, I believe you'd just have to do some manual manipulation of my_mesh.vectors. Ie, find all unique vectors in my_mesh.vectors, and figure out which faces include which unique vectors.