Create TIFF stack from an stl file


I want to create a stack of TIFF images from an stl file and have tried the code provided in the post below however I can’t get this to work as I keep getting error “[VTK] No input data”. Can you please help with this?

I couldn’t find a way to upload the stl file

inputModelFile = r"C:\Work\Temp\Body1.stl"
outputDir = r"C:\Work\Temp\Slicer"
outputVolumeLabelValue = 255
inPlaneResolutionDpi = 200
planeThicknessMm = 1
outputVolumeMarginMm = [0, 0, 0] # mm of buffer before/after and around

import math
import numpy as np
import sys
    import imageio
except ImportError:

imageSpacingMm = [25.4/inPlaneResolutionDpi, 25.4/inPlaneResolutionDpi, planeThicknessMm]
inputModel = slicer.util.loadModel(inputModelFile)
bounds = np.zeros(6)
imageSize = [ int((math.ceil(bounds[axis*2+1] - bounds[axis*2] + 2 * outputVolumeMarginMm[axis]))/imageSpacingMm[axis]) for axis in range(3) ]
imageOrigin = [ bounds[axis*2] - outputVolumeMarginMm[axis] for axis in range(3) ]
sliceImageData = vtk.vtkImageData()
sliceImageData.SetDimensions(imageSize[0], imageSize[1], 1)
sliceImageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
sliceNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLLabelMapVolumeNode")
seg = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLSegmentationNode')
# restrict rasterization to the reference geometry (single frame at a time)
seg.GetSegmentation().SetConversionParameter("Crop to reference image geometry", "1")
seg.GetSegmentation().SetMasterRepresentationName("Closed surface")
slicer.modules.segmentations.logic().ImportModelToSegmentationNode(inputModel, seg)
segmentId = seg.GetSegmentation().GetNthSegmentID(0)

for sliceIndex in range(imageSize[2]):
    sliceNode.SetOrigin(imageOrigin[0], imageOrigin[1], imageOrigin[2] + sliceIndex * imageSpacingMm[2])
    seg.GetSegmentation().CreateRepresentation('Binary labelmap', True)  # Force recreating binary labelmap representation immediately
    outputSliceImageArray = np.squeeze(slicer.util.arrayFromSegmentBinaryLabelmap(seg, segmentId))
    outputSliceImageArray[outputSliceImageArray>0] = outputVolumeLabelValue
    filename = f'{outputDir}/slice_{sliceIndex:03}.tif'
    result = imageio.imwrite(filename, outputSliceImageArray)
    print(filename)  # update console

I have attached the file here.

I’ve tried and the script works well on your data.

You can ignore the [VTK] No input data message, it is just logged when a slice view does not intersect the segmentation node and so there is nothing to show. We’ll suppress this message to not confuse users.