How does slicer repair damaged surfaces when converting binary labelmap into closed surfaces?

I noticed that in Slicer, when converting a binary labelmap to a closed surface, it automatically repairs damaged surfaces, as shown in the right image.

Image

However, when I tried to use some VTK methods to convert a labelmap to a closed surface, I couldn’t achieve the same result. My code is as follows:

reader = vtk.vtkNIFTIImageReader()
reader.SetFileName(segmentation_file_path)
reader.Update()

desired_label = 1

threshold = vtk.vtkImageThreshold()
threshold.SetInputData(reader.GetOutput())

threshold.ThresholdBetween(desired_label, desired_label)
threshold.ReplaceInOn()
threshold.SetInValue(1)
threshold.ReplaceOutOn()
threshold.SetOutValue(0)

marching_cubes = vtk.vtkDiscreteFlyingEdges3D()
marching_cubes.SetInputConnection(threshold.GetOutputPort())
marching_cubes.SetValue(0, 1)

decimate_filter = vtk.vtkDecimatePro()
decimate_filter.SetInputConnection(marching_cubes.GetOutputPort())
decimate_filter.SetTargetReduction(0.3)

smooth_filter = vtk.vtkWindowedSincPolyDataFilter()
smooth_filter.SetInputConnection(decimate_filter.GetOutputPort())
smooth_filter.SetNumberOfIterations(15)
smooth_filter.BoundarySmoothingOff()
smooth_filter.FeatureEdgeSmoothingOff()
smooth_filter.SetFeatureAngle(120.01)
smooth_filter.SetPassBand(0.001)
smooth_filter.NonManifoldSmoothingOn()
smooth_filter.NormalizeCoordinatesOn()
smooth_filter.Update()

clean_filter = vtk.vtkCleanPolyData()
clean_filter.SetInputConnection(smooth_filter.GetOutputPort())
clean_filter.SetTolerance(0.0001)

stl_writer = vtk.vtkSTLWriter()
stl_writer.SetFileName(output_file_path)
stl_writer.SetInputConnection(clean_filter.GetOutputPort())
stl_writer.Write()

I want to know what methods I should use to repair the damaged surfaces in the left image of the illustration.


This is the picture mentioned.