def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        smoothingFilter = None

        if self.Method is 'taubin':
            smoothingFilter = vtk.vtkWindowedSincPolyDataFilter()
            smoothingFilter.SetInput(self.Surface)
            smoothingFilter.SetNumberOfIterations(self.NumberOfIterations)
            smoothingFilter.SetPassBand(self.PassBand)
            smoothingFilter.SetBoundarySmoothing(self.BoundarySmoothing)
##            smoothingFilter.NormalizeCoordinatesOn()
            smoothingFilter.Update()
        elif self.Method is 'laplace':
            smoothingFilter = vtk.vtkSmoothPolyDataFilter()
            smoothingFilter.SetInput(self.Surface)
            smoothingFilter.SetNumberOfIterations(self.NumberOfIterations)
            smoothingFilter.SetRelaxationFactor(self.RelaxationFactor)
            smoothingFilter.Update()
        else:
            self.PrintError('Error: smoothing method not supported.')

        self.Surface = smoothingFilter.GetOutput()

        normals = vmtkscripts.vmtkSurfaceNormals()
        normals.Surface = self.Surface
        normals.Execute()

        self.Surface = normals.Surface

        if self.Surface.GetSource():
            self.Surface.GetSource().UnRegisterAllOutputs()
    def update_mask(self, src):

        # Filter
        cast_filter = vtk.vtkImageCast()
        cast_filter.SetOutputScalarTypeToUnsignedInt()
        cast_filter.SetInputData(src)
        cast_filter.Update()

        # Create mesh using marching cube
        march = vtk.vtkDiscreteMarchingCubes()
        march.ComputeNormalsOn()
        march.ComputeGradientsOn()
        for i, organ in enumerate(Settings.organs):
            march.SetValue(i, Settings.labels[organ]['value'])
        march.SetInputData(cast_filter.GetOutput())
        march.Update()

        # Filtrate the masks
        smooth = vtk.vtkWindowedSincPolyDataFilter()
        smooth.SetInputConnection(march.GetOutputPort())
        smooth.SetNumberOfIterations(15)
        smooth.BoundarySmoothingOff()
        smooth.FeatureEdgeSmoothingOff()
        smooth.SetFeatureAngle(120.0)
        smooth.SetPassBand(.001)
        smooth.NonManifoldSmoothingOn()
        smooth.NormalizeCoordinatesOn()
        smooth.Update()

        self.surface_mapper.SetInputConnection(smooth.GetOutputPort())
Beispiel #3
0
def smoothMesh(mesh, nIterations=10):
    """Smooth a mesh using VTK's WindowedSincPolyData filter."""
    try:
        t = time.perf_counter()
        smooth = vtk.vtkWindowedSincPolyDataFilter()
        smooth.SetNumberOfIterations(nIterations)
        if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
            smooth.SetInputData(mesh)
        else:
            smooth.SetInput(mesh)
        smooth.Update()
        print("Surface smoothed")
        m2 = smooth.GetOutput()
        print("    ", m2.GetNumberOfPolys(), "polygons")
        elapsedTime(t)
        smooth = None
        return m2
    except:
        print("Surface smoothing failed")
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exception(exc_type,
                                  exc_value,
                                  exc_traceback,
                                  limit=2,
                                  file=sys.stdout)
    return None
def run(neuron_num):
    file = "meshes-with-axons-filled-assembled/n%02d.vtp" % neuron_num

    readerVolume = vtk.vtkXMLPolyDataReader()
    readerVolume.SetFileName(file)
    readerVolume.Update()

    decimate = readerVolume
    nlod = 5

    for i in range(nlod):
        smoother = vtk.vtkWindowedSincPolyDataFilter()
        smoother.SetInputConnection(decimate.GetOutputPort())
        smoother.SetNumberOfIterations(20)  # This has little effect on the error!
        smoother.BoundarySmoothingOff()
        smoother.FeatureEdgeSmoothingOff()
        smoother.SetPassBand(.1)        # This increases the error a lot! .001
        smoother.NonManifoldSmoothingOn()
        smoother.NormalizeCoordinatesOn()
        smoother.GenerateErrorScalarsOn()
        smoother.Update()

        decimate = vtk.vtkQuadricDecimation ()
        decimate.SetInputData(smoother.GetOutput())
        decimate.SetTargetReduction(.7)
        decimate.Update()


        full_out_name = 'meshes-with-axons-filled-assembled-lod/n%02d_LOD%d.obj' % (neuron_num, i - 1)
        writer = vtk.vtkOBJWriter()
        writer.SetFileName(full_out_name)
        writer.SetInputData(decimate.GetOutput())
        writer.Write()
Beispiel #5
0
def windowed_sinc_smooth_vtk_polydata(poly,
                                      iteration=15,
                                      band=0.1,
                                      boundary=False,
                                      feature=False):
    """
    This function smooths a vtk polydata, using windowed sinc algorithm

    Args:
        poly: vtk polydata to smooth
        boundary: boundary smooth bool

    Returns:
        smoothed vtk polydata
    """
    ftr = vtk.vtkWindowedSincPolyDataFilter()
    ftr.SetInputData(poly)
    ftr.SetNumberOfIterations(iteration)
    ftr.SetPassBand(band)
    ftr.SetBoundarySmoothing(boundary)
    ftr.SetFeatureEdgeSmoothing(feature)
    ftr.NonManifoldSmoothingOn()
    ftr.NormalizeCoordinatesOn()
    ftr.Update()
    return ftr.GetOutput()
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        smoothingFilter = None

        if self.Method is 'taubin':
            smoothingFilter = vtk.vtkWindowedSincPolyDataFilter()
            smoothingFilter.SetInputData(self.Surface)
            smoothingFilter.SetNumberOfIterations(self.NumberOfIterations)
            smoothingFilter.SetPassBand(self.PassBand)
            smoothingFilter.SetBoundarySmoothing(self.BoundarySmoothing)
            smoothingFilter.SetNormalizeCoordinates(self.NormalizeCoordinates)
            smoothingFilter.Update()
        elif self.Method is 'laplace':
            smoothingFilter = vtk.vtkSmoothPolyDataFilter()
            smoothingFilter.SetInputData(self.Surface)
            smoothingFilter.SetNumberOfIterations(self.NumberOfIterations)
            smoothingFilter.SetRelaxationFactor(self.RelaxationFactor)
            smoothingFilter.Update()
        else:
            self.PrintError('Error: smoothing method not supported.')

        self.Surface = smoothingFilter.GetOutput()

        normals = vmtkscripts.vmtkSurfaceNormals()
        normals.Surface = self.Surface
        normals.Execute()

        self.Surface = normals.Surface
Beispiel #7
0
def smooth_surface(vtk_path, output_path):
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(vtk_path)
    reader.Update()

    if (reader.GetOutput().GetNumberOfPoints() == 0):
        print('WARNING: nothing to smooth for', vtk_path)
        return 
    
    smoothingIterations = 50
    passBand = 0.05
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(reader.GetOutputPort())
    smoother.SetNumberOfIterations(smoothingIterations)
    smoother.SetPassBand(passBand)
    smoother.Update()

    decimate = vtk.vtkDecimatePro()
    decimate.SetInputData(smoother.GetOutput())
    decimate.SetTargetReduction(0.8)
    decimate.PreserveTopologyOn()
    decimate.Update()


    writer = vtk.vtkSTLWriter()
    writer.SetInputData(decimate.GetOutput())
    writer.SetFileTypeToASCII()  
    writer.SetFileName(output_path)  # .stl
    writer.Update()
def simplify_polydata(polydata, num_simplify_iter=0, smooth=False):
    for simplify_iter in range(num_simplify_iter):

        t = time.time()

        deci = vtk.vtkQuadricDecimation()
        deci.SetInputData(polydata)

        deci.SetTargetReduction(0.8)
        # 0.8 means each iteration causes the point number to drop to 20% the original

        deci.Update()

        polydata = deci.GetOutput()

        if smooth:

            smoother = vtk.vtkWindowedSincPolyDataFilter()
            #         smoother.NormalizeCoordinatesOn()
            smoother.SetPassBand(.1)
            smoother.SetNumberOfIterations(20)
            smoother.SetInputData(polydata)
            smoother.Update()

            polydata = smoother.GetOutput()

        n_pts = polydata.GetNumberOfPoints()

        if polydata.GetNumberOfPoints() < 200:
            break

        sys.stderr.write('simplify %d @ %d: %.2f seconds\n' %
                         (simplify_iter, n_pts, time.time() - t))  #

    return polydata
