一是采用vtkVoxelModeller
:
voxelModel = vtk.vtkVoxelModeller()
voxelModel.SetInputConnection(connect.GetOutputPort())
voxelModel.SetSampleDimensions(128, 128, 128)
voxelModel.SetScalarTypeToBit()
voxelModel.SetForegroundValue(1)
voxelModel.SetBackgroundValue(0)
voxelSurface = vtk.vtkContourFilter()
voxelSurface.SetInputConnection(voxelModel.GetOutputPort())
voxelSurface.SetValue(0, .999)
这种方法实验下来发现特别的慢。
另一种是采用vtkImagePolyDataToImageStencil
:
stl = reader.GetOutput()
bounds = stl.GetBounds()
spacing = [0.1, 0.1, 0.1]
whiteImage = vtk.vtkImageData()
whiteImage.SetSpacing(spacing)
# Set dim
dim = [math.ceil((bounds[i*2+1]-bounds[i*2])/spacing[i]) for i in range(3)]
print(dim)
whiteImage.SetDimensions(dim)
whiteImage.SetExtent(0, dim[0]-1, 0, dim[1]-1, 0, dim[2]-1)
# Set origin
origin = [bounds[i*2]+spacing[i]/2 for i in range(3)]
whiteImage.SetOrigin(origin)
whiteImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
# Fill the image with foreground voxels
inval = 1
outval = 0
whiteImage.GetPointData().GetScalars().Fill(inval)
# Polygonal data --> image stencil
pol2stenc = vtk.vtkPolyDataToImageStencil()
pol2stenc.SetInputData(stl)
pol2stenc.SetOutputOrigin(origin)
pol2stenc.SetOutputSpacing(spacing)
pol2stenc.SetOutputWholeExtent(whiteImage.GetExtent())
pol2stenc.Update()
# Cut the corresponding white image and set the background
imgstenc = vtk.vtkImageStencil()
imgstenc.SetInputData(whiteImage)
imgstenc.SetStencilConnection(pol2stenc.GetOutputPort())
imgstenc.ReverseStencilOff()
imgstenc.SetBackgroundValue(outval)
imgstenc.Update()
这种方法效率还不错,就是要控制一下它的边界,不然容易产生空洞。