Converting .nrrd file to .stl (using python)

Is there a way to convert .nrrd file to a .stl file on python?
The nrrd file is binary (every voxel has a value of either 0 or 255).

You should be able to do it using some kind of marching cubes filter

Hi Ron

I think the below script should work for this, but let me know if you have any questions on it.

import vtk
label = 255
nrrd_file_path = “”
output_stl_path = “”

reader = vtk.vtkNrrdReader()
img = read.GetOutput()

marching_cubes_filter = vtk.vtkDiscreteMarchingCubes()
marching_cubes_filter.SetValue(0, 255)
polydata = marching_cubes_filter.GetOutput()

writer = vtk.vtkSTLWriter()

If you want to see correctly reconstructed (smooth) surface then you can run these commands in Slicer’s Python environment:

segmentation = slicer.util.loadSegmentation("/path/to/labelmap.nrrd")
slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentsClosedSurfaceRepresentationToFiles("/path/to/folder", segmentation)

See more useful code snippets for loading, processing, saving data in the script repository.

Thanks for the suggestion. I referred this link to see how to use VTK to convert a file to stl format. I made the following changes to the code to suit my needs:

def get_program_parameters():
    parser.add_argument('filename', help='Trial.stl.')

def main():

The code, however, gives parsing error. I don’t understand the nature of this error:

Thanks for the suggestion. This was a very straightforward approach [changed read.GetOutput() to reader.GetOutput()]!
It created an STL file but the file is “malformed” and fails to open (the file size is 1KB).


What exactly is going wrong?

Thank you for the suggestion. Just as BrentFoster’s suggestion, the code is straightforward and doesn’t give any error while execution but no file is created. This is the output on the Python interface.

The output path must be a folder, not a filename, because this method exports all the segments of the segmentation, each as a separate file in the specified folder.

1 Like

@lassoan thanks for the reply!

To streamline the method I’m implementing is there a way to execute these commands on Spyder or Jupyter Notebook?

Yes, sure, you can use Slicer as a Jupyter Notebook kernel.

1 Like