def create_mesh(label_pix, labels_to_use, inds_to_phys=None):
    # convert the numpy representation to VTK, so we can create a mesh
    # using marching cubes for display later
    vtk_import = vtkImageImport()
    vtk_import.SetImportVoidPointer(label_pix, True)
    vtk_import.SetDataScalarType(VTK_UNSIGNED_CHAR)
    vtk_import.SetNumberOfScalarComponents(1)

    vtk_import.SetDataExtent(0, label_pix.shape[2] - 1, 0,
                             label_pix.shape[1] - 1, 0, label_pix.shape[0] - 1)

    vtk_import.SetWholeExtent(0, label_pix.shape[2] - 1, 0,
                              label_pix.shape[1] - 1, 0,
                              label_pix.shape[0] - 1)

    vtk_import.Update()

    flipper = vtkImageFlip()
    flipper.SetInputData(vtk_import.GetOutput())
    flipper.SetFilteredAxis(1)
    flipper.FlipAboutOriginOff()
    flipper.Update()

    vtk_img = flipper.GetOutput()

    marching_cubes = vtkDiscreteMarchingCubes()
    marching_cubes.SetInputData(vtk_img)

    num_labels_to_use = len(labels_to_use)

    marching_cubes.SetNumberOfContours(num_labels_to_use)

    for i in range(num_labels_to_use):
        marching_cubes.SetValue(i, labels_to_use[i])

    marching_cubes.Update()

    smoother = vtkWindowedSincPolyDataFilter()
    smoother.SetInputData(marching_cubes.GetOutput())
    smoother.SetNumberOfIterations(25)
    smoother.SetPassBand(0.1)
    smoother.SetBoundarySmoothing(False)
    smoother.SetFeatureEdgeSmoothing(False)
    smoother.SetFeatureAngle(120.0)
    smoother.SetNonManifoldSmoothing(True)
    smoother.NormalizeCoordinatesOn()
    smoother.Update()

    mesh_reduce = vtkQuadricDecimation()
    mesh_reduce.SetInputData(smoother.GetOutput())
    mesh_reduce.SetTargetReduction(0.25)
    mesh_reduce.Update()

    vertex_xform = np.mat(np.eye(4))
    vertex_xform[1, 1] = -1
    vertex_xform[1, 3] = label_pix.shape[1] + 1

    vertex_xform = inds_to_phys * vertex_xform

    return xform_mesh(mesh_reduce.GetOutput(), vertex_xform)
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkWindowedSincPolyDataFilter(), 'Processing.',
         ('vtkPolyData',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
def createSTL(mha, stl):

    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(mha)
    reader.Update()

    threshold = vtk.vtkImageThreshold()
    threshold.SetInputConnection(reader.GetOutputPort())
    threshold.ThresholdByLower(0.1)
    threshold.ReplaceInOn()
    threshold.SetInValue(0)  # set all values below 0.1 to 0
    threshold.ReplaceOutOn()
    threshold.SetOutValue(1)  # set all values above 0.1 to 1
    threshold.Update()

    dmc = vtk.vtkFlyingEdges3D()
    dmc.SetInputConnection(threshold.GetOutputPort())
    dmc.ComputeNormalsOn()
    dmc.GenerateValues(1, 1, 1)
    dmc.Update()

    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(dmc.GetOutputPort())
    smoother.SetNumberOfIterations(15)
    smoother.BoundarySmoothingOff()
    smoother.Update()

    writer = vtk.vtkSTLWriter()
    writer.SetInputConnection(smoother.GetOutputPort())
    writer.SetFileTypeToBinary()
    writer.SetFileName(stl)
    writer.Write()

    return 0
Beispiel #12
0
def extract_smooth_mesh(imageVTK,
                        label_range,
                        smoothing_iterations=30,
                        pass_band_param=0.01,
                        target_reduction=0.95):
    '''Extract mesh/contour for labels in imageVTK, smooth and decimate.
    
    Multiple labels can be extracted at once, however touching labels 
    will share vertices and the label ids are lost during smoothing/decimation.
    Processing is slow for small objects in a large volume and should be cropped beforehand.
    
    Args:
        imageVTK: vtk image data
        label_range: range of labels to extract. A tuple (l,l) will extract 
            a mesh for a single label id l
        smoothing_iterations: number of iterations for vtkWindowedSincPolyDataFilter
        pass_band_param: pass band param in range [0.,2.] for vtkWindowedSincPolyDataFilter.
            Lower value remove higher frequencies.
        target_reduction: target reduction for vtkQuadricDecimation
    '''

    n_contours = label_range[1] - label_range[0] + 1

    # alternative vtkDiscreteMarchingCubes is slower and creates some weird missalignment lines when applied to tight crops
    dfe = vtk.vtkDiscreteFlyingEdges3D()
    dfe.SetInputData(imageVTK)
    dfe.ComputeScalarsOff(
    )  # numpy image labels --> cells (faces) scalar values
    dfe.ComputeNormalsOff()
    dfe.ComputeGradientsOff()
    dfe.InterpolateAttributesOff()
    dfe.GenerateValues(n_contours, label_range[0],
                       label_range[1])  # numContours, rangeStart, rangeEnd
    dfe.Update()

    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(dfe.GetOutputPort())
    smoother.SetNumberOfIterations(
        smoothing_iterations)  #this has little effect on the error!
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    # smoother.SetFeatureAngle(120)
    smoother.SetPassBand(
        pass_band_param)  # from 0 to 2, 2 keeps high frequencies
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.GenerateErrorScalarsOff()
    smoother.GenerateErrorVectorsOff()
    smoother.Update()

    # vtkQuadricDecimation looks cleaner than vtkDecimatePro (no unexpected sharp edges)
    # but drop points scalar value --> can be added back if doing one instance a time
    decimate = vtk.vtkQuadricDecimation()
    decimate.SetInputConnection(smoother.GetOutputPort())
    decimate.SetTargetReduction(target_reduction)
    decimate.VolumePreservationOn()
    decimate.Update()

    return decimate.GetOutput()
Beispiel #13
0
def CreateFrogActor(fileName, tissue):
    #reader = vtk.vtkMetaImageReader()
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(fileName)
    reader.Update()

    selectTissue = vtk.vtkImageThreshold()
    #selectTissue.ThresholdBetween(tissue, tissue)
    selectTissue.ThresholdBetween(120, 125)
    selectTissue.SetInValue(255)
    selectTissue.SetOutValue(0)
    selectTissue.SetInputConnection(reader.GetOutputPort())

    gaussianRadius = 1
    gaussianStandardDeviation = 2.0
    gaussian = vtk.vtkImageGaussianSmooth()
    gaussian.SetStandardDeviations(gaussianStandardDeviation,
                                   gaussianStandardDeviation,
                                   gaussianStandardDeviation)
    gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius)
    gaussian.SetInputConnection(selectTissue.GetOutputPort())

    isoValue = 130
    mcubes = vtk.vtkMarchingCubes()
    #mcubes.SetInputConnection(gaussian.GetOutputPort())
    mcubes.SetInputConnection(reader.GetOutputPort())
    mcubes.ComputeScalarsOff()
    mcubes.ComputeGradientsOff()
    mcubes.ComputeNormalsOff()
    mcubes.SetValue(0, isoValue)

    smoothingIterations = 5
    passBand = 0.001
    featureAngle = 60.0
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(mcubes.GetOutputPort())
    smoother.SetNumberOfIterations(smoothingIterations)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(featureAngle)
    smoother.SetPassBand(passBand)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(smoother.GetOutputPort())
    normals.SetFeatureAngle(featureAngle)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(normals.GetOutputPort())

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(stripper.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
Beispiel #14
0
def create_marching_cube(data,
                         color,
                         opacity=0.5,
                         min_threshold=0,
                         smoothing_iterations=None,
                         spacing=[1., 1., 1.]):
    im = vtk.vtkImageData()
    I, J, K = data.shape[:3]
    im.SetDimensions(I, J, K)
    im.SetSpacing(spacing[0], spacing[1], spacing[2])
    im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)

    vol = np.swapaxes(data, 0, 2)
    vol = np.ascontiguousarray(vol)
    vol = vol.ravel()

    uchar_array = numpy_support.numpy_to_vtk(vol, deep=0)
    im.GetPointData().SetScalars(uchar_array)

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputData(im)
    mapper.Update()

    threshold = vtk.vtkImageThreshold()
    threshold.SetInputData(im)
    threshold.ThresholdByLower(min_threshold)
    threshold.ReplaceInOn()
    threshold.SetInValue(0)
    threshold.ReplaceOutOn()
    threshold.SetOutValue(1)
    threshold.Update()

    dmc = vtk.vtkDiscreteMarchingCubes()
    dmc.SetInputConnection(threshold.GetOutputPort())
    dmc.GenerateValues(1, 1, 1)
    dmc.Update()

    mapper = vtk.vtkPolyDataMapper()

    if smoothing_iterations is not None:
        smoother = vtk.vtkWindowedSincPolyDataFilter()
        smoother.SetInputConnection(dmc.GetOutputPort())
        smoother.SetNumberOfIterations(smoothing_iterations)
        smoother.Update()
        mapper.SetInputConnection(smoother.GetOutputPort())
    else:
        mapper.SetInputConnection(dmc.GetOutputPort())

    mapper.Update()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    mapper.ScalarVisibilityOff()

    actor.GetProperty().SetColor(color)
    actor.GetProperty().SetOpacity(opacity)

    return actor
Beispiel #15
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkWindowedSincPolyDataFilter(),
                                       'Processing.', ('vtkPolyData', ),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
    def __init__(self, source):

        # Get list with string-representations of the organs to be used
        organs = Settings.organs

        source.Update()

        # Filter
        cast_filter = vtk.vtkImageCast()
        cast_filter.SetOutputScalarTypeToUnsignedInt()
        cast_filter.SetInputConnection(source.GetOutputPort())
        cast_filter.Update()

        # Create mesh using marching cube
        march = vtk.vtkDiscreteMarchingCubes()
        march.ComputeNormalsOn()
        march.ComputeGradientsOn()
        for i, organ in enumerate(organs):
            march.SetValue(i, Settings.labels[organ]['value'])
        march.SetInputData(cast_filter.GetOutput())
        march.Update()

        # Filtrate the masks
        smooth = vtk.vtkWindowedSincPolyDataFilter()
        smooth.SetInputConnection(march.GetOutputPort())
        smooth.SetNumberOfIterations(15)
        smooth.BoundarySmoothingOff()
        smooth.FeatureEdgeSmoothingOff()
        smooth.SetFeatureAngle(120.0)
        smooth.SetPassBand(.001)
        smooth.NonManifoldSmoothingOn()
        smooth.NormalizeCoordinatesOn()
        smooth.Update()


        # Set lookup table
        self.color_transfer = vtk.vtkDiscretizableColorTransferFunction()
        self.alpha_transfer = vtk.vtkPiecewiseFunction()
        self.color_transfer.AddRGBPoint(0, 0., 0., 0.) # Background
        self.alpha_transfer.AddPoint(0, 0) # Background
        for i, organ in enumerate(Settings.organs):
            self.color_transfer.AddRGBPoint(Settings.labels[organ]['value'], *Settings.labels[organ]['rgb'])
            self.alpha_transfer.AddPoint(Settings.labels[organ]['value'], 1.)
        self.color_transfer.SetScalarOpacityFunction(self.alpha_transfer)


        # Surface mapper
        self.surface_mapper = vtk.vtkPolyDataMapper()
        self.surface_mapper.SetLookupTable(self.color_transfer)
        self.surface_mapper.SetInputConnection(smooth.GetOutputPort())


        # Create the actor
        self.actor = vtk.vtkActor()
        self.actor.GetProperty().SetOpacity(1.)
        self.actor.SetMapper(self.surface_mapper)
        self.actor.GetProperty().ShadingOn()
Beispiel #17
0
def smoothen_mesh_vtkPolys(vtkPolys):
    '''
    apply mesh smoothing to a vtk mesh
    '''
    vtkSF=vtk.vtkWindowedSincPolyDataFilter()
    vtkSF.SetNumberOfIterations(10)
    vtkSF.SetInputData(vtkPolys)
    vtkSF.Update()
    return vtkSF.GetOutput() 
