Convert stl 2 numpy, volume data

Question:

Is there a way to convert a stl file to a numpy array?
The numpy array, resolved with x*y*z datapoints should contain volumetric information in the sense of “inside” or “outside” the geometry, say as 0 or 1.

To my surprise I didn’t find anything on this yet, although numpy2stl seems to be quite popular.

The problem is a complex geometry of porous media, so convex hull conversion does not work either.

import numpy
import stl
from stl import mesh
stl.stl.MAX_COUNT = 1e10
your_mesh = stl.mesh.Mesh.from_file('Data.stl')
print your_mesh.data

seems to be able to export triangles only.

In addition, even this usually leads to MemoryError messages; but numpy-stl (usually) works for loading the datapoints into numpy.

Is there a way to convert the stl data into volume data that contains information if every point is inside or outside the geometry?
The resulting 3D array could technically be of binary data type, but this isn’t required.
overcomplicated
With commercial software this conversion seems to be trivial, but it’s not python or free. Implementing a ray casting algorithm from scratch seems over complicated for file type conversion.

Asked By: DennisH

||

Answers:

I do believe that what you want to do is a voxelization of your volume. You can do that with the trimesh package at https://trimsh.org/

import trimesh
mesh = trimesh.load_mesh('path2yourstlfile.stl')
assert(mesh.is_watertight) # you cannot build a solid if your volume is not tight
volume = mesh.voxelized(pitch=0.1)
mat = volume.matrix # matrix of boolean

You can also check if a list of point are inside the volume using:

mesh.contains(points)
Answered By: nperraud

Small typo in [4], trimesh has no matrix atribute, you get it from VoxelGrid.

mat = mesh.matrix

fixed

mat = volume.matrix 
Answered By: jack95
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.