TriangleMeshToBinaryImageFilter In Python

Hi, I’m trying to get a 3D binary image from a mesh stl file. I found an example in c++ using the TriangleMeshToBinaryImageFilter function. I was wondering if this function is available from the Python interface?

Hi Roger,

This patch adds Python wrapping for TriangleMeshToBinaryImageFilter:

Since you are interested in STL files, it is worth noting that Python packages for ITKIOMeshSTL were recently released. Install with:

python -m pip install itk-iomeshstl

Then, read a mesh file, e.g.:

import itk
MeshType = itk.Mesh[itk.F, 3]
reader = itk.MeshFileReader[MeshType].New()
meshIO = itk.STLMeshIO.New()
mesh = reader.GetOutput()

Hi Matt, thanks for thi addition! Could you please explain to me how can I install it? usually I would just use pip
python -m pip install --upgrade --pre itk
but I am not sure if I have to install from source?

Hi Roger,

This will be available in the upcoming ITK 5.0 Release Candidate 2 – in the meantime, if you have Linux, you could try the nightly Python package builds:

python -m pip install --upgrade pip numpy
python -m pip install itk --upgrade --no-index \

I used the above code, but get the error like Segmentation fault (core dumped).

Hi @buaaduke,

Thanks for the note.

We an issue we are resolving with remote module Python packages in ITK 5.0 RC 2 that causes this segmentation fault. We aim to have these resolved with the 5.0.0 release.

The itk-iomeshstl package will encounter this issue, but the itk.TriangleMeshToBinaryImageFilter should be available in the 5.0 RC 2 packages. It is possible to write the result with one of the other mesh file formats supported by ITK in the meantime.

CC: @fbudin

Hi @matt.mccormick,

Thank you for your reply. I also tried to use ITKIOMeshOBJ to load the mesh file (.obj), code as follows,

import itk
meshType = itk.Mesh[itk.F, 3]
meshReader = itk.MeshFileReader[meshType].New()
meshIO = itk.OBJMeshIO.New()

but got error like ‘Bus error (core dumped)’. I used itk-5.0rc2.

@buaaduke thanks for the follow-up - this issue was created to track progress on the updated reading.

@buaaduke: I tried to reproduce your error using ITK Python v5.0rc2 and it actually worked on my machine with the model that I provided. Would you be able to share the model that you used that creates the error?

ok, see the attachment.
bunny.obj (386.3 KB)

1 Like

I was able to reproduce the error on my machine. Thanks for sharing the data.

For some reason this objfile has more vertex normals (4968) than vertices (2503) which makes ITK crash. I fixed ITK so it does not crash, but I don’t know what the correct behavior should be: Error message, ignore,… My Work-In-Progress pull request is here.

Is the number of vertex normals equal to number of faces, or triple number of faces?