pythonopenscadstl-format

How to extract vertices and faces from a STL file


I am trying to create an STL rendering application in python. I have achieved the actual rendering, but I need to pass it the vertices and faces in OpenSCAD polyhedron format. This means I need a list of all the vertices in the object, and another list where all the list entries are lists that contain the indexes (from the first list) of the vertices, in clockwise order around the face, looking from outside. For example, a cube would be:

vertices = [
[-1, -1, 1],
[1, -1, 1],
[1, 1, 1],
[-1, 1, 1],
[-1, -1, -1],
[1, -1, -1],
[1, 1, -1],
[-1, 1, -1]
] 
faces = [
[0, 1, 2, 3],
[4, 5, 6, 7],
[1, 2, 6, 5],
[0, 3, 7, 4],
[0, 1, 5, 4],
[2, 3, 7, 6]
]

I've tried this answer but I don't want to use OpenGL. I also can't just manually use a STL to OpenScad converter because I would like to be able to just type in the file location and it renders it. How can I do this?


Solution

  • You can use numpy with stl to create a function to return the vertices and faces. First run pip install numpy-stl then use the following code

    import numpy
    import stl
    
    def parse_stl(stl_file):
    
        # Load the STL file
        mesh_data = stl.mesh.Mesh.from_file(stl_file)
    
        # Extract vertices and faces
        vertices = mesh_data.vectors.reshape((-1, 3))
        faces = np.arange(len(vertices)).reshape((-1, 3))
    
        return vertices, faces