Beispiel #18
0
def create_smooth_frog_actor(file_name, tissue):
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(str(file_name))
    reader.Update()

    select_tissue = vtk.vtkImageThreshold()
    select_tissue.ThresholdBetween(tissue, tissue)
    select_tissue.SetInValue(255)
    select_tissue.SetOutValue(0)
    select_tissue.SetInputConnection(reader.GetOutputPort())

    gaussianRadius = 1
    gaussianStandardDeviation = 2.0
    gaussian = vtk.vtkImageGaussianSmooth()
    gaussian.SetStandardDeviations(gaussianStandardDeviation,
                                   gaussianStandardDeviation,
                                   gaussianStandardDeviation)
    gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius)
    gaussian.SetInputConnection(select_tissue.GetOutputPort())

    isoValue = 63.5
    iso_surface = vtk.vtkFlyingEdges3D()
    iso_surface.SetInputConnection(gaussian.GetOutputPort())
    iso_surface.ComputeScalarsOff()
    iso_surface.ComputeGradientsOff()
    iso_surface.ComputeNormalsOff()
    iso_surface.SetValue(0, isoValue)

    smoothing_iterations = 20
    pass_band = 0.001
    feature_angle = 60.0
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(iso_surface.GetOutputPort())
    smoother.SetNumberOfIterations(smoothing_iterations)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(feature_angle)
    smoother.SetPassBand(pass_band)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOff()
    smoother.Update()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(smoother.GetOutputPort())
    normals.SetFeatureAngle(feature_angle)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(normals.GetOutputPort())

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(stripper.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
 def smooth_window(self, number_of_iterations=15, pass_band=0.5):
     smooth = vtk.vtkWindowedSincPolyDataFilter()
     smooth.SetInputConnection(self.mesh.GetOutputPort())
     smooth.SetNumberOfIterations(number_of_iterations)
     smooth.BoundarySmoothingOn()
     smooth.FeatureEdgeSmoothingOff()
     smooth.SetPassBand(pass_band)
     smooth.NonManifoldSmoothingOn()
     smooth.NormalizeCoordinatesOn()
     smooth.Update()
     self.mesh = smooth
Beispiel #20
0
 def _smoothPolydata(polydata, smoothingFactor):
     passBand = pow(10.0, -4.0 * smoothingFactor)
     smootherSinc = vtk.vtkWindowedSincPolyDataFilter()
     smootherSinc.SetInputData(polydata)
     smootherSinc.SetNumberOfIterations(20)
     smootherSinc.FeatureEdgeSmoothingOff()
     smootherSinc.BoundarySmoothingOff()
     smootherSinc.NonManifoldSmoothingOn()
     smootherSinc.NormalizeCoordinatesOn()
     smootherSinc.Update()
     return smootherSinc.GetOutput()
Beispiel #21
0
  def applyFilters(self, state):

    surface = None
    surface = state.inputModelNode.GetPolyDataConnection()

    if state.decimation:
      triangle = vtk.vtkTriangleFilter()
      triangle.SetInputConnection(surface)
      decimation = vtk.vtkDecimatePro()
      decimation.SetTargetReduction(state.reduction)
      decimation.SetBoundaryVertexDeletion(state.boundaryDeletion)
      decimation.PreserveTopologyOn()
      decimation.SetInputConnection(triangle.GetOutputPort())
      surface = decimation.GetOutputPort()

    if state.smoothing:
      if state.smoothingMethod == "Laplace":
        smoothing = vtk.vtkSmoothPolyDataFilter()
        smoothing.SetBoundarySmoothing(state.boundarySmoothing)
        smoothing.SetNumberOfIterations(state.laplaceIterations)
        smoothing.SetRelaxationFactor(state.laplaceRelaxation)
        smoothing.SetInputConnection(surface)
        surface = smoothing.GetOutputPort()
      elif state.smoothingMethod == "Taubin":
        smoothing = vtk.vtkWindowedSincPolyDataFilter()
        smoothing.SetBoundarySmoothing(state.boundarySmoothing)
        smoothing.SetNumberOfIterations(state.taubinIterations)
        smoothing.SetPassBand(state.taubinPassBand)
        smoothing.SetInputConnection(surface)
        surface = smoothing.GetOutputPort()

    if state.normals:
      normals = vtk.vtkPolyDataNormals()
      normals.AutoOrientNormalsOn()
      normals.SetFlipNormals(state.flipNormals)
      normals.SetSplitting(state.splitting)
      normals.SetFeatureAngle(state.featureAngle)
      normals.ConsistencyOn()
      normals.SetInputConnection(surface)
      surface = normals.GetOutputPort()

    if state.cleaner:
      cleaner = vtk.vtkCleanPolyData()
      cleaner.SetInputConnection(surface)
      surface = cleaner.GetOutputPort()

    if state.connectivity:
      connectivity = vtk.vtkPolyDataConnectivityFilter()
      connectivity.SetExtractionModeToLargestRegion()
      connectivity.SetInputConnection(surface)
      surface = connectivity.GetOutputPort()

    state.outputModelNode.SetPolyDataConnection(surface)
    return True
Beispiel #22
0
    def applyFilters(self, state):

        surface = None
        surface = state.inputModelNode.GetPolyDataConnection()

        if state.decimation:
            triangle = vtk.vtkTriangleFilter()
            triangle.SetInputConnection(surface)
            decimation = vtk.vtkDecimatePro()
            decimation.SetTargetReduction(state.reduction)
            decimation.SetBoundaryVertexDeletion(state.boundaryDeletion)
            decimation.PreserveTopologyOn()
            decimation.SetInputConnection(triangle.GetOutputPort())
            surface = decimation.GetOutputPort()

        if state.smoothing:
            if state.smoothingMethod == "Laplace":
                smoothing = vtk.vtkSmoothPolyDataFilter()
                smoothing.SetBoundarySmoothing(state.boundarySmoothing)
                smoothing.SetNumberOfIterations(state.laplaceIterations)
                smoothing.SetRelaxationFactor(state.laplaceRelaxation)
                smoothing.SetInputConnection(surface)
                surface = smoothing.GetOutputPort()
            elif state.smoothingMethod == "Taubin":
                smoothing = vtk.vtkWindowedSincPolyDataFilter()
                smoothing.SetBoundarySmoothing(state.boundarySmoothing)
                smoothing.SetNumberOfIterations(state.taubinIterations)
                smoothing.SetPassBand(state.taubinPassBand)
                smoothing.SetInputConnection(surface)
                surface = smoothing.GetOutputPort()

        if state.normals:
            normals = vtk.vtkPolyDataNormals()
            normals.AutoOrientNormalsOn()
            normals.SetFlipNormals(state.flipNormals)
            normals.SetSplitting(state.splitting)
            normals.SetFeatureAngle(state.featureAngle)
            normals.ConsistencyOn()
            normals.SetInputConnection(surface)
            surface = normals.GetOutputPort()

        if state.cleaner:
            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInputConnection(surface)
            surface = cleaner.GetOutputPort()

        if state.connectivity:
            connectivity = vtk.vtkPolyDataConnectivityFilter()
            connectivity.SetExtractionModeToLargestRegion()
            connectivity.SetInputConnection(surface)
            surface = connectivity.GetOutputPort()

        state.outputModelNode.SetPolyDataConnection(surface)
        return True
Beispiel #23
0
 def __init__(self, img, threshold, xysmoothing, zsmoothing, color, alpha):
     dataImporter = vtk.vtkImageImport()
     simg = np.ascontiguousarray(img, np.uint8)
     dataImporter.CopyImportVoidPointer(simg.data, len(simg.data))
     dataImporter.SetDataScalarTypeToUnsignedChar()
     dataImporter.SetNumberOfScalarComponents(1)
     dataImporter.SetDataExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1)
     dataImporter.SetWholeExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1)
     self.__smoother = vtk.vtkImageGaussianSmooth()
     self.__smoother.SetStandardDeviation(xysmoothing, xysmoothing, zsmoothing)
     self.__smoother.SetInputConnection(dataImporter.GetOutputPort())
     self.__threshold = vtk.vtkImageThreshold()
     self.__threshold.SetInputConnection(self.__smoother.GetOutputPort())
     self.__threshold.ThresholdByUpper(threshold)
     self.__threshold.ReplaceInOn()
     self.__threshold.SetInValue(1)
     self.__threshold.ReplaceOutOn()
     self.__threshold.SetOutValue(0)
     self.__threshold.Update()
     contour = vtk.vtkDiscreteMarchingCubes()
     contour.SetInputConnection(self.__threshold.GetOutputPort())
     contour.ComputeNormalsOn()
     contour.SetValue(0, 1)
     contour.Update()
     smoother = vtk.vtkWindowedSincPolyDataFilter()
     smoother.SetInputConnection(contour.GetOutputPort())
     smoother.NonManifoldSmoothingOn()
     smoother.NormalizeCoordinatesOn()
     smoother.Update()
     triangleCellNormals=vtk.vtkPolyDataNormals()
     triangleCellNormals.SetInputConnection(smoother.GetOutputPort())
     triangleCellNormals.ComputeCellNormalsOn()
     triangleCellNormals.ComputePointNormalsOff()
     triangleCellNormals.ConsistencyOn()
     triangleCellNormals.AutoOrientNormalsOn()
     triangleCellNormals.Update()
     triangleCellAn = vtk.vtkMeshQuality()
     triangleCellAn.SetInputConnection(triangleCellNormals.GetOutputPort())
     triangleCellAn.SetTriangleQualityMeasureToArea()
     triangleCellAn.SaveCellQualityOn()
     triangleCellAn.Update()
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(triangleCellAn.GetOutputPort())
     mapper.ScalarVisibilityOn()
     mapper.SetScalarRange(.3, 1)
     mapper.SetScalarModeToUsePointData()
     colorLookupTable = vtk.vtkLookupTable()
     colorLookupTable.SetHueRange(.6, 1)
     colorLookupTable.Build()
     mapper.SetLookupTable(colorLookupTable)
     self.SetMapper(mapper)
     self.GetProperty().SetColor(*color)
     self.GetProperty().SetOpacity(alpha)
Beispiel #24
0
def sinWinSmoother(polyData):
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputData(polyData)
    smoother.SetNumberOfIterations(15)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(60.0)
    smoother.SetPassBand(0.1)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()
    return smoother.GetOutput()
Beispiel #25
0
def sinWinSmoother(polyData):
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputData(polyData);
    smoother.SetNumberOfIterations(15);
    smoother.BoundarySmoothingOff();
    smoother.FeatureEdgeSmoothingOff();
    smoother.SetFeatureAngle(60.0);
    smoother.SetPassBand(0.1);
    smoother.NonManifoldSmoothingOn();
    smoother.NormalizeCoordinatesOn();
    smoother.Update()
    return smoother.GetOutput()
def niftiMask2Surface(img_path, surf_name, smooth_iter=10, filetype="vtk"):
    # import the binary nifti image
    reader = vtk.vtkNIFTIImageReader()
    reader.SetFileName(img_path)
    reader.Update()

    # do marching cubes to create a surface
    surface = vtk.vtkDiscreteMarchingCubes()
    surface.SetInputConnection(reader.GetOutputPort())
    # GenerateValues(number of surfaces, label range start, label range end)
    surface.GenerateValues(1, 1, 1)
    surface.Update()

    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(surface.GetOutputPort())
    smoother.SetNumberOfIterations(smooth_iter)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()

    connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
    connectivityFilter.SetInputConnection(smoother.GetOutputPort())
    connectivityFilter.SetExtractionModeToLargestRegion()
    connectivityFilter.Update()

    cleaned = vtk.vtkCleanPolyData()
    cleaned.SetInputConnection(connectivityFilter.GetOutputPort())
    cleaned.Update()
    # doesn't work, but may need in future
    # close_holes = vtk.vtkFillHolesFilter()
    # close_holes.SetInputConnection(smoother.GetOutputPort())
    # close_holes.SetHoleSize(10)
    # close_holes.Update()
    if filetype == "stl":
        writer = vtk.vtkSTLWriter()
        writer.SetInputConnection(cleaned.GetOutputPort())
        writer.SetFileTypeToASCII()
        writer.SetFileName(surf_name)
        writer.Write()

    if filetype == "ply":
        writer = vtk.vtkPLYWriter()
        writer.SetInputConnection(cleaned.GetOutputPort())
        writer.SetFileTypeToASCII()
        writer.SetFileName(surf_name)
        writer.Write()

    if filetype == "vtk":
        writer = vtk.vtkPolyDataWriter()
        #writer = vtk.vtkDataSetWriter()
        writer.SetInputConnection(cleaned.GetOutputPort())
        writer.SetFileName(surf_name)
        writer.Write()
    def prepareModel(self, polyData):
        '''
        '''
        # import the vmtk libraries
        try:
            import vtkvmtkComputationalGeometryPython as vtkvmtkComputationalGeometry
            import vtkvmtkMiscPython as vtkvmtkMisc
        except ImportError:
            logging.error("Unable to import the SlicerVmtk libraries")

        capDisplacement = 0.0

        surfaceCleaner = vtk.vtkCleanPolyData()
        surfaceCleaner.SetInputData(polyData)
        surfaceCleaner.Update()

        surfaceTriangulator = vtk.vtkTriangleFilter()
        surfaceTriangulator.SetInputData(surfaceCleaner.GetOutput())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        # new steps for preparation to avoid problems because of slim models (f.e. at stenosis)
        subdiv = vtk.vtkLinearSubdivisionFilter()
        subdiv.SetInputData(surfaceTriangulator.GetOutput())
        subdiv.SetNumberOfSubdivisions(1)
        subdiv.Update()

        smooth = vtk.vtkWindowedSincPolyDataFilter()
        smooth.SetInputData(subdiv.GetOutput())
        smooth.SetNumberOfIterations(20)
        smooth.SetPassBand(0.1)
        smooth.SetBoundarySmoothing(1)
        smooth.Update()

        normals = vtk.vtkPolyDataNormals()
        normals.SetInputData(smooth.GetOutput())
        normals.SetAutoOrientNormals(1)
        normals.SetFlipNormals(0)
        normals.SetConsistency(1)
        normals.SplittingOff()
        normals.Update()

        surfaceCapper = vtkvmtkComputationalGeometry.vtkvmtkCapPolyData()
        surfaceCapper.SetInputData(normals.GetOutput())
        surfaceCapper.SetDisplacement(capDisplacement)
        surfaceCapper.SetInPlaneDisplacement(capDisplacement)
        surfaceCapper.Update()

        outPolyData = vtk.vtkPolyData()
        outPolyData.DeepCopy(surfaceCapper.GetOutput())

        return outPolyData
Beispiel #28
0
def main():
    n = 20
    radius = 8
    blob = make_blob(n, radius)

    discrete = vtk.vtkDiscreteMarchingCubes()
    discrete.SetInputData(blob)
    discrete.GenerateValues(n, 1, n)

    smoothing_iterations = 15
    pass_band = 0.001
    feature_angle = 120.0

    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(discrete.GetOutputPort())
    smoother.SetNumberOfIterations(smoothing_iterations)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(feature_angle)
    smoother.SetPassBand(pass_band)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()

    lut = make_colors(n)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(smoother.GetOutputPort())
    mapper.SetLookupTable(lut)
    mapper.SetScalarRange(0, lut.GetNumberOfColors())

    # Create the RenderWindow, Renderer and both Actors
    #
    ren = vtk.vtkRenderer()
    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(ren)
    ren_win.SetWindowName('SmoothDiscreteMarchingCubes')

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(ren_win)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    ren.AddActor(actor)

    colors = vtk.vtkNamedColors()
    ren.SetBackground(colors.GetColor3d('Burlywood'))

    ren_win.Render()

    iren.Start()
