Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i extrude a stl with python

I am trying to convert png images to 3d stls. I finally found a way to do that. But there is a problem. Now the exported image has no z value no thickness. The way I am doing it is for the white pixels on the image I draw triangles to a surface.

def define_faces(numpy_array, column_number, row_number, z_value):
    print("Vertices Initializing.")
    vertices = np.zeros((row_number , column_number , 3))
    for x in range(0, column_number):
        for y in range(0, row_number):
            z = z_value
            vertices[y][x] = (x,y,z)
    print("Vertices Initialized")
    faces = []
    print("Initializing Faces.")
    for x in range(0, column_number - 1):
        for y in range(0, row_number - 1):
            if numpy_array[y][x] >= PIXEL_COLOR_FILTER:
                vertice1 = vertices[y][x]
                vertice2 = vertices[y+1][x]
                vertice3 = vertices[y+1][x+1]
                face1 = np.array([vertice1, vertice2, vertice3])

                vertice1 = vertices[y][x]
                vertice2 = vertices[y][x+1]
                vertice3 = vertices[y+1][x+1]
                face2 = np.array([vertice1,vertice2,vertice3])
                faces.append(face1)
                faces.append(face2)
    print("Faces Initialized")
    return np.array(faces) , faces

and

def create_mesh(faces_numpy, faces, output_name):
    print("Creating Mesh.")
    surface = mesh.Mesh(np.zeros(faces_numpy.shape[0], dtype = mesh.Mesh.dtype))
    for i ,f in enumerate(faces):
        for j in range(3):
            surface.vectors[i][j] = faces_numpy[i][j]
            
    surface.save(output_name)
    print("Mesh created succesfully.")

These are the core functions of this code. Code is originally for Lithophane generation. I have an idea on instead of giving triangles and making them an stl, directly generating cubes on intended pixels. so it becomes 3d. But before that any ideas on how to extrude the final stl?

This is the png:

This is the png

This is the stl:

This is the stl


1 Answers

You can use open source library MeshLib with python bindings to solve your task.

Then the code for extrusion is as follows:

import meshlib.mrmeshpy as mr
# load image as Distance Map object:
dm = mr.loadDistanceMapFromImage(mr.Path("your-image.png"), 0)
# find boundary contour of the letter:
polyline2 = mr.distanceMapTo2DIsoPolyline(dm, isoValue=127)
# triangulate the contour
mesh = mr.triangulateContours(polyline2.contours2())
# extrude itself:
mr.addBaseToPlanarMesh(mesh, zOffset=30)
# export the result:
mr.saveMesh(mesh, mr.Path("output-mesh.stl"))

The result will look as enter image description here

like image 73
Fedor Avatar answered Apr 24 '26 09:04

Fedor