import pymesh from PIL import Image # Load the image file and convert to grayscale img = Image.open("heightfield.png").convert('L') # Clamp the width and height to a 5 inch square width, height = img.size max_dim = min(width, height, 500) img = img.resize((max_dim, max_dim)) # Create a mesh using PyMesh mesh = pymesh.form_mesh(np.zeros((max_dim * max_dim, 3)), np.zeros((0, 3))) # Set the vertex positions of the mesh based on the grayscale values for i in range(max_dim): for j in range(max_dim): index = i + j * max_dim gray_val = img.getpixel((i, j)) / 255.0 depth = gray_val * 0.2 vertex = [i / 254.0 * 5, j / 254.0 * 5, depth] mesh.vertices[index] = vertex # Generate the surface mesh using PyMesh mesh = pymesh.compute_outer_hull(mesh) # Save the mesh as an STL file pymesh.save_mesh("surface.stl", mesh)