Beispiel #29
0
    def show_render(self):
        self.reader = vtk.vtkXMLImageDataReader()
        if os.sep == '\\':
            self.reader.SetFileName('.\\__vtk_files__\\Polydata.vti')
        else:
            self.reader.SetFileName('__vtk_files__/Polydata.vti')
        self.reader.Update()

        self.surface = vtk.vtkMarchingCubes()
        self.surface.SetInputData(self.reader.GetOutput())
        self.surface.ComputeNormalsOn()
        self.surface.SetValue(0, 1)

        renderer = vtk.vtkRenderer()
        renderer.SetBackground(1, 1, 1)

        renderWindow = vtk.vtkRenderWindow()
        renderWindow.AddRenderer(renderer)

        interactor = vtk.vtkRenderWindowInteractor()
        interactor.SetRenderWindow(renderWindow)

        smoothing_iterations = 15
        pass_band = 0.001
        feature_angle = 120.0
        self.smoother = vtk.vtkWindowedSincPolyDataFilter()
        self.smoother.SetInputConnection(self.surface.GetOutputPort())
        self.smoother.SetNumberOfIterations(smoothing_iterations)
        self.smoother.BoundarySmoothingOff()
        self.smoother.FeatureEdgeSmoothingOff()
        self.smoother.SetFeatureAngle(feature_angle)
        self.smoother.SetPassBand(pass_band)
        self.smoother.NonManifoldSmoothingOn()
        self.smoother.NormalizeCoordinatesOn()
        self.smoother.Update()

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.smoother.GetOutputPort())
        self.mapper.ScalarVisibilityOff()

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetColor(0.105, 0.980, 0)
        self.actor.GetProperty().SetAmbient(0.3)
        self.actor.GetProperty().SetDiffuse(0.5)
        #actor.GetProperty().SetSpecular(0.1);
        style = vtk.vtkInteractorStyleTrackballCamera()
        self.iren.SetInteractorStyle(style)
        self.renderer.AddActor(self.actor)
        self.renderer.ResetCamera()
        self.iren.Initialize()
        self.iren.Start()
Beispiel #30
0
def smoothtaubin(polydata, iterations=15, angle=120, passband=0.001):
    """Execute volume reserving smoothing."""
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInput(polydata)
    smoother.SetNumberOfIterations(iterations)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(angle)
    smoother.SetPassBand(passband)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()
    return smoother.GetOutput()
 def wrapOpImp(self):
     smooth = vtk.vtkWindowedSincPolyDataFilter();
     smooth.SetInputData(self.data);
     smooth.NormalizeCoordinatesOn();
     smooth.NonManifoldSmoothingOn();
     smooth.BoundarySmoothingOn();
     if self.feature_detect:
         smooth.FeatureEdgeSmoothingOn();
     else:
         smooth.FeatureEdgeSmoothingOff();
     smooth.Update();
     result = smooth.GetOutput();
     return result; 
Beispiel #32
0
    def desenha_surface(self,
                        tipo='Schwarz_P',
                        tam=None,
                        spacing=None,
                        hole_size=None,
                        ufunc=None):
        if tam is None:
            tam = 6, 6, 6
        if spacing is None:
            spacing = 1.0, 1.0, 1.0
        if hole_size is None:
            hole_size = 0.1, 0.3
        #print hole_size

        M = fun_schwartzP(tipo, tam, spacing, hole_size, ufunc)

        f = h5py.File("/tmp/camboja_ufunc.hdf5", "w")
        f['data'] = M
        f['spacing'] = numpy.array(spacing)

        self.M = M
        self.spacing = spacing

        image = to_vtk(M, spacing)

        surf = vtk.vtkMarchingCubes()
        surf.SetInputData(image)
        #surf.SetValue(0,0.5)
        surf.SetValue(0, 0.02)
        surf.ComputeNormalsOn()
        surf.ComputeGradientsOn()
        surf.Update()

        subdiv = vtk.vtkWindowedSincPolyDataFilter()
        subdiv.SetInputData(surf.GetOutput())
        subdiv.SetNumberOfIterations(100)
        subdiv.SetFeatureAngle(120)
        subdiv.SetBoundarySmoothing(60)
        subdiv.BoundarySmoothingOn()
        subdiv.SetEdgeAngle(90)
        subdiv.Update()

        ##        subdiv= vtk.vtkLoopSubdivisionFilter()
        ##        subdiv.SetInput(surf.GetOutput())
        ##        subdiv.Update()

        #self.mapper.SetInput(surf.GetOutput())

        self.mapper.SetInputData(subdiv.GetOutput())
        self.Interactor.Render()
Beispiel #33
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self)

        mm = self._module_manager

        self._cleaner = vtk.vtkCleanPolyData()

        self._tf = vtk.vtkTriangleFilter()
        self._tf.SetInput(self._cleaner.GetOutput())

        self._wspdf = vtk.vtkWindowedSincPolyDataFilter()
        #self._wspdf.SetNumberOfIterations(50)
        self._wspdf.SetInput(self._tf.GetOutput())
        self._wspdf.SetProgressText('smoothing')
        self._wspdf.SetProgressMethod(
            lambda s=self, mm=mm: mm.vtk_progress_cb(s._wspdf))

        self._cleaner2 = vtk.vtkCleanPolyData()
        self._cleaner2.SetInput(self._wspdf.GetOutput())

        self._curvatures = vtk.vtkCurvatures()
        self._curvatures.SetCurvatureTypeToMean()
        self._curvatures.SetInput(self._cleaner2.GetOutput())

        self._tf.SetProgressText('triangulating')
        self._tf.SetProgressMethod(
            lambda s=self, mm=mm: mm.vtk_progress_cb(s._tf))

        self._curvatures.SetProgressText('calculating curvatures')
        self._curvatures.SetProgressMethod(
            lambda s=self, mm=mm: mm.vtk_progress_cb(s._curvatures))

        self._inputFilter = self._tf

        self._inputPoints = None
        self._inputPointsOID = None
        self._giaGlenoid = None
        self._outsidePoints = None
        self._outputPolyDataARB = vtk.vtkPolyData()
        self._outputPolyDataHM = vtk.vtkPolyData()

        self._createViewFrame('Test Module View', {
            'vtkTriangleFilter': self._tf,
            'vtkCurvatures': self._curvatures
        })

        self._viewFrame.Show(True)
def CreateFrogSkinActor(fileName, useMarchingCubes):
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(fileName)
    reader.Update()

    isoValue = 20.5
    mcubes = vtk.vtkMarchingCubes()
    flyingEdges = vtk.vtkFlyingEdges3D()
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    if useMarchingCubes:
        mcubes.SetInputConnection(reader.GetOutputPort())
        mcubes.ComputeScalarsOff()
        mcubes.ComputeGradientsOff()
        mcubes.ComputeNormalsOff()
        mcubes.SetValue(0, isoValue)
        smoother.SetInputConnection(mcubes.GetOutputPort())
    else:
        flyingEdges.SetInputConnection(reader.GetOutputPort())
        flyingEdges.ComputeScalarsOff()
        flyingEdges.ComputeGradientsOff()
        flyingEdges.ComputeNormalsOff()
        flyingEdges.SetValue(0, isoValue)
        smoother.SetInputConnection(flyingEdges.GetOutputPort())

    smoothingIterations = 5
    passBand = 0.001
    featureAngle = 60.0
    smoother.SetNumberOfIterations(smoothingIterations)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(featureAngle)
    smoother.SetPassBand(passBand)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(smoother.GetOutputPort())
    normals.SetFeatureAngle(featureAngle)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(normals.GetOutputPort())

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(stripper.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
Beispiel #35
0
def smooth_mesh(mesh: Union[vtk.vtkPolyData, pv.PolyData], n_iter=15, pass_band=0.001, feature_angle=120.0):
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputData(mesh)
    smoother.SetNumberOfIterations(n_iter)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(feature_angle)
    smoother.SetPassBand(pass_band)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()
    mesh = smoother.GetOutput()
    mesh = pv.wrap(mesh)
    return mesh
 def smooth(inputModel, outputModel, method='Taubin', iterations=30, laplaceRelaxationFactor=0.5, taubinPassBand=0.1, boundarySmoothing=True):
   """Smoothes surface model using a Laplacian filter or Taubin's non-shrinking algorithm.
   """
   if method == "Laplace":
     smoothing = vtk.vtkSmoothPolyDataFilter()
     smoothing.SetRelaxationFactor(laplaceRelaxationFactor)
   else:  # "Taubin"
     smoothing = vtk.vtkWindowedSincPolyDataFilter()
     smoothing.SetPassBand(taubinPassBand)
   smoothing.SetBoundarySmoothing(boundarySmoothing)
   smoothing.SetNumberOfIterations(iterations)
   smoothing.SetInputData(inputModel.GetPolyData())
   smoothing.Update()
   outputModel.SetAndObservePolyData(smoothing.GetOutput())
Beispiel #37
0
    def create_lungcontour(self):
        """Create a lungcontour using the Marching Cubes algorithm and smooth the surface
        
        """
    	self._view_frame.SetStatusText("Calculating lungcontour...")
    	contourLung = vtk.vtkMarchingCubes()
    	contourLung.SetValue(0,1)
    	contourLung.SetInput(self.mask_data)

    	smoother = vtk.vtkWindowedSincPolyDataFilter()
    	smoother.SetInput(contourLung.GetOutput())
    	smoother.BoundarySmoothingOn()
    	smoother.SetNumberOfIterations(40)
    	smoother.Update()
    	self.lung_mapper.SetInput(smoother.GetOutput())
    	self.lung_mapper.Update()
    	self._view_frame.SetStatusText("Calculated lungcontour")
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self)

        mm = self._module_manager

        self._cleaner = vtk.vtkCleanPolyData()

        self._tf = vtk.vtkTriangleFilter()
        self._tf.SetInput(self._cleaner.GetOutput())

        self._wspdf = vtk.vtkWindowedSincPolyDataFilter()
        # self._wspdf.SetNumberOfIterations(50)
        self._wspdf.SetInput(self._tf.GetOutput())
        self._wspdf.SetProgressText("smoothing")
        self._wspdf.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._wspdf))

        self._cleaner2 = vtk.vtkCleanPolyData()
        self._cleaner2.SetInput(self._wspdf.GetOutput())

        self._curvatures = vtk.vtkCurvatures()
        self._curvatures.SetCurvatureTypeToMean()
        self._curvatures.SetInput(self._cleaner2.GetOutput())

        self._tf.SetProgressText("triangulating")
        self._tf.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._tf))

        self._curvatures.SetProgressText("calculating curvatures")
        self._curvatures.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._curvatures))

        self._inputFilter = self._tf

        self._inputPoints = None
        self._inputPointsOID = None
        self._giaGlenoid = None
        self._outsidePoints = None
        self._outputPolyDataARB = vtk.vtkPolyData()
        self._outputPolyDataHM = vtk.vtkPolyData()

        self._createViewFrame("Test Module View", {"vtkTriangleFilter": self._tf, "vtkCurvatures": self._curvatures})

        self._viewFrame.Show(True)
Beispiel #39
0
def load_maps(mol,rendmod,gfx,atomcol):
	mol.reader = vtk.vtkStructuredPointsReader()
	mol.reader.SetFileName(mol.mod.dfn)
	mol.reader.Update() #by calling Update() we read the file
	mol.iso = vtk.vtkMarchingContourFilter()
	mol.iso.UseScalarTreeOn()
	mol.iso.ComputeNormalsOn()
	mol.iso.SetInputConnection(mol.reader.GetOutputPort())
	mol.iso.SetValue(0,mol.mod.isov*mol.mod.sigavg[0]+mol.mod.sigavg[1])
	clean = vtk.vtkCleanPolyData()
  	clean.SetInputConnection(mol.iso.GetOutputPort())
 	clean.ConvertStripsToPolysOn()
	smooth = vtk.vtkWindowedSincPolyDataFilter()
 	smooth.SetInputConnection(clean.GetOutputPort())
 	smooth.BoundarySmoothingOn()
 	smooth.GenerateErrorVectorsOn()
  	smooth.GenerateErrorScalarsOn()
  	smooth.NormalizeCoordinatesOn()
  	smooth.NonManifoldSmoothingOn()
  	smooth.FeatureEdgeSmoothingOn()
  	smooth.SetEdgeAngle(90)
	smooth.SetFeatureAngle(90)
	smooth.Update()
	mol.mapper = vtk.vtkOpenGLPolyDataMapper()
	mol.mapper.SetInputConnection(smooth.GetOutputPort()) ### <- connection here
	mol.mapper.ScalarVisibilityOff()
	mol.mapper.Update()
	mol.acteur= vtk.vtkOpenGLActor()
	mol.acteur.SetMapper(mol.mapper)
	mol.acteur.GetProperty().SetColor(mol.col)
	if rendmod==5:
		mol.acteur.GetProperty().SetRepresentationToSurface()
	elif rendmod==6:
		mol.acteur.GetProperty().SetRepresentationToWireframe()
	elif rendmod==7:
		mol.acteur.GetProperty().SetRepresentationToPoints()
	else :
		mol.acteur.GetProperty().SetRepresentationToSurface()
	mol.acteur.GetProperty().SetInterpolationToGouraud()
	mol.acteur.GetProperty().SetSpecular(.4)
	mol.acteur.GetProperty().SetSpecularPower(10)
	gfx.renderer.AddActor(mol.acteur)
	gfx.renwin.Render()
Beispiel #40
0
def smoothMesh(mesh, nIterations=10):
    try:
        t = time.clock()
        smooth = vtk.vtkWindowedSincPolyDataFilter()
        smooth.SetNumberOfIterations( nIterations )
        if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
            smooth.SetInputData( mesh )
        else:
            smooth.SetInput( mesh )
        smooth.Update()
        print ("Surface smoothed")
        m2 = smooth.GetOutput()
        print "    ", m2.GetNumberOfPolys(), "polygons"
        elapsedTime(t)
        smooth = None
        return m2
    except:
        print "Surface smoothing failed"
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
    return None
Beispiel #41
0
    def process_image(self, image):
        dims = image.shape
        width = dims[1]
        height = dims[2]
        depth = dims[0]
        vtk_data = numpy_support.numpy_to_vtk(num_array=image.ravel(), deep=True, array_type=vtk.VTK_FLOAT)

        imgdat = vtk.vtkImageData()
        imgdat.GetPointData().SetScalars(vtk_data)
        imgdat.SetDimensions(height, width, depth)
        imgdat.SetOrigin(0, 0, 0)
        spacing = self.image_processing.spacing
        imgdat.SetSpacing(spacing[0], spacing[1], spacing[2])

        dmc = vtk.vtkDiscreteMarchingCubes()
        dmc.SetInputData(imgdat)
        dmc.GenerateValues(1, 1, 1)
        dmc.Update()

        smoothing_iterations = 15
        pass_band = 0.001
        feature_angle = 120.0

        smoother = vtk.vtkWindowedSincPolyDataFilter()
        smoother.SetInputConnection(dmc.GetOutputPort())
        smoother.SetNumberOfIterations(smoothing_iterations)
        smoother.BoundarySmoothingOff()
        smoother.FeatureEdgeSmoothingOff()
        smoother.SetFeatureAngle(feature_angle)
        smoother.SetPassBand(pass_band)
        smoother.NonManifoldSmoothingOn()
        smoother.NormalizeCoordinatesOn()
        smoother.Update()

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(smoother.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        return actor
Beispiel #42
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        

        self._wsPDFilter = vtk.vtkWindowedSincPolyDataFilter()

        module_utils.setup_vtk_object_progress(self, self._wsPDFilter,
                                           'Smoothing polydata')
        

        # setup some defaults
        self._config.numberOfIterations = 20
        self._config.passBand = 0.1
        self._config.featureEdgeSmoothing = False
        self._config.boundarySmoothing = True
        self._config.non_manifold_smoothing = False

        config_list = [
            ('Number of iterations', 'numberOfIterations', 'base:int', 'text',
             'Algorithm will stop after this many iterations.'),
            ('Pass band (0 - 2, default 0.1)', 'passBand', 'base:float',
             'text', 'Indication of frequency cut-off, the lower, the more '
             'it smoothes.'),
            ('Feature edge smoothing', 'featureEdgeSmoothing', 'base:bool',
             'checkbox', 'Smooth feature edges (large dihedral angle)'),
            ('Boundary smoothing', 'boundarySmoothing', 'base:bool',
             'checkbox', 'Smooth boundary edges (edges with only one face).'),
            ('Non-manifold smoothing', 'non_manifold_smoothing',
            'base:bool', 'checkbox',
            'Smooth non-manifold vertices, for example output of '
            'discrete marching cubes (multi-material).')]

        ScriptedConfigModuleMixin.__init__(
            self, config_list,
            {'Module (self)' : self,
             'vtkWindowedSincPolyDataFilter' : self._wsPDFilter})
   
        self.sync_module_logic_with_config()
Beispiel #43
0
def load_map(gfx,mapfile,root,status,scale,rendtype,isov,opct,cropentry,nfv,vardeci,varsmooth,color,caller):
	if caller != 'fit':
		root.configure(cursor='watch')
		status.set('Map loading ... please wait')
	if mapfile =='' or mapfile == None or mapfile ==() :
		MB.showwarning('Info','Select map file')
		status.clear()
		root.configure(cursor='arrow')
		return
	try:
		gfx.renderer.RemoveActor(gfx.map[0].acteur)
		gfx.renderer.RemoveActor(gfx.map[0].box)
	except:
		pass
	if mapfile == 0:
		mapfile = gfx.map[0].fn
	if gfx.map == []:
		gfx.map = [Map()]
		gfx.map[0].id=0
	if 'map' in caller :
		clean_map(gfx) #supression des fichiers sort.s xudi et iudi
	if '.vtk' in mapfile:
		chdir(gfx.tmpdir)
		v2v_out='info_map'
		if caller != 'crop':
			gfx.map[0].sigma,gfx.map[0].avg = map_sigma_avg(v2v_out)
		if scale != gfx.map[0].scale:
			spc = None
			o = None
			f = open(mapfile,'r')
			for l in f:
				if l.startswith('SPACING'):
					spc = l.split()[1:4]
				if l.startswith('ORIGIN'):
					o = l.split()[1:4]
				if spc != None and o != None:
					break
			f.close()
			gfx.map[0].ratio = scale/gfx.map[0].scale
			if spc != None and o != None:
				system("sed -i -e /^SPACING/s/.*/'SPACING %f %f %f'/ %s"%(float(spc[0])*gfx.map[0].ratio,float(spc[1])*gfx.map[0].ratio,float(spc[2])*gfx.map[0].ratio,mapfile))
				system("sed -i -e /^ORIGIN/s/.*/'ORIGIN %f %f %f'/ %s"%(float(o[0])*gfx.map[0].ratio,float(o[1])*gfx.map[0].ratio,float(o[2])*gfx.map[0].ratio,mapfile))
		chdir(gfx.workdir)
	if '.ezd' in mapfile:
		chdir(gfx.tmpdir)
		mapfileout = extract_file_from_path(mapfile)[:-4]+'.vtk'
		e2v_out='info_map'
		system(gfx.vedabin+'/e2v.exe >> %s <<ENDOF\n%s  \n%f  \n%s  \nENDOF'%(e2v_out,mapfile,scale,mapfileout))
		mapfile = gfx.tmpdir + '/' + mapfileout
		gfx.map[0].sigma,gfx.map[0].avg = map_sigma_avg(e2v_out)
		chdir(gfx.workdir)
	gfx.map[0].fn = mapfile
	gfx.map[0].id = set_map_id(gfx)
	gfx.map[0].color = color
	gfx.map[0].oldscale = gfx.map[0].scale
	gfx.map[0].scale = scale
	if nfv !=None:
		nfv.set(extract_file_from_path(gfx.map[0].fn))
	reader = vtk.vtkStructuredPointsReader()
	reader.SetFileName(mapfile)
	reader.Update() #by calling Update() we read the file
	gfx.map[0].reader=reader
	iso = vtk.vtkMarchingContourFilter()
	iso.UseScalarTreeOn()
	iso.ComputeNormalsOn()
	iso.SetInputConnection(reader.GetOutputPort())
	iso.SetValue(0,isov*gfx.map[0].sigma+gfx.map[0].avg)
	gfx.map[0].iso=iso
	gfx.map[0].isov=isov
	if varsmooth == '1':
		#generate vectors
		clean = vtk.vtkCleanPolyData()
	  	clean.SetInputConnection(iso.GetOutputPort())
	 	clean.ConvertStripsToPolysOn()
		smooth = vtk.vtkWindowedSincPolyDataFilter()
	 	smooth.SetInputConnection(clean.GetOutputPort())
	 	smooth.BoundarySmoothingOn()
	 	smooth.GenerateErrorVectorsOn()
	  	smooth.GenerateErrorScalarsOn()
	  	smooth.NormalizeCoordinatesOn()
	  	smooth.NonManifoldSmoothingOn()
	  	smooth.FeatureEdgeSmoothingOn()
	  	smooth.SetEdgeAngle(90)
		smooth.SetFeatureAngle(90)
		smooth.Update()
	if vardeci=='1':
		deci = vtk.vtkDecimatePro()
		if varsmooth == '0':
			deci.SetInput(iso.GetOutput())
		else :
			deci.SetInput(smooth.GetOutput())
		deci.PreserveTopologyOn()
		deci.BoundaryVertexDeletionOn()
		deci.SplittingOn()
		deci.PreSplitMeshOn()
		deci.SetTargetReduction(0.97)
		gfx.map[0].isdeci='1'
		mapper = vtk.vtkOpenGLPolyDataMapper()
		mapper.SetInputConnection(deci.GetOutputPort())
	else :
		mapper = vtk.vtkOpenGLPolyDataMapper()
		if varsmooth == '1':
			mapper.SetInputConnection(smooth.GetOutputPort()) ### <- connection here
		else :
			mapper.SetInputConnection(iso.GetOutputPort())
		#mapper.SetInput(newpd) ### <- newpd connect there
		gfx.map[0].isdeci='0'
	mapper.ScalarVisibilityOff()
	mapper.Update()
	gfx.map[0].mapper=mapper
	actor = vtk.vtkOpenGLActor()
	actor.SetMapper(mapper)
	gfx.map[0].acteur=actor
	#actor.SetScale(scale,scale,scale) gerer differament
	actor.GetProperty().SetColor(gfx.map[0].color)
	actor.PickableOff()
	#definition de la box
	outline = vtk.vtkOutlineFilter()
        outline.SetInput(reader.GetOutput())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInput(outline.GetOutput())
	box=vtk.vtkActor()
        box.SetMapper( outlineMapper )
        box.GetProperty().SetColor((invcolor(gfx.map[0].color)))
        box.PickableOff()
	#box.SetScale(scale,scale,scale)
	gfx.map[0].box = box
	#get boxwidget bounds and set axes lenth
	(xmin,xmax,ymin,ymax,zmin,zmax)=box.GetBounds()
        x=abs(xmin-xmax)/2.0
	y=abs(ymin-ymax)/2.0
	z=abs(zmin-zmax)/2.0
	gfx.axes.SetTotalLength( x, y , z ) #defini la longeurs des axe
	init_cam_slab(gfx,(xmin,xmax,ymin,ymax,zmin,zmax)) #defini le slab correct
	gfx.map[0].rendtype=rendtype
	if rendtype=='Wireframe':
		actor.GetProperty().SetRepresentationToWireframe()
	elif rendtype=='Surface':
		actor.GetProperty().SetRepresentationToSurface()
	elif rendtype=='Points':
		actor.GetProperty().SetRepresentationToPoints()
		actor.GetProperty().SetPointSize(5)
	else :
		actor.GetProperty().SetRepresentationToWireframe()
	gfx.map[0].opct=opct
	actor.GetProperty().SetOpacity(opct)
	actor.GetProperty().SetInterpolationToGouraud()
	actor.GetProperty().SetSpecular(.4)
	actor.GetProperty().SetSpecularPower(10)
	if cropentry!=None:
		if gfx.crop==None:
			gfx.crop=Crop(gfx,iso,cropentry,None) #here entryval = None
	rendermap(gfx)
	#ajustement pour la symetry helicoidale
	if gfx.map[0].scale != gfx.map[0].oldscale:#changement de scale
		gfx.itf.propagate_scale(gfx,scale,caller)
		if gfx.ps != None:
			if gfx.ps.solidtype == 'Helicoidal':
				gfx.ps.display_tube(gfx,caller)
			elif gfx.ps.solidtype == 'Icosahedral' or gfx.ps.solidtype =='Octahedral' or gfx.ps.solidtype == 'Tetrahedral':
				gfx.ps.display_platonic(gfx,gfx.ps.ori)
			elif gfx.ps.solidtype =='Cn' or gfx.ps.solidtype == 'Dn':
				gfx.ps.display_Xn(gfx)
	if caller == 'crop':#crop uniquement helicoidal
		if gfx.ps != None:
			if gfx.ps.solidtype == 'Helicoidal':
				gfx.ps.display_tube(gfx,caller)
	if caller != 'fit':
		status.clear()
		root.configure(cursor='arrow')
    def FringeSimulator(self, file_name, file_output):
        
 
        reader = vtk.vtkPLYReader()
        reader.SetFileName(file_name)
        reader.Update()

        smooth = vtk.vtkWindowedSincPolyDataFilter()   
        smooth.SetInput(reader.GetOutput())
        smooth.Update()
  
        normals = vtk.vtkPolyDataNormals()
        normals.SetInput(smooth.GetOutput())
        normals.SetComputePointNormals(1)
        normals.SetComputeCellNormals(1)
        normals.Update()

        mapper=vtk.vtkDataSetMapper()
        mapper.SetInput(smooth.GetOutput())
        mapper.SetScalarVisibility(1)

        actor = vtk.vtkActor()
        actor.GetProperty().SetInterpolationToFlat()
        actor.SetMapper(mapper)

        self.renderer.AddActor(actor)

        key_properties = vtk.vtkInformation()
        key_properties.Set(vtk.vtkShadowMapBakerPass.OCCLUDER(),0) #// dummy val.
        key_properties.Set(vtk.vtkShadowMapBakerPass.RECEIVER(),0) #// dummy val.

        actor.SetPropertyKeys(key_properties)
        actor.SetVisibility(1)

        self.renderer.ResetCamera()
        cam = self.renderer.GetActiveCamera()

        cam_pos = cam.GetPosition()
        cam_f =  cam.GetFocalPoint()

        vcam_pos = numpy.array([float(cam_pos[0]), float(cam_pos[1]), float(cam_pos[2])])
        vcam_f = numpy.array([float(cam_f[0]),float(cam_f[1]),float(cam_f[2])])

        v = vcam_f - vcam_pos 
        d = numpy.linalg.norm(v)
        vn = v/d

        ap = vtk.vtkAppendPolyData()
        dist_fringes = cam_pos - vn * -250

        for x in xrange(-220, 220):
            cube_source= vtk.vtkCubeSource()
            cube_source.SetXLength(0.20)
            cube_source.SetYLength(80)
            cube_source.SetZLength(0.1)

            xfm = vtk.vtkTransform()
            xfm.Translate(float(x) * 0.40, 0, 0) 

            xfmPd = vtk.vtkTransformPolyDataFilter()
            xfmPd.SetInput(cube_source.GetOutput())
            xfmPd.SetTransform(xfm)

            ap.AddInput(xfmPd.GetOutput())

        ap.Update()


        xfm = vtk.vtkTransform()
        xfm.Translate(200, dist_fringes[1], dist_fringes[2])

        xfmPd = vtk.vtkTransformPolyDataFilter()
        xfmPd.SetInput(ap.GetOutput())
        xfmPd.SetTransform(xfm)

        cube_mapper=vtk.vtkPolyDataMapper()
        cube_mapper.SetInput(xfmPd.GetOutput())


        fringes_actor = vtk.vtkActor()
        fringes_actor.SetMapper(cube_mapper)
        fringes_actor.GetProperty().SetColor(1,0,0)

        fringesKeyProperties=vtk.vtkInformation()
        fringesKeyProperties.Set(vtk.vtkShadowMapBakerPass.OCCLUDER(),0) #// dummy val.
        fringesKeyProperties.Set(vtk.vtkShadowMapBakerPass.RECEIVER(),0) #// dummy val.
        fringes_actor.SetPropertyKeys(fringesKeyProperties)

        self.renderer.AddActor(fringes_actor)
        
        self.renderer.LightFollowCameraOff()
        self.renderer.AutomaticLightCreationOff()
        self.renderer.RemoveAllLights()
        self.renderer.UpdateLights()

        l = vtk.vtkLight()
        l.SetLightTypeToSceneLight()

        dist_light = cam_pos - vn * 6

        l.SetFocalPoint(vcam_f[0], vcam_f[1], vcam_f[2])
        l.SetPosition(220, dist_light[1], dist_light[2])
        l.PositionalOn()
        self.renderer.AddLight(l)
    
        self.renderer.Render()

        wf = vtk.vtkWindowToImageFilter()
        wf.SetInput(self.ren_win)
        wf.Update()

        png = vtk.vtkPNGWriter()
        png.SetFileName(file_output + ".png")
        png.SetInput(wf.GetOutput())
        png.Write()
Beispiel #45
0
    def contour_smooth(vol, voxsz=(1.0, 1.0, 1.0), affine=None, levels=[50],
                       colors=[np.array([1.0, 0.0, 0.0])], opacities=[0.5], smoothing=10):
        """ Take a volume and draw surface contours for any any number of
        thresholds (levels) where every contour has its own color and opacity

        Parameters
        ----------
        vol : (N, M, K) ndarray
            An array representing the volumetric dataset for which we will draw
            some beautiful contours .
        voxsz : (3,) array_like
            Voxel size.
        affine : None
            Not used.
        levels : array_like
            Sequence of thresholds for the contours taken from image values needs
            to be same datatype as `vol`.
        colors : (N, 3) ndarray
            RGB values in [0,1].
        opacities : array_like
            Opacities of contours.

        Returns
        -------
        vtkAssembly

        Examples
        --------
        >>> import numpy as np
        >>> from dipy.viz import fvtk
        >>> A=np.zeros((10,10,10))
        >>> A[3:-3,3:-3,3:-3]=1
        >>> r=fvtk.ren()
        >>> fvtk.add(r,fvtk.contour(A,levels=[1]))
        >>> #fvtk.show(r)

        """
        major_version = vtk.vtkVersion.GetVTKMajorVersion()

        im = vtk.vtkImageData()
        if major_version <= 5:
            im.SetScalarTypeToUnsignedChar()

        im.SetDimensions(vol.shape[0], vol.shape[1], vol.shape[2])
        # im.SetOrigin(0,0,0)
        # im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])
        if major_version <= 5:
            im.AllocateScalars()
        else:
            im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 3)

        for i in range(vol.shape[0]):
            for j in range(vol.shape[1]):
                for k in range(vol.shape[2]):
                    im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])

        ass = vtk.vtkAssembly()
        # ass=[]

        for (i, l) in enumerate(levels):

            # print levels
            skinExtractor = vtk.vtkContourFilter()
            if major_version <= 5:
                skinExtractor.SetInput(im)
            else:
                skinExtractor.SetInputData(im)
            skinExtractor.SetValue(0, l)

            #
            # Smoothing
            # Taken from: https://lorensen.github.io/VTKExamples/site/Python/MeshLabelImageColor/
            #
            smoother = vtk.vtkWindowedSincPolyDataFilter()
            if vtk.VTK_MAJOR_VERSION <= 5:
                smoother.SetInput(skinExtractor.GetOutput())
            else:
                smoother.SetInputConnection(skinExtractor.GetOutputPort())
            smoother.SetNumberOfIterations(smoothing)  # 30  # this has little effect on the error!
            # smoother.BoundarySmoothingOff()
            # smoother.FeatureEdgeSmoothingOff()
            # smoother.SetFeatureAngle(120.0)
            # smoother.SetPassBand(.001)        #this increases the error a lot!
            smoother.NonManifoldSmoothingOn()
            smoother.NormalizeCoordinatesOn()
            smoother.GenerateErrorScalarsOn()
            # smoother.GenerateErrorVectorsOn()
            smoother.Update()

            skinNormals = vtk.vtkPolyDataNormals()
            skinNormals.SetInputConnection(smoother.GetOutputPort())
            skinNormals.SetFeatureAngle(60.0)

            # No Smoothing
            # skinNormals = vtk.vtkPolyDataNormals()
            # skinNormals.SetInputConnection(skinExtractor.GetOutputPort())
            # skinNormals.SetFeatureAngle(60.0)

            skinMapper = vtk.vtkPolyDataMapper()
            skinMapper.SetInputConnection(skinNormals.GetOutputPort())
            skinMapper.ScalarVisibilityOff()

            skin = vtk.vtkActor()

            skin.SetMapper(skinMapper)
            skin.GetProperty().SetOpacity(opacities[i])

            # print colors[i]
            skin.GetProperty().SetColor(colors[i][0], colors[i][1], colors[i][2])
            # skin.Update()
            ass.AddPart(skin)

            del skin
            del skinMapper
            del skinExtractor

        return ass
    def Execute(self):

        if self.GaussFiltering:
            gauss = vtk.vtkImageGaussianSmooth()
            gauss.SetInput(self.Image)
            gauss.SetStandardDeviations(self.StandardDeviations)
            gauss.SetRadiusFactors(self.RadiusFactors)
            if self.Shape.find('2d') != -1:
                gauss.SetDimensionality(2)
            elif self.Shape.find('3d') != -1:
                gauss.SetDimensionality(3)
            else:
                gauss.SetDimensionality(3)
            gauss.Update()
            self.Image = gauss.GetOutput()

        scalarRange = [0.0,0.0]
        if self.FWHMRegion == 'image':
            scalarRange = self.Image.GetScalarRange()
        elif self.FWHMRegion == 'midline':
            extent = self.Image.GetWholeExtent()
            newYExtent = extent[2]+(extent[3]-extent[2])/2
            clip = vtk.vtkImageClip()
            clip.SetInput(self.Image)
            clip.SetOutputWholeExtent(extent[0],extent[1],newYExtent,newYExtent,extent[4],extent[5])
            clip.ClipDataOn()
            clip.Update()
            scalarRange = clip.GetOutput().GetScalarRange()

        self.FWHMLevel = (scalarRange[1] - scalarRange[0]) * self.FWHMRatio + scalarRange[0]
        if self.FWHMBackground != None:
            self.FWHMLevel = (scalarRange[1] - self.FWHMBackground) * self.FWHMRatio + self.FWHMBackground

        if self.Method == 'levelsets':
            if self.Shape.find('2d') != -1:
                gradientMagnitude = vtk.vtkImageGradientMagnitude()
                gradientMagnitude.SetDimensionality(2)
            elif self.Shape.find('3d') != -1:
                if self.FeatureImageType == 'gradient':
                    gradientMagnitude = vtkvmtk.vtkvmtkGradientMagnitudeImageFilter()
                elif self.FeatureImageType == 'upwind':
                    gradientMagnitude = vtkvmtk.vtkvmtkUpwindGradientMagnitudeImageFilter()
                    gradientMagnitude.SetUpwindFactor(self.UpwindFactor)
                else:
                    self.PrintError('Unsupported feature image type: choices are "gradient", "upwind".')
                    return
            else:
                gradientMagnitude = vtk.vtkImageGradientMagnitude()
            gradientMagnitude.SetInput(self.Image)
            gradientMagnitude.Update()
            boundedReciprocal = vtkvmtk.vtkvmtkBoundedReciprocalImageFilter()
            boundedReciprocal.SetInput(gradientMagnitude.GetOutput())
            boundedReciprocal.Update()
            self.FeatureImage = vtk.vtkImageData()
            self.FeatureImage.DeepCopy(boundedReciprocal.GetOutput())
            levelSetsFilter = None
            if self.Shape.find('2d') != -1:
                levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSet2DImageFilter()
            elif self.Shape.find('3d') != -1:
                levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter()
            else:
                levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter()
            levelSetsFilter.SetInput(self.Image)
            levelSetsFilter.SetFeatureImage(boundedReciprocal.GetOutput())
            levelSetsFilter.SetDerivativeSigma(0.0)
            levelSetsFilter.SetAutoGenerateSpeedAdvection(1)
            levelSetsFilter.SetNumberOfIterations(self.LevelSetsIterations)
            levelSetsFilter.SetPropagationScaling(0.0)
            levelSetsFilter.SetCurvatureScaling(self.CurvatureScaling)
            levelSetsFilter.SetAdvectionScaling(1.0)
            levelSetsFilter.SetIsoSurfaceValue(self.FWHMLevel)
            levelSetsFilter.SetInterpolateSurfaceLocation(1)
            levelSetsFilter.SetMaximumRMSError(1E-10)
            levelSetsFilter.Update()

            self.LevelSets = vtk.vtkImageData()
            self.LevelSets.DeepCopy(levelSetsFilter.GetOutput())

            contourFilter = vtk.vtkMarchingContourFilter()
            contourFilter.SetInput(self.LevelSets)
            contourFilter.SetValue(0,0.0)
            contourFilter.Update()

            self.Contour = contourFilter.GetOutput()

        elif self.Method == 'fwhm':
            contourFilter = vtk.vtkMarchingContourFilter()
            contourFilter.SetInput(self.Image)
            contourFilter.SetValue(0,self.FWHMLevel)
            contourFilter.Update()

            self.Contour = contourFilter.GetOutput()
        else:
            self.PrintError('Unsupported method: choices are "levelsets", "fwhm".')
            return


        if self.Smoothing:
            smoothingFilter = vtk.vtkWindowedSincPolyDataFilter()
            smoothingFilter.SetInput(self.Contour)
            smoothingFilter.SetNumberOfIterations(self.SmoothingIterations)
            smoothingFilter.SetPassBand(self.SmoothingPassBand)
            smoothingFilter.Update()
            self.Contour = smoothingFilter.GetOutput()

        measurementFilter = None

        if self.Shape is 'thickplane2d':
            measurementFilter = femri2DPlaneThickness()
        elif self.Shape is 'cylinder2d':
            measurementFilter = femri2DCylinderThickness()
        elif self.Shape is 'hollowcylinder2d':
            measurementFilter = femri2DHollowCylinderThickness()
        elif self.Shape is 'cylinder3d':
            measurementFilter = femri3DCylinderThickness()
        else:
            self.PrintError('Unsupported shape: choices are "thickplane2d", "cylinder2d", "hollowcylinder2d", "cylinder3d".')
            return

        measurementFilter.Contour = self.Contour
        measurementFilter.Center = self.Center
        measurementFilter.TiltingAngle = math.radians(self.TiltingAngle)
        measurementFilter.RotationAngle = math.radians(self.RotationAngle)
        measurementFilter.Execute()

        if self.Shape is 'hollowcylinder2d':
            measurementFilter.ComputeAreas()
            self.InnerArea = measurementFilter.InnerArea
            self.OuterArea = measurementFilter.OuterArea

        self.Thickness = measurementFilter.Thickness
        self.Thickness3D = measurementFilter.Thickness3D
        self.Locations = measurementFilter.Locations

        self.Contour = measurementFilter.Contour
  
        self.OutputText('\n')
        self.OutputText('Thickness: ' + str(self.Thickness) + '\n')
        self.OutputText('Thickness3D: ' + str(self.Thickness3D) + '\n')
        self.OutputText('Locations: ' + str(self.Locations) + '\n')
        if self.Shape is 'hollowcylinder2d':
            self.OutputText('InnerArea: ' + str(self.InnerArea) + '\n')
            self.OutputText('OuterArea: ' + str(self.OuterArea) + '\n')
        self.OutputText('\n')
Beispiel #47
0
  def applyFilters(self, state):

    surface = None
    surface = state.inputModelNode.GetPolyDataConnection()

    if state.decimation:
      triangle = vtk.vtkTriangleFilter()
      triangle.SetInputConnection(surface)
      decimation = vtk.vtkDecimatePro()
      decimation.SetTargetReduction(state.reduction)
      decimation.SetBoundaryVertexDeletion(state.boundaryDeletion)
      decimation.PreserveTopologyOn()
      decimation.SetInputConnection(triangle.GetOutputPort())
      surface = decimation.GetOutputPort()

    if state.smoothing:
      if state.smoothingMethod == "Laplace":
        smoothing = vtk.vtkSmoothPolyDataFilter()
        smoothing.SetBoundarySmoothing(state.boundarySmoothing)
        smoothing.SetNumberOfIterations(state.laplaceIterations)
        smoothing.SetRelaxationFactor(state.laplaceRelaxation)
        smoothing.SetInputConnection(surface)
        surface = smoothing.GetOutputPort()
      elif state.smoothingMethod == "Taubin":
        smoothing = vtk.vtkWindowedSincPolyDataFilter()
        smoothing.SetBoundarySmoothing(state.boundarySmoothing)
        smoothing.SetNumberOfIterations(state.taubinIterations)
        smoothing.SetPassBand(state.taubinPassBand)
        smoothing.SetInputConnection(surface)
        surface = smoothing.GetOutputPort()

    if state.normals:
      normals = vtk.vtkPolyDataNormals()
      normals.SetAutoOrientNormals(state.autoOrientNormals)
      normals.SetFlipNormals(state.flipNormals)
      normals.SetSplitting(state.splitting)
      normals.SetFeatureAngle(state.featureAngle)
      normals.ConsistencyOn()
      normals.SetInputConnection(surface)
      surface = normals.GetOutputPort()

    if state.mirror:
      mirrorTransformMatrix = vtk.vtkMatrix4x4()
      mirrorTransformMatrix.SetElement(0, 0, -1 if state.mirrorX else 1)
      mirrorTransformMatrix.SetElement(1, 1, -1 if state.mirrorY else 1)
      mirrorTransformMatrix.SetElement(2, 2, -1 if state.mirrorZ else 1)
      mirrorTransform = vtk.vtkTransform()
      mirrorTransform.SetMatrix(mirrorTransformMatrix)
      transformFilter = vtk.vtkTransformPolyDataFilter()
      transformFilter.SetInputConnection(surface)
      transformFilter.SetTransform(mirrorTransform)
      surface = transformFilter.GetOutputPort()
      if mirrorTransformMatrix.Determinant()<0:
        reverse = vtk.vtkReverseSense()
        reverse.SetInputConnection(surface)
        surface = reverse.GetOutputPort()

    if state.cleaner:
      cleaner = vtk.vtkCleanPolyData()
      cleaner.SetInputConnection(surface)
      surface = cleaner.GetOutputPort()

    if state.fillHoles:
      fillHoles = vtk.vtkFillHolesFilter()
      fillHoles.SetHoleSize(state.fillHolesSize)
      fillHoles.SetInputConnection(surface)
      # Need to auto-orient normals, otherwise holes
      # could appear to be unfilled when only front-facing elements
      # are chosen to be visible.
      normals = vtk.vtkPolyDataNormals()
      normals.AutoOrientNormalsOn()
      normals.ConsistencyOn()
      normals.SetInputConnection(fillHoles.GetOutputPort())
      surface = normals.GetOutputPort()

    if state.connectivity:
      connectivity = vtk.vtkPolyDataConnectivityFilter()
      connectivity.SetExtractionModeToLargestRegion()
      connectivity.SetInputConnection(surface)
      surface = connectivity.GetOutputPort()

    state.outputModelNode.SetPolyDataConnection(surface)
    return True
def image_to_vtk_polydata(img,considered_cells=None,mesh_center=None,coef=1.0,mesh_fineness=1.0):
    start_time = time()
    print "--> Generating vtk mesh from image"

    vtk_mesh = vtk.vtkPolyData()
    vtk_points = vtk.vtkPoints()
    vtk_triangles = vtk.vtkCellArray()
    vtk_cells = vtk.vtkLongArray()
    
    nx, ny, nz = img.shape
    data_string = img.tostring('F')

    reader = vtk.vtkImageImport()
    reader.CopyImportVoidPointer(data_string, len(data_string))
    if img.dtype == np.uint8:
        reader.SetDataScalarTypeToUnsignedChar()
    else:
        reader.SetDataScalarTypeToUnsignedShort()
    reader.SetNumberOfScalarComponents(1)
    reader.SetDataExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetWholeExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetDataSpacing(*img.resolution)

    if considered_cells is None:
        considered_cells = np.unique(img)[1:]

    if mesh_center is None:
        mesh_center = np.array(img.resolution)*np.array(img.shape)/2.

    marching_cube_start_time = time()
    print "  --> Marching Cubes"
    contour = vtk.vtkDiscreteMarchingCubes()
    SetInput(contour,reader.GetOutput())
    contour.ComputeNormalsOn()
    contour.ComputeGradientsOn()
    contour.ComputeScalarsOn()
    for i,label in enumerate(considered_cells):
        contour.SetValue(i,label)
    contour.Update()
    marching_cube_end_time = time()
    print "  <-- Marching Cubes : ",contour.GetOutput().GetPoints().GetNumberOfPoints()," Points,",contour.GetOutput().GetNumberOfCells()," Triangles, ",len(np.unique(img)[1:])," Cells [",marching_cube_end_time - marching_cube_start_time,"s]"

    marching_cubes = contour.GetOutput()

    marching_cubes_cell_data = marching_cubes.GetCellData().GetArray(0)

    triangle_cell_start_time = time()
    print "    --> Listing triangles"
    print "      - ",marching_cubes.GetNumberOfCells()," triangles"
    marching_cubes_triangles = np.sort([[marching_cubes.GetCell(t).GetPointIds().GetId(i) for i in xrange(3)] for t in xrange(marching_cubes.GetNumberOfCells())])   
    triangle_cell_end_time = time()
    print "    <-- Listing triangles            [",triangle_cell_end_time - triangle_cell_start_time,"s]"

    triangle_cell_start_time = time()
    print "    --> Listing triangle cells"
    triangle_cell = np.array([marching_cubes_cell_data.GetTuple(t)[0] for t in xrange(marching_cubes.GetNumberOfCells())],np.uint16)
    triangle_cell_end_time = time()
    print "    <-- Listing triangle cells     [",triangle_cell_end_time - triangle_cell_start_time,"s]"

    triangle_cell_start_time = time()
    print "    --> Updating marching cubes mesh"
    vtk_mesh = vtk.vtkPolyData()
    vtk_points = vtk.vtkPoints()
    vtk_triangles = vtk.vtkCellArray()
    vtk_cells = vtk.vtkLongArray()

    for label in considered_cells:

        # cell_start_time = time()

        cell_marching_cubes_triangles = marching_cubes_triangles[np.where(triangle_cell == label)]

        marching_cubes_point_ids = np.unique(cell_marching_cubes_triangles)

        marching_cubes_points = np.array([marching_cubes.GetPoints().GetPoint(p) for p in marching_cubes_point_ids])
        marching_cubes_center = marching_cubes_points.mean(axis=0)
        marching_cubes_points = marching_cubes_center + coef*(marching_cubes_points-marching_cubes_center) - mesh_center

        cell_points = []
        for p in xrange(marching_cubes_points.shape[0]):
            pid = vtk_points.InsertNextPoint(marching_cubes_points[p])
            cell_points.append(pid)
        cell_points = array_dict(cell_points,marching_cubes_point_ids)

        for t in xrange(cell_marching_cubes_triangles.shape[0]):
            poly = vtk_triangles.InsertNextCell(3)
            for i in xrange(3):
                pid = cell_marching_cubes_triangles[t][i]
                vtk_triangles.InsertCellPoint(cell_points[pid])
            vtk_cells.InsertValue(poly,label)

        # cell_end_time = time()
        # print "  --> Cell",label,":",cell_marching_cubes_triangles.shape[0],"triangles [",cell_end_time-cell_start_time,"s]"

    vtk_mesh.SetPoints(vtk_points)
    vtk_mesh.SetPolys(vtk_triangles)
    vtk_mesh.GetCellData().SetScalars(vtk_cells)

    triangle_cell_end_time = time()
    print "    <-- Updating marching cubes mesh [",triangle_cell_end_time - triangle_cell_start_time,"s]"

    decimation_start_time = time()
    print "  --> Decimation"
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    SetInput(smoother,vtk_mesh)
    smoother.SetFeatureAngle(30.0)
    smoother.SetPassBand(0.05)
    smoother.SetNumberOfIterations(25)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()

    decimate = vtk.vtkQuadricClustering()
    SetInput(decimate,smoother.GetOutput())
    decimate.SetNumberOfDivisions(*tuple(mesh_fineness*np.array(np.array(img.shape)*np.array(img.resolution)/2.,np.uint16)))
    decimate.SetFeaturePointsAngle(30.0)
    decimate.CopyCellDataOn()
    decimate.Update()

    decimation_end_time = time()
    print "  <-- Decimation     : ",decimate.GetOutput().GetPoints().GetNumberOfPoints()," Points,",decimate.GetOutput().GetNumberOfCells()," Triangles, ",len(considered_cells)," Cells [",decimation_end_time - decimation_start_time,"s]"

    end_time = time()
    print "<-- Generating vtk mesh from image      [",end_time-start_time,"s]"

    return decimate.GetOutput()
def image_to_vtk_cell_polydata(img,considered_cells=None,mesh_center=None,coef=1.0,mesh_fineness=1.0,smooth_factor=1.0):

    start_time = time()
    print "--> Generating vtk mesh from image"

    vtk_mesh = vtk.vtkPolyData()
    vtk_points = vtk.vtkPoints()
    vtk_triangles = vtk.vtkCellArray()
    vtk_cells = vtk.vtkLongArray()
    
    nx, ny, nz = img.shape
    data_string = img.tostring('F')

    reader = vtk.vtkImageImport()
    reader.CopyImportVoidPointer(data_string, len(data_string))
    if img.dtype == np.uint8:
        reader.SetDataScalarTypeToUnsignedChar()
    else:
        reader.SetDataScalarTypeToUnsignedShort()
    reader.SetNumberOfScalarComponents(1)
    reader.SetDataExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetWholeExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetDataSpacing(*img.resolution)
    reader.Update()

    if considered_cells is None:
        considered_cells = np.unique(img)[1:]

    if mesh_center is None:
        #mesh_center = np.array(img.resolution)*np.array(img.shape)/2.
        mesh_center = np.array([0,0,0])

    for label in considered_cells:

        cell_start_time = time()

        cell_volume = (img==label).sum()*np.array(img.resolution).prod()

        # mask_data = vtk.vtkImageThreshold()
        # mask_data.SetInputConnection(reader.GetOutputPort())
        # mask_data.ThresholdBetween(label, label)
        # mask_data.ReplaceInOn()
        # mask_data.SetInValue(label)
        # mask_data.SetOutValue(0)
        contour = vtk.vtkDiscreteMarchingCubes()
        # contour.SetInput(mask_data.GetOutput())
        SetInput(contour,reader.GetOutput())
        contour.ComputeNormalsOn()
        contour.ComputeGradientsOn()
        contour.SetValue(0,label)
        contour.Update()

        # print "    --> Marching Cubes : ",contour.GetOutput().GetPoints().GetNumberOfPoints()," Points,",contour.GetOutput().GetNumberOfCells()," Triangles,  1 Cell"

        # decimate = vtk.vtkDecimatePro()
        # decimate.SetInputConnection(contour.GetOutputPort())
        # # decimate.SetTargetReduction(0.75)
        # decimate.SetTargetReduction(0.66)
        # # decimate.SetTargetReduction(0.5)
        # # decimate.SetMaximumError(2*np.sqrt(3))
        # decimate.Update()

        smooth_iterations = int(np.ceil(smooth_factor*8.))

        smoother = vtk.vtkWindowedSincPolyDataFilter()
        SetInput(smoother,contour.GetOutput())
        smoother.BoundarySmoothingOn()
        # smoother.BoundarySmoothingOff()
        smoother.FeatureEdgeSmoothingOn()
        # smoother.FeatureEdgeSmoothingOff()
        smoother.SetFeatureAngle(120.0)
        # smoother.SetPassBand(1)
        smoother.SetPassBand(0.01)
        smoother.SetNumberOfIterations(smooth_iterations)
        smoother.NonManifoldSmoothingOn()
        smoother.NormalizeCoordinatesOn()
        smoother.Update()

        divisions = int(np.ceil(np.power(cell_volume,1/3.)*mesh_fineness))

        decimate = vtk.vtkQuadricClustering()
        # decimate = vtk.vtkQuadricDecimation()
        # decimate = vtk.vtkDecimatePro()
        # decimate.SetInput(contour.GetOutput())
        SetInput(decimate,smoother.GetOutput())
        # decimate.SetTargetReduction(0.95)
        # decimate.AutoAdjustNumberOfDivisionsOff()
        decimate.SetNumberOfDivisions(divisions,divisions,divisions)
        decimate.SetFeaturePointsAngle(120.0)
        # decimate.AttributeErrorMetricOn()
        # decimate.ScalarsAttributeOn()
        # decimate.PreserveTopologyOn()
        # decimate.CopyCellDataOn()
        # decimate.SetMaximumCost(1.0)
        # decimate.SetMaximumCollapsedEdges(10000.0)
        decimate.Update()

        # print "    --> Decimation     : ",decimate.GetOutput().GetPoints().GetNumberOfPoints()," Points,",decimate.GetOutput().GetNumberOfCells()," Triangles,  1 Cell"

        cell_polydata = decimate.GetOutput()
        # cell_polydata = smoother.GetOutput()

        polydata_points = np.array([cell_polydata.GetPoints().GetPoint(p) for p in xrange(cell_polydata.GetPoints().GetNumberOfPoints())])
        polydata_center = polydata_points.mean(axis=0)
        polydata_points = polydata_center + coef*(polydata_points-polydata_center) - mesh_center

        cell_points = []
        for p in xrange(cell_polydata.GetPoints().GetNumberOfPoints()):
            pid = vtk_points.InsertNextPoint(polydata_points[p])
            cell_points.append(pid)
        cell_points = array_dict(cell_points,np.arange(cell_polydata.GetPoints().GetNumberOfPoints()))

        for t in xrange(cell_polydata.GetNumberOfCells()):
            poly = vtk_triangles.InsertNextCell(3)
            for i in xrange(3):
                pid = cell_polydata.GetCell(t).GetPointIds().GetId(i)
                vtk_triangles.InsertCellPoint(cell_points[pid])
                vtk_cells.InsertValue(poly,label)

        cell_end_time = time()
        print "  --> Cell",label,":",decimate.GetOutput().GetNumberOfCells(),"triangles (",cell_volume," microm3 ) [",cell_end_time-cell_start_time,"s]"

    vtk_mesh.SetPoints(vtk_points)
    vtk_mesh.SetPolys(vtk_triangles)
    vtk_mesh.GetCellData().SetScalars(vtk_cells)

    print "  <-- Cell Mesh      : ",vtk_mesh.GetPoints().GetNumberOfPoints()," Points,",vtk_mesh.GetNumberOfCells()," Triangles, ",len(considered_cells)," Cells"

    end_time = time()
    print "<-- Generating vtk mesh from image      [",end_time-start_time,"s]"

    return vtk_mesh
Beispiel #50
0
line.SetPoint2(0, 1, 2)
line.SetResolution(10)

lineSweeper = vtk.vtkRotationalExtrusionFilter()
lineSweeper.SetResolution(20)
lineSweeper.SetInputConnection(line.GetOutputPort())
lineSweeper.SetAngle(270)

bump = vtk.vtkBrownianPoints()
bump.SetInputConnection(lineSweeper.GetOutputPort())

warp = vtk.vtkWarpVector()
warp.SetInputConnection(bump.GetOutputPort())
warp.SetScaleFactor(.2)

smooth = vtk.vtkWindowedSincPolyDataFilter()
smooth.SetInputConnection(warp.GetOutputPort())
smooth.SetNumberOfIterations(20)
smooth.BoundarySmoothingOn()
smooth.SetFeatureAngle(120)
smooth.SetEdgeAngle(90)
smooth.SetPassBand(0.1)

normals = vtk.vtkPolyDataNormals()
normals.SetInputConnection(smooth.GetOutputPort())

cylMapper = vtk.vtkPolyDataMapper()
cylMapper.SetInputConnection(normals.GetOutputPort())

cylActor = vtk.vtkActor()
cylActor.SetMapper(cylMapper)
  def smoothMultipleSegments(self):
    import vtkSegmentationCorePython as vtkSegmentationCore

    # Generate merged labelmap of all visible segments
    segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()
    visibleSegmentIds = vtk.vtkStringArray()
    segmentationNode.GetDisplayNode().GetVisibleSegmentIDs(visibleSegmentIds)
    if visibleSegmentIds.GetNumberOfValues() == 0:
      logging.info("Smoothing operation skipped: there are no visible segments")
      return

    mergedImage = vtkSegmentationCore.vtkOrientedImageData()
    if not segmentationNode.GenerateMergedLabelmapForAllSegments(mergedImage,
                                                                 vtkSegmentationCore.vtkSegmentation.EXTENT_UNION_OF_SEGMENTS_PADDED,
                                                                 None, visibleSegmentIds):
      logging.error('Failed to apply smoothing: cannot get list of visible segments')
      return

    segmentLabelValues = [] # list of [segmentId, labelValue]
    for i in range(visibleSegmentIds.GetNumberOfValues()):
      segmentId = visibleSegmentIds.GetValue(i)
      segmentLabelValues.append([segmentId, i+1])

    # Perform smoothing in voxel space
    ici = vtk.vtkImageChangeInformation()
    ici.SetInputData(mergedImage)
    ici.SetOutputSpacing(1, 1, 1)
    ici.SetOutputOrigin(0, 0, 0)

    # Convert labelmap to combined polydata
    # vtkDiscreteFlyingEdges3D cannot be used here, as in the output of that filter,
    # each labeled region is completely disconnected from neighboring regions, and
    # for joint smoothing it is essential for the points to move together.
    convertToPolyData = vtk.vtkDiscreteMarchingCubes()
    convertToPolyData.SetInputConnection(ici.GetOutputPort())
    convertToPolyData.SetNumberOfContours(len(segmentLabelValues))

    contourIndex = 0
    for segmentId, labelValue in segmentLabelValues:
      convertToPolyData.SetValue(contourIndex, labelValue)
      contourIndex += 1

    # Low-pass filtering using Taubin's method
    smoothingFactor = self.scriptedEffect.doubleParameter("JointTaubinSmoothingFactor")
    smoothingIterations = 100 #  according to VTK documentation 10-20 iterations could be enough but we use a higher value to reduce chance of shrinking
    passBand = pow(10.0, -4.0*smoothingFactor) # gives a nice range of 1-0.0001 from a user input of 0-1
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(convertToPolyData.GetOutputPort())
    smoother.SetNumberOfIterations(smoothingIterations)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(90.0)
    smoother.SetPassBand(passBand)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()

    # Extract a label
    threshold = vtk.vtkThreshold()
    threshold.SetInputConnection(smoother.GetOutputPort())

    # Convert to polydata
    geometryFilter = vtk.vtkGeometryFilter()
    geometryFilter.SetInputConnection(threshold.GetOutputPort())

    # Convert polydata to stencil
    polyDataToImageStencil = vtk.vtkPolyDataToImageStencil()
    polyDataToImageStencil.SetInputConnection(geometryFilter.GetOutputPort())
    polyDataToImageStencil.SetOutputSpacing(1,1,1)
    polyDataToImageStencil.SetOutputOrigin(0,0,0)
    polyDataToImageStencil.SetOutputWholeExtent(mergedImage.GetExtent())

    # Convert stencil to image
    stencil = vtk.vtkImageStencil()
    emptyBinaryLabelMap = vtk.vtkImageData()
    emptyBinaryLabelMap.SetExtent(mergedImage.GetExtent())
    emptyBinaryLabelMap.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
    vtkSegmentationCore.vtkOrientedImageDataResample.FillImage(emptyBinaryLabelMap, 0)
    stencil.SetInputData(emptyBinaryLabelMap)
    stencil.SetStencilConnection(polyDataToImageStencil.GetOutputPort())
    stencil.ReverseStencilOn()
    stencil.SetBackgroundValue(1) # General foreground value is 1 (background value because of reverse stencil)

    imageToWorldMatrix = vtk.vtkMatrix4x4()
    mergedImage.GetImageToWorldMatrix(imageToWorldMatrix)

    for segmentId, labelValue in segmentLabelValues:
      threshold.ThresholdBetween(labelValue, labelValue)
      stencil.Update()
      smoothedBinaryLabelMap = vtkSegmentationCore.vtkOrientedImageData()
      smoothedBinaryLabelMap.ShallowCopy(stencil.GetOutput())
      smoothedBinaryLabelMap.SetImageToWorldMatrix(imageToWorldMatrix)
      # Write results to segments directly, bypassing masking
      slicer.vtkSlicerSegmentationsModuleLogic.SetBinaryLabelmapToSegment(smoothedBinaryLabelMap,
        segmentationNode, segmentId, slicer.vtkSlicerSegmentationsModuleLogic.MODE_REPLACE, smoothedBinaryLabelMap.GetExtent())