Exemplo n.º 1
0
    def surfaceRecon(self):
        pointSource = vtk.vtkProgrammableSource()

        def readPoints():
            output = pointSource.GetPolyDataOutput()
            #points = vtk.vtkPoints()
            output.SetPoints(self.vtkPoints)

        pointSource.SetExecuteMethod(readPoints)
        surf = vtk.vtkSurfaceReconstructionFilter()
        surf.SetInputConnection(pointSource.GetOutputPort())
        print(surf)
        contour = vtk.vtkContourFilter()
        contour.SetInputConnection(surf.GetOutputPort())
        contour.SetValue(0, 0.0)
        print(contour)
        reverse = vtk.vtkReverseSense()
        reverse.SetInputConnection(contour.GetOutputPort())
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()
        contourMapper = vtk.vtkPolyDataMapper()
        contourMapper.SetInputConnection(reverse.GetOutputPort())
        contourMapper.ScalarVisibilityOff()
        print(contourMapper)
        contourActor = vtk.vtkActor()
        contourActor.SetMapper(contourMapper)
        print(contourActor)
        return contourActor
Exemplo n.º 2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkReverseSense(), 'Processing.',
         ('vtkPolyData',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemplo n.º 3
0
 def MakeGlyphs(src, normal_reverse, normal_arrowAtPoint):
     reverse = vtk.vtkReverseSense()
     maskPts = vtk.vtkMaskPoints()
     maskPts.SetOnRatio(1)
     if normal_reverse:
         reverse.SetInputData(src)
         reverse.ReverseCellsOn()
         reverse.ReverseNormalsOn()
         maskPts.SetInputConnection(reverse.GetOutputPort())
     else:
         maskPts.SetInputData(src)
     arrow = vtk.vtkArrowSource()
     if normal_arrowAtPoint:
         arrow.SetInvert(1)
     else: 
         arrow.SetInvert(0)
     arrow.SetTipResolution(16)
     arrow.SetTipLength(normal_length)
     arrow.SetTipRadius(normal_tip_radius)
     glyph = vtk.vtkGlyph3D()
     glyph.SetSourceConnection(arrow.GetOutputPort())
     glyph.SetInputConnection(maskPts.GetOutputPort())
     glyph.SetVectorModeToUseNormal()
     glyph.SetScaleFactor(normal_scale)
     if normal_scaleByPointScalar:
         glyph.SetScaleModeToScaleByScalar()
     else:
         glyph.SetScaleModeToScaleByVector()
     glyph.SetColorModeToColorByScalar()
     glyph.OrientOn()
     return glyph
Exemplo n.º 4
0
 def vtkPlotCenterline(self, vtkCenterLine):
    "Affichage de la centerline"
    
    self.ren.RemoveActor(self.centerlineActor)
    self.vtkRedraw()
    self.centerlineActor = None
    
    reverse = vtk.vtkReverseSense()
    reverse.SetInputConnection(vtkCenterLine.GetOutputPort())
    reverse.ReverseCellsOff()
    reverse.ReverseNormalsOff()
    
    self.centerLineMapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        self.centerLineMapper.SetInput(reverse.GetOutput())
    else:
        self.centerLineMapper.SetInputConnection(reverse.GetOutputPort())
    
    self.centerlineActor = vtk.vtkActor()
    self.centerlineActor.SetMapper(self.centerLineMapper)
    self.centerlineActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)
    self.centerlineActor.GetProperty().SetSpecularColor(1, 1, 1)
    self.centerlineActor.GetProperty().SetSpecular(.4)
    self.centerlineActor.GetProperty().SetSpecularPower(50)
    
    self.ren.AddActor(self.centerlineActor)
    self.vtkRedraw()
Exemplo n.º 5
0
def flipx(pd, c):
    """ flip mesh along x-axis and center c (only cx matters) """

    # setting up the transform (could be factorised if applied t o several subjects), but not a big overhead
    d = tuple([-x for x in c])

    transform = vtk.vtkTransform()
    transform.PostMultiply()
    transform.Translate(d)
    transform.Scale(-1, 1, 1)
    transform.Translate(c)

    t = vtk.vtkTransformPolyDataFilter()
    t.SetTransform(transform)

    rev = vtk.vtkReverseSense()

    # apply
    t.SetInputData(pd)
    t.Update()

    rev.SetInputData(t.GetOutput())
    rev.Update()

    return rev.GetOutput()
Exemplo n.º 6
0
 def reverse_lines(self, source):
     strip = vtk.vtkStripper()
     strip.SetInputData(source)
     strip.Update()
     reversed = vtk.vtkReverseSense()
     reversed.SetInputConnection(strip.GetOutputPort())
     reversed.Update()
     return reversed.GetOutput()
Exemplo n.º 7
0
    def createSymmetry(self, inputData, plane):
        normal = [0, 0, 0]
        origin = [0, 0, 0]
        plane.GetNormalWorld(normal)
        plane.GetOriginWorld(origin)

        vtkPlane = vtk.vtkPlane()
        vtkPlane.SetOrigin(origin)
        vtkPlane.SetNormal(normal)
        clipper = vtk.vtkClipPolyData()
        clipper.SetClipFunction(vtkPlane)
        clipper.SetInputData(inputData)
        clipper.Update()
        return cleanFilter.GetOutput()

        mirrorMatrix = vtk.vtkMatrix4x4()
        mirrorMatrix.SetElement(0, 0, 1 - 2 * normal[0] * normal[0])
        mirrorMatrix.SetElement(0, 1, -2 * normal[0] * normal[1])
        mirrorMatrix.SetElement(0, 2, -2 * normal[0] * normal[2])
        mirrorMatrix.SetElement(1, 0, -2 * normal[0] * normal[1])
        mirrorMatrix.SetElement(1, 1, 1 - 2 * normal[1] * normal[1])
        mirrorMatrix.SetElement(1, 2, -2 * normal[1] * normal[2])
        mirrorMatrix.SetElement(2, 0, -2 * normal[0] * normal[2])
        mirrorMatrix.SetElement(2, 1, -2 * normal[1] * normal[2])
        mirrorMatrix.SetElement(2, 2, 1 - 2 * normal[2] * normal[2])

        translateWorldToPlane = [0, 0, 0]
        vtk.vtkMath.Add(translateWorldToPlane, origin, translateWorldToPlane)
        translatePlaneOToWorld = [0, 0, 0]
        vtk.vtkMath.Add(translatePlaneOToWorld, origin, translatePlaneOToWorld)
        vtk.vtkMath.MultiplyScalar(translatePlaneOToWorld, -1)

        mirrorTransform = vtk.vtkTransform()
        mirrorTransform.SetMatrix(mirrorMatrix)
        mirrorTransform.PostMultiply()
        mirrorTransform.Identity()
        mirrorTransform.Translate(translatePlaneOToWorld)
        mirrorTransform.Concatenate(mirrorMatrix)
        mirrorTransform.Translate(translateWorldToPlane)
        mirrorFilter = vtk.vtkTransformFilter()
        mirrorFilter.SetTransform(mirrorTransform)
        mirrorFilter.SetInputConnection(clipper.GetOutputPort())

        reverseNormalFilter = vtk.vtkReverseSense()
        reverseNormalFilter.SetInputConnection(mirrorFilter.GetOutputPort())
        reverseNormalFilter.Update()

        appendFilter = vtk.vtkAppendPolyData()
        appendFilter.AddInputData(clipper.GetOutput())
        appendFilter.AddInputData(reverseNormalFilter.GetOutput())

        cleanFilter = vtk.vtkCleanPolyData()
        cleanFilter.SetInputConnection(appendFilter.GetOutputPort())
        cleanFilter.Update()
        return cleanFilter.GetOutput()
Exemplo n.º 8
0
    def SetInput(self, sourcePolyData):
        mirror_transform = vtk.vtkTransform()
        mirror_transform.Scale(-1,1,1)
        transformer = vtk.vtkTransformPolyDataFilter()
        transformer.SetTransform(mirror_transform)
        transformer.SetInput(sourcePolyData)
        rev = vtk.vtkReverseSense()
        rev.SetInput(transformer.GetOutput())

        self.AddInput(rev.GetOutput())
        self.AddInput(sourcePolyData)
Exemplo n.º 9
0
    def SetInput(self, sourcePolyData):
        mirror_transform = vtk.vtkTransform()
        mirror_transform.Scale(-1, 1, 1)
        transformer = vtk.vtkTransformPolyDataFilter()
        transformer.SetTransform(mirror_transform)
        transformer.SetInput(sourcePolyData)
        rev = vtk.vtkReverseSense()
        rev.SetInput(transformer.GetOutput())

        self.AddInput(rev.GetOutput())
        self.AddInput(sourcePolyData)
Exemplo n.º 10
0
def reverse_normals(grid):
    polydata_filter = vtk.vtkGeometryFilter()
    polydata_filter.SetInputData(grid)
    polydata_filter.Update()
    polydata = polydata_filter.GetOutput()

    reverse = vtk.vtkReverseSense()
    reverse.ReverseCellsOn()
    reverse.SetInputData(polydata)
    reverse.Update()
    return reverse.GetOutput()
Exemplo n.º 11
0
    def _labelmapToPolydata(labelmap, value=1):
        discreteCubes = vtk.vtkDiscreteMarchingCubes()
        discreteCubes.SetInputData(labelmap)
        discreteCubes.SetValue(0, value)

        reverse = vtk.vtkReverseSense()
        reverse.SetInputConnection(discreteCubes.GetOutputPort())
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()
        reverse.Update()

        return reverse.GetOutput()
Exemplo n.º 12
0
def mirror(flt):
    tr = vtk.vtkTransform()
    tr.Scale(-1, 1, 1)

    tp = vtk.vtkTransformPolyDataFilter()
    tp.SetTransform(tr)
    tp.SetInputConnection(flt.GetOutputPort())

    rs = vtk.vtkReverseSense()
    rs.SetInputConnection(tp.GetOutputPort())

    return rs
Exemplo n.º 13
0
def flipNormals(actor):  # N.B. input argument gets modified
    rs = vtk.vtkReverseSense()
    setInput(rs, polydata(actor, True))
    rs.ReverseNormalsOn()
    rs.Update()
    poly = rs.GetOutput()
    mapper = actor.GetMapper()
    setInput(mapper, poly)
    mapper.Update()
    actor.Modified()
    if hasattr(actor, 'poly'): actor.poly = poly
    return actor  # return same obj for concatenation
Exemplo n.º 14
0
    def reconstruct(self):
        # Read some points. Use a programmable filter to read them.
        # Construct the surface and create isosurface.
        surf = vtk.vtkSurfaceReconstructionFilter()
        surf.SetSampleSpacing(1)
        surf.SetInputConnection(self.pointSource.GetOutputPort())

        cf = vtk.vtkContourFilter()
        cf.SetInputConnection(surf.GetOutputPort())
        cf.SetValue(0, 0.0)

        # Sometimes the contouring algorithm can create a volume whose gradient
        # vector and ordering of polygon (using the right hand rule) are
        # inconsistent. vtkReverseSense cures this problem.
        reverse = vtk.vtkReverseSense()
        reverse.SetInputConnection(cf.GetOutputPort())
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()

        map = vtk.vtkPolyDataMapper()
        map.SetInputConnection(reverse.GetOutputPort())
        map.ScalarVisibilityOff()

        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(map)
        surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)
        surfaceActor.GetProperty().SetSpecularColor(1, 1, 1)
        surfaceActor.GetProperty().SetSpecular(.4)
        surfaceActor.GetProperty().SetSpecularPower(50)

        # Create the RenderWindow, Renderer and both Actors
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # Add the actors to the renderer, set the background and size
        ren.AddActor(surfaceActor)
        ren.SetBackground(1, 1, 1)
        renWin.SetSize(400, 400)
        ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
        ren.GetActiveCamera().SetPosition(1, 0, 0)
        ren.GetActiveCamera().SetViewUp(0, 0, 1)
        ren.ResetCamera()
        ren.GetActiveCamera().Azimuth(20)
        ren.GetActiveCamera().Elevation(30)
        ren.GetActiveCamera().Dolly(1.2)
        ren.ResetCameraClippingRange()

        return cf
    def marchingCubes(self, image, ijkToRasMatrix, threshold):


        transformIJKtoRAS = vtk.vtkTransform()
        transformIJKtoRAS.SetMatrix(ijkToRasMatrix)

        marchingCubes = vtk.vtkMarchingCubes()
        marchingCubes.SetInputData(image)
        marchingCubes.SetValue(0, threshold)
        marchingCubes.ComputeScalarsOn()
        marchingCubes.ComputeGradientsOn()
        marchingCubes.ComputeNormalsOn()
        marchingCubes.ReleaseDataFlagOn()
        marchingCubes.Update()


        if transformIJKtoRAS.GetMatrix().Determinant() < 0:
            reverser = vtk.vtkReverseSense()
            reverser.SetInputData(marchingCubes.GetOutput())
            reverser.ReverseNormalsOn()
            reverser.ReleaseDataFlagOn()
            reverser.Update()
            correctedOutput = reverser.GetOutput()
        else:
            correctedOutput = marchingCubes.GetOutput()

        transformer = vtk.vtkTransformPolyDataFilter()
        transformer.SetInputData(correctedOutput)
        transformer.SetTransform(transformIJKtoRAS)
        transformer.ReleaseDataFlagOn()
        transformer.Update()

        normals = vtk.vtkPolyDataNormals()
        normals.ComputePointNormalsOn()
        normals.SetInputData(transformer.GetOutput())
        normals.SetFeatureAngle(60)
        normals.SetSplitting(1)
        normals.ReleaseDataFlagOn()
        normals.Update()

        stripper = vtk.vtkStripper()
        stripper.SetInputData(normals.GetOutput())
        stripper.ReleaseDataFlagOff()
        stripper.Update()
        stripper.GetOutput()

        result = vtk.vtkPolyData()
        result.DeepCopy(stripper.GetOutput())

        return result
    def marchingCubes(self, image, ijkToRasMatrix, threshold):


        transformIJKtoRAS = vtk.vtkTransform()
        transformIJKtoRAS.SetMatrix(ijkToRasMatrix)

        marchingCubes = vtk.vtkMarchingCubes()
        marchingCubes.SetInputData(image)
        marchingCubes.SetValue(0, threshold)
        marchingCubes.ComputeScalarsOn()
        marchingCubes.ComputeGradientsOn()
        marchingCubes.ComputeNormalsOn()
        marchingCubes.ReleaseDataFlagOn()
        marchingCubes.Update()


        if transformIJKtoRAS.GetMatrix().Determinant() < 0:
            reverser = vtk.vtkReverseSense()
            reverser.SetInputData(marchingCubes.GetOutput())
            reverser.ReverseNormalsOn()
            reverser.ReleaseDataFlagOn()
            reverser.Update()
            correctedOutput = reverser.GetOutput()
        else:
            correctedOutput = marchingCubes.GetOutput()

        transformer = vtk.vtkTransformPolyDataFilter()
        transformer.SetInputData(correctedOutput)
        transformer.SetTransform(transformIJKtoRAS)
        transformer.ReleaseDataFlagOn()
        transformer.Update()

        normals = vtk.vtkPolyDataNormals()
        normals.ComputePointNormalsOn()
        normals.SetInputData(transformer.GetOutput())
        normals.SetFeatureAngle(60)
        normals.SetSplitting(1)
        normals.ReleaseDataFlagOn()
        normals.Update()

        stripper = vtk.vtkStripper()
        stripper.SetInputData(normals.GetOutput())
        stripper.ReleaseDataFlagOff()
        stripper.Update()
        stripper.GetOutput()

        result = vtk.vtkPolyData()
        result.DeepCopy(stripper.GetOutput())

        return result
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create source
        source = vtk.vtkSphereSource()
        #source = vtk.vtkConeSource()
        source.Update()

        polydata = vtk.vtkPolyData()
        polydata.SetPoints(source.GetOutput().GetPoints())

        # Construct the surface the create isosurface
        surf = vtk.vtkSurfaceReconstructionFilter()
        surf.SetInput(polydata)

        cf = vtk.vtkContourFilter()
        cf.SetInputConnection(surf.GetOutputPort())
        cf.SetValue(0, 0.0)

        # Sometimes the contouring algorithm can create a volumn whose gradient
        # vector and ordering of polygon (using the right hand rule) are
        # inconsistent, vetReverseSense cures this problem.
        reverse = vtk.vtkReverseSense()
        reverse.SetInputConnection(cf.GetOutputPort())
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(reverse.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Exemplo n.º 18
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create source
        source = vtk.vtkSphereSource()
        #source = vtk.vtkConeSource()
        source.Update()

        polydata = vtk.vtkPolyData()
        polydata.SetPoints(source.GetOutput().GetPoints())

        # Construct the surface the create isosurface
        surf = vtk.vtkSurfaceReconstructionFilter()
        surf.SetInput(polydata)

        cf = vtk.vtkContourFilter()
        cf.SetInputConnection(surf.GetOutputPort())
        cf.SetValue(0, 0.0)

        # Sometimes the contouring algorithm can create a volumn whose gradient
        # vector and ordering of polygon (using the right hand rule) are
        # inconsistent, vetReverseSense cures this problem.
        reverse = vtk.vtkReverseSense()
        reverse.SetInputConnection(cf.GetOutputPort())
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(reverse.GetOutputPort())

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
    def createSurface(self, points):

        surf = vtk.vtkSurfaceReconstructionFilter()
        surf.SetInputConnection(points.GetOutputPort())

        cf = vtk.vtkContourFilter()
        cf.SetInputConnection(surf.GetOutputPort())
        cf.SetValue(0, 0.0)

        reverse = vtk.vtkReverseSense()
        reverse.SetInputConnection(cf.GetOutputPort())
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()
        reverse.Update()

        return reverse
Exemplo n.º 20
0
def to_vtk_files():
    reader = vtk.vtkXMLUnstructuredGridReader()
    writer = vtk.vtkXMLUnstructuredGridWriter()

    for i in range(77):
        reader.SetFileName('proteus_vtu/proteus_{}.vtu'.format(i))
        reader.Update()

        grid = reader.GetOutput()

        # Extract boundaries
        boundaries_filter = vtk.vtkGeometryFilter()
        boundaries_filter.SetInputData(grid)
        # boundaries_filter.ComputeNormalsOff()
        # boundaries_filter.ComputeGradientsOff()
        # boundaries_filter.ComputeScalarsOff()
        # boundaries_filter.GenerateTrianglesOn()
        boundaries_filter.Update()
        boundaries = boundaries_filter.GetOutput()

        # Reverse cells indexing (for reversing the normals)
        reverse_normals = vtk.vtkReverseSense()
        reverse_normals.ReverseCellsOn()
        reverse_normals.ReverseNormalsOn()
        reverse_normals.SetInputData(boundaries)
        reverse_normals.Update()
        reversed_normals = reverse_normals.GetOutput()

        # Compute the cell normals (this is needed otherwise ReverseSense seems
        # to compute point normals)
        # compute_cell_normals = vtk.vtkPolyDataNormals()
        # compute_cell_normals.ComputePointNormalsOff()  # Flat shading in shaders
        # compute_cell_normals.ComputeCellNormalsOn()
        # compute_cell_normals.SetInputData(reversed_normals)
        # computed_cell_normals = compute_cell_normals.GetOutput()

        # Extract the unstructured grid
        ugrid_filter = vtk.vtkAppendFilter()
        ugrid_filter.SetInputData(reversed_normals)
        ugrid_filter.Update()
        unstructured_grid = ugrid_filter.GetOutput()

        writer.SetInputData(unstructured_grid)
        writer.SetFileName('proteus_vtu/proteus_boundaries_{}.vtu'.format(i))

        writer.Write()
Exemplo n.º 21
0
 def vtkImportSTLfile(self, path):
    """ Importation d'un fichier stl """
    stlReader = vtk.vtkSTLReader()
    stlReader.SetFileName(path)
    stlReader.Update()
    
    reverse = vtk.vtkReverseSense()
    reverse.SetInputConnection(stlReader.GetOutputPort())
    reverse.ReverseCellsOn()
    reverse.ReverseNormalsOn()
    
    self.meshMapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        self.meshMapper.SetInput(reverse.GetOutput())
    else:
        self.meshMapper.SetInputConnection(reverse.GetOutputPort())
    self.vtkPlotSTLMesh()
Exemplo n.º 22
0
def MakeGlyphs(src, reverseNormals):
    '''
    Glyph the normals on the surface.

    You may need to adjust the parameters for maskPts, arrow and glyph for a
    nice appearance.

    :param: src - the surface to glyph.
    :param: reverseNormals - if True the normals on the surface are reversed.
    :return: The glyph object.

    '''
    # Sometimes the contouring algorithm can create a volume whose gradient
    # vector and ordering of polygon (using the right hand rule) are
    # inconsistent. vtkReverseSense cures this problem.
    reverse = vtk.vtkReverseSense()

    # Choose a random subset of points.
    maskPts = vtk.vtkMaskPoints()
    maskPts.SetOnRatio(5)
    maskPts.RandomModeOn()
    if reverseNormals:
        reverse.SetInputData(src)
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()
        maskPts.SetInputConnection(reverse.GetOutputPort())
    else:
        maskPts.SetInputData(src)

    # Source for the glyph filter
    arrow = vtk.vtkArrowSource()
    arrow.SetTipResolution(16)
    arrow.SetTipLength(0.3)
    arrow.SetTipRadius(0.1)

    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(arrow.GetOutputPort())
    glyph.SetInputConnection(maskPts.GetOutputPort())
    glyph.SetVectorModeToUseNormal()
    glyph.SetScaleFactor(1)
    glyph.SetColorModeToColorByVector()
    glyph.SetScaleModeToScaleByVector()
    glyph.OrientOn()
    glyph.Update()
    return glyph
def MakeGlyphs(src, reverseNormals):
    '''
    Glyph the normals on the surface.

    You may need to adjust the parameters for maskPts, arrow and glyph for a
    nice appearance.

    :param: src - the surface to glyph.
    :param: reverseNormals - if True the normals on the surface are reversed.
    :return: The glyph object.

    '''
    # Sometimes the contouring algorithm can create a volume whose gradient
    # vector and ordering of polygon (using the right hand rule) are
    # inconsistent. vtkReverseSense cures this problem.
    reverse = vtk.vtkReverseSense()

    # Choose a random subset of points.
    maskPts = vtk.vtkMaskPoints()
    maskPts.SetOnRatio(5)
    maskPts.RandomModeOn()
    if reverseNormals:
        reverse.SetInputData(src)
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()
        maskPts.SetInputConnection(reverse.GetOutputPort())
    else:
        maskPts.SetInputData(src)

    # Source for the glyph filter
    arrow = vtk.vtkArrowSource()
    arrow.SetTipResolution(16)
    arrow.SetTipLength(0.3)
    arrow.SetTipRadius(0.1)

    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(arrow.GetOutputPort())
    glyph.SetInputConnection(maskPts.GetOutputPort())
    glyph.SetVectorModeToUseNormal()
    glyph.SetScaleFactor(1)
    glyph.SetColorModeToColorByVector()
    glyph.SetScaleModeToScaleByVector()
    glyph.OrientOn()
    glyph.Update()
    return glyph
Exemplo n.º 24
0
 def vtkCreateSTLMesh(self):
    """ Affichage d'un fichier mesh STL"""
    
    self.meshMapper = vtk.vtkReverseSense()
    #~ self.meshMapper.SetInputConnection(self.meshNormals.GetOutputPort())
    self.meshMapper.ReverseCellsOn()
    self.meshMapper.ReverseNormalsOn()
    
    self.STLMeshMapper = vtk.vtkPolyDataMapper()
    self.STLMeshMapper.SetInputConnection(self.meshMapper.GetOutputPort())
    
    self.meshNormals = vtk.vtkPolyDataNormals()
    self.meshNormals.SetInputConnection(self.STLMeshMapper.GetOutputPort())
    self.meshNormals.SetFeatureAngle(60.0)
    self.meshNormals.ComputeCellNormalsOn()
    self.meshNormals.ComputePointNormalsOn()
    self.meshNormals.ConsistencyOn()
    self.meshNormals.AutoOrientNormalsOn()
Exemplo n.º 25
0
def marchingCubes(volume) -> pv.PolyData:
    # use marching cube algorithm
    cf = vtk.vtkMarchingCubes()
    cf.SetInputData(volume)
    cf.SetValue(0, 1)
    cf.Update()

    # reverse the normal
    reverse = vtk.vtkReverseSense()
    reverse.SetInputConnection(cf.GetOutputPort())
    reverse.ReverseCellsOn()
    reverse.ReverseNormalsOn()

    reverse.Update()

    mesh = reverse.GetOutput()
    mesh = pv.wrap(mesh)
    return mesh
Exemplo n.º 26
0
def surfaceRecon(vtkPolyData):
    surf = vtk.vtkSurfaceReconstructionFilter()
    surf.SetInputData(vtkPolyData)
    print(surf)
    contour = vtk.vtkContourFilter()
    contour.SetInputConnection(surf.GetOutputPort())
    contour.SetValue(0, 0.0)
    print(contour)
    reverse = vtk.vtkReverseSense()
    reverse.SetInputConnection(contour.GetOutputPort())
    reverse.ReverseCellsOn()
    reverse.ReverseNormalsOn()
    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInputConnection(reverse.GetOutputPort())
    contourMapper.ScalarVisibilityOff()
    print(contourMapper)
    contourActor = vtk.vtkActor()
    contourActor.SetMapper(contourMapper)
    print(contourActor)
    return contourActor
Exemplo n.º 27
0
def reverse_sense_and_normals(vtk_algorithm_output):
    """
    Sometimes the contouring algorithm can create a volume whose gradient
    vector and ordering of polygon (using the right hand rule) are
    inconsistent. vtkReverseSense cures this problem.

    Args:
        vtk_algorithm_output (vtkAlgorithmOutput): output of a VTK algorithm,
            to get with: algorithm_instance.GetOutputPort()

    Returns:
        surface with reversed normals (vtk.vtkPolyData)
    """

    reverse = vtk.vtkReverseSense()
    reverse.SetInputConnection(vtk_algorithm_output)
    reverse.ReverseCellsOn()
    reverse.ReverseNormalsOn()
    reverse.Update()
    return reverse.GetOutput()
Exemplo n.º 28
0
  def transform(inputModel, outputModel, scaleX=1.0, scaleY=1.0, scaleZ=1.0, translateX=0.0, translateY=0.0, translateZ=0.0):
    """Mesh relaxation based on vtkWindowedSincPolyDataFilter.
    Scale of 1.0 means original size, >1.0 means magnification.
    """
    transform = vtk.vtkTransform()
    transform.Translate(translateX, translateY, translateZ)
    transform.Scale(scaleX, scaleY, scaleZ)
    transformFilter = vtk.vtkTransformFilter()
    transformFilter.SetInputData(inputModel.GetPolyData())
    transformFilter.SetTransform(transform)

    if transform.GetMatrix().Determinant() >= 0.0:
      transformFilter.Update()
      outputModel.SetAndObservePolyData(transformFilter.GetOutput())
    else:
      # The mesh is turned inside out, reverse the mesh cells to keep them facing outside
      reverse = vtk.vtkReverseSense()
      reverse.SetInputConnection(transformFilter.GetOutputPort())
      reverse.Update()
      outputModel.SetAndObservePolyData(reverse.GetOutput())
Exemplo n.º 29
0
    def threshold(self, value=None, flip=False):
        """
        Create a polygonal Mesh from a Picture by filling regions with pixels
        luminosity above a specified value.

        Parameters
        ----------
        value : float, optional
            The default is None, e.i. 1/3 of the scalar range.

        flip: bool, optional
            Flip polygon orientations

        Returns
        -------
        Mesh
            A polygonal mesh.
        """
        mgf = vtk.vtkImageMagnitude()
        mgf.SetInputData(self._data)
        mgf.Update()
        msq = vtk.vtkMarchingSquares()
        msq.SetInputData(mgf.GetOutput())
        if value is None:
            r0, r1 = self._data.GetScalarRange()
            value = r0 + (r1 - r0) / 3
        msq.SetValue(0, value)
        msq.Update()
        if flip:
            rs = vtk.vtkReverseSense()
            rs.SetInputData(msq.GetOutput())
            rs.ReverseCellsOn()
            rs.ReverseNormalsOff()
            rs.Update()
            output = rs.GetOutput()
        else:
            output = msq.GetOutput()
        ctr = vtk.vtkContourTriangulator()
        ctr.SetInputData(output)
        ctr.Update()
        return vedo.Mesh(ctr.GetOutput(), c='k').bc('t').lighting('off')
    def createPlaneModel(self, InputModel, plane, breastFlag):
        #this function creates a model (visual representation) of the defined plane

        #The input is linearly extruded to create a closed input model so that when the cutter extracts the
        # region it is large enough to create a plane to cover the entire breast
        closedInputModel = vtk.vtkLinearExtrusionFilter()
        closedInputModel.SetInputData(InputModel)
        closedInputModel.SetScaleFactor(100)
        closedInputModel.CappingOn()
        closedInputModel.Update()

        clippedInput = vtk.vtkClipPolyData()
        clippedInput.SetInputData(closedInputModel.GetOutput())
        clippedInput.SetClipFunction(plane)
        clippedInput.SetValue(0)
        clippedInput.SetInsideOut(breastFlag)
        clippedInput.Update()

        cutterPlane = vtk.vtkCutter()
        cutterPlane.SetCutFunction(plane)
        cutterPlane.SetInputData(clippedInput.GetOutput())
        cutterPlane.Update()

        cutterModel = vtk.vtkPolyData()
        cutterModel = cutterPlane.GetOutput()
        surfPlane = vtk.vtkSurfaceReconstructionFilter()
        surfPlane.SetInputData(cutterModel)
        surfPlane.SetSampleSpacing(2.5)

        cfPlane = vtk.vtkContourFilter()
        cfPlane.SetInputConnection(surfPlane.GetOutputPort())
        cfPlane.SetValue(0, 0.0)
        reversePlane = vtk.vtkReverseSense()
        reversePlane.SetInputConnection(cfPlane.GetOutputPort())
        reversePlane.ReverseCellsOn()
        reversePlane.ReverseNormalsOn()

        return reversePlane
Exemplo n.º 31
0
def vertices_to_surface(vertices, num_simplify_iter=3, smooth=True):

    polydata = mesh_to_polydata(vertices, [])

    surf = vtk.vtkSurfaceReconstructionFilter()
    surf.SetNeighborhoodSize(30)
    surf.SetSampleSpacing(5)
    surf.SetInputData(polydata)
    surf.Update()

    # Visualize signed distance function computed by VTK (VTK bug: error outside actual contour)
    # q = surf.GetOutput()
    # arr = numpy_support.vtk_to_numpy(q.GetPointData().GetScalars())
    # sc = arr.reshape(q.GetDimensions()[::-1])
    # plt.imshow(sc[40,:,:]);
    # plt.colorbar();

    cf = vtk.vtkContourFilter()
    cf.SetInputConnection(surf.GetOutputPort())
    cf.SetValue(0, 0.)
    # print cf.GetNumberOfContours()
    cf.Update()
    # polydata = cf.GetOutput()

    reverse = vtk.vtkReverseSense()
    reverse.SetInputConnection(cf.GetOutputPort())
    reverse.ReverseCellsOn()
    reverse.ReverseNormalsOn()
    reverse.Update()

    polydata = reverse.GetOutput()

    polydata = simplify_polydata(polydata,
                                 num_simplify_iter=num_simplify_iter,
                                 smooth=smooth)

    return polydata
Exemplo n.º 32
0
cowReader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/Viewpoint/cow.obj")
plane = vtk.vtkPlane()
plane.SetNormal(1, 0, 0)
cowClipper = vtk.vtkClipPolyData()
cowClipper.SetInputConnection(cowReader.GetOutputPort())
cowClipper.SetClipFunction(plane)
cellNormals = vtk.vtkPolyDataNormals()
cellNormals.SetInputConnection(cowClipper.GetOutputPort())
cellNormals.ComputePointNormalsOn()
cellNormals.ComputeCellNormalsOn()
reflect = vtk.vtkTransform()
reflect.Scale(-1, 1, 1)
cowReflect = vtk.vtkTransformPolyDataFilter()
cowReflect.SetTransform(reflect)
cowReflect.SetInputConnection(cellNormals.GetOutputPort())
cowReverse = vtk.vtkReverseSense()
cowReverse.SetInputConnection(cowReflect.GetOutputPort())
cowReverse.ReverseNormalsOn()
cowReverse.ReverseCellsOff()
reflectedMapper = vtk.vtkPolyDataMapper()
reflectedMapper.SetInputConnection(cowReverse.GetOutputPort())
reflected = vtk.vtkActor()
reflected.SetMapper(reflectedMapper)
reflected.GetProperty().SetDiffuseColor(flesh)
reflected.GetProperty().SetDiffuse(.8)
reflected.GetProperty().SetSpecular(.5)
reflected.GetProperty().SetSpecularPower(30)
reflected.GetProperty().FrontfaceCullingOn()
ren1.AddActor(reflected)
cowMapper = vtk.vtkPolyDataMapper()
cowMapper.SetInputConnection(cowClipper.GetOutputPort())
Exemplo n.º 33
0
	def addCSVFile(self,fname,csvDelimiter=None):
		self.setCaption(r' File:'+str(fname))
		pts=np.loadtxt(fname,csvDelimiter)
		r,t,z = rec2cyl(pts[:,0],pts[:,1],pts[:,2])
		sf=self.scalingFactor

		if pts.shape[1] == 4:
			im=pts[:,3]
		else:
			im=getGeomImperfection(r,z,np.mean(r))
		rid=r-im
		xx,yy,zz=cyl2rec(rid+im*sf,t,z)
		points = vtk.vtkPoints()

		colors =vtk.vtkUnsignedCharArray()
		colors.SetNumberOfComponents(3);
		colors.SetName("Colors");

		for i in range(0,pts.shape[0]):
			points.InsertPoint(i,xx[i],yy[i],zz[i] )
		polydata = vtk.vtkPolyData()
		polydata.SetPoints(points)
		polydata.GetPointData().SetScalars(colors)
		polydata.Update()

		surf =vtk.vtkSurfaceReconstructionFilter()
		surf.SetInput(polydata)
		surf.SetNeighborhoodSize(self.nbSize)
		surf.SetSampleSpacing(self.sampleSpacing)

		contourFilter = vtk.vtkContourFilter()
		contourFilter.SetInputConnection(surf.GetOutputPort())
		reverse = vtk.vtkReverseSense()
		reverse.SetInputConnection(contourFilter.GetOutputPort())
		reverse.ReverseCellsOn()
		reverse.ReverseNormalsOn()
		reverse.Update()

		outputPolyData=reverse.GetOutput()

		newSurf = self.transform_back( points, reverse.GetOutput());

		pts2=np.zeros((newSurf.GetNumberOfPoints(),3))
		for i in range(0,newSurf.GetNumberOfPoints()):
			pts2[i,:]=newSurf.GetPoint(i)

		r2,t2,z2 = rec2cyl(pts2[:,0],pts2[:,1],pts2[:,2])
		im2=getGeomImperfection(r2,z2,np.mean(r2))
		self.paint.setValue(np.min(im2))
		self.paint.setValue(np.max(im2))

		for i in range(0,newSurf.GetNumberOfPoints()):
			colors.InsertNextTupleValue(self.paint.getRGB(im2[i]))

		newSurf.GetPointData().SetScalars(colors );
		self.outputs.append(newSurf)

		mapper = vtk.vtkPolyDataMapper();
		mapper.InterpolateScalarsBeforeMappingOn()
		mapper.SetInputConnection(newSurf.GetProducerPort())
		mapper.SetScalarModeToUsePointData()
		mapper.ScalarVisibilityOn();

		surfaceActor = vtk.vtkActor();
		surfaceActor.SetMapper(mapper);

		self.ren.AddActor(surfaceActor);
Exemplo n.º 34
0
	def addCSVFile(self,fname,mode='folded',csvDelimiter=None):
		self.setCaption(r' File:'+str(fname))
		pts=np.loadtxt(fname,csvDelimiter)
				
		points = vtk.vtkPoints()
		r,t,z = rec2cyl(pts[:,0],pts[:,1],pts[:,2])
		im_g=getGeomImperfection(r,z,np.mean(r))

		if pts.shape[1] == 4:
			useThickImp=True
		else:
			useThickImp=False

		if useThickImp:
			im_t=pts[:,3]
		else:
			im_t=np.zeros(pts.shape[0])

		rid=r-im_g
		if mode == 'unfolded':
			tt=t*r.mean()
			rr=im_g*self.scalingFactor
			for i in range(0,pts.shape[0]):
				points.InsertPoint(i,tt[i],z[i],rr[i] )
		else:
			xx,yy,zz=cyl2rec(rid+im_g*self.scalingFactor,t,z)
			for i in range(0,pts.shape[0]):
				points.InsertPoint(i,xx[i],yy[i],zz[i] )
		
        	
		polydata = vtk.vtkPolyData()
		polydata.SetPoints(points)
		polydata.Update()

		if useThickImp:
			imps=im_t
		else:
			imps=im_g
#		imps=vtk.vtkFloatArray()
#		if useThickImp:
#			for i in range(0,polydata.GetNumberOfPoints()):
#				imps.InsertNextValue(im_t[i])
#		else:
#				imps.InsertNextValue(im_g[i])
#		polydata.GetPointData().SetScalars(imps);
#
		surf =vtk.vtkSurfaceReconstructionFilter()
		surf.SetInput(polydata)
		surf.SetNeighborhoodSize(self.nbSize)
		surf.SetSampleSpacing(self.sampleSpacing)

		contourFilter = vtk.vtkContourFilter()
		contourFilter.SetInputConnection(surf.GetOutputPort())
		reverse = vtk.vtkReverseSense()
		reverse.SetInputConnection(contourFilter.GetOutputPort())
		reverse.ReverseCellsOn()
		reverse.ReverseNormalsOn()
		reverse.Update()

		outputPolyData=reverse.GetOutput()

		newSurf = self.transform_back( points, reverse.GetOutput());

		pts2=np.zeros((newSurf.GetNumberOfPoints(),3))
		for i in range(0,newSurf.GetNumberOfPoints()):
			pts2[i,:]=newSurf.GetPoint(i)

		r2,t2,z2 = rec2cyl(pts2[:,0],pts2[:,1],pts2[:,2])

				
		kDTree = vtk.vtkKdTreePointLocator()
		kDTree.SetDataSet(polydata)
		kDTree.BuildLocator()

		colors=vtk.vtkFloatArray()
			
		for i in range(0,len(pts2)):
			kid=kDTree.FindClosestPoint(pts2[i])
			colors.InsertNextValue(imps[kid])	


#		if mode == 'folded':
#				im2=getGeomImperfection(r2,z2,np.mean(r2))/self.scalingFactor
#
#		if mode == 'unfolded':
#			im2=pts2[:,2]/self.scalingFactor
#
#		colors=vtk.vtkFloatArray()
#		for i in range(0,newSurf.GetNumberOfPoints()):
#			colors.InsertNextValue(im2[i])

		newSurf.GetPointData().SetScalars(colors);
        
		self.scalarRange=colors.GetRange()
        
		self.lut=vtk.vtkLookupTable()
		self.lut.SetNumberOfTableValues(100)
		self.lut.SetTableRange(self.scalarRange)
		self.lut.SetHueRange(0.667, 0.0)
		self.lut.Build()

		
		self.resP=newSurf.GetProducerPort()
		self.colors=colors
		self.outputs.append(newSurf)

		mapper = vtk.vtkPolyDataMapper();
		mapper.SetLookupTable(self.lut)
		mapper.InterpolateScalarsBeforeMappingOn()
		mapper.SetInputConnection(newSurf.GetProducerPort())
		mapper.SetScalarModeToUsePointData()
		mapper.ScalarVisibilityOn();
		mapper.SetScalarRange(colors.GetRange())
		surfaceActor = vtk.vtkActor();
		surfaceActor.SetMapper(mapper);

		self.boundBox=newSurf.GetBounds()
		self.ren.AddActor(surfaceActor);
Exemplo n.º 35
0
    def updateModelFromMarkup(self, inputMarkup, outputModel):
        """
    Update model to enclose all points in the input markup list
    """

        # Delaunay triangulation is robust and creates nice smooth surfaces from a small number of points,
        # however it can only generate convex surfaces robustly.
        useDelaunay = True

        # Create polydata point set from markup points

        points = vtk.vtkPoints()
        cellArray = vtk.vtkCellArray()

        numberOfPoints = inputMarkup.GetNumberOfFiducials()

        # Surface generation algorithms behave unpredictably when there are not enough points
        # return if there are very few points
        if useDelaunay:
            if numberOfPoints < 3:
                return
        else:
            if numberOfPoints < 10:
                return

        points.SetNumberOfPoints(numberOfPoints)
        new_coord = [0.0, 0.0, 0.0]

        for i in range(numberOfPoints):
            inputMarkup.GetNthFiducialPosition(i, new_coord)
            points.SetPoint(i, new_coord)

        cellArray.InsertNextCell(numberOfPoints)
        for i in range(numberOfPoints):
            cellArray.InsertCellPoint(i)

        pointPolyData = vtk.vtkPolyData()
        pointPolyData.SetLines(cellArray)
        pointPolyData.SetPoints(points)

        # Create surface from point set

        if useDelaunay:

            delaunay = vtk.vtkDelaunay3D()
            delaunay.SetInputData(pointPolyData)

            surfaceFilter = vtk.vtkDataSetSurfaceFilter()
            surfaceFilter.SetInputConnection(delaunay.GetOutputPort())

            smoother = vtk.vtkButterflySubdivisionFilter()
            smoother.SetInputConnection(surfaceFilter.GetOutputPort())
            smoother.SetNumberOfSubdivisions(3)
            smoother.Update()

            outputModel.SetPolyDataConnection(smoother.GetOutputPort())

        else:

            surf = vtk.vtkSurfaceReconstructionFilter()
            surf.SetInputData(pointPolyData)
            surf.SetNeighborhoodSize(20)
            surf.SetSampleSpacing(
                80
            )  # lower value follows the small details more closely but more dense pointset is needed as input

            cf = vtk.vtkContourFilter()
            cf.SetInputConnection(surf.GetOutputPort())
            cf.SetValue(0, 0.0)

            # Sometimes the contouring algorithm can create a volume whose gradient
            # vector and ordering of polygon (using the right hand rule) are
            # inconsistent. vtkReverseSense cures this problem.
            reverse = vtk.vtkReverseSense()
            reverse.SetInputConnection(cf.GetOutputPort())
            reverse.ReverseCellsOff()
            reverse.ReverseNormalsOff()

            outputModel.SetPolyDataConnection(reverse.GetOutputPort())

        # Create default model display node if does not exist yet
        if not outputModel.GetDisplayNode():
            modelDisplayNode = slicer.mrmlScene.CreateNodeByClass(
                "vtkMRMLModelDisplayNode")

            # Get color of edited segment
            segmentationNode = self.scriptedEffect.parameterSetNode(
            ).GetSegmentationNode()
            segmentID = self.scriptedEffect.parameterSetNode(
            ).GetSelectedSegmentID()
            r, g, b = segmentationNode.GetSegmentation().GetSegment(
                segmentID).GetColor()

            modelDisplayNode.SetColor(r, g, b)  # Edited segment color
            modelDisplayNode.BackfaceCullingOff()
            modelDisplayNode.SliceIntersectionVisibilityOn()
            modelDisplayNode.SetSliceIntersectionThickness(2)
            modelDisplayNode.SetOpacity(0.3)  # Between 0-1, 1 being opaque
            slicer.mrmlScene.AddNode(modelDisplayNode)
            outputModel.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())

        outputModel.GetDisplayNode().SliceIntersectionVisibilityOn()

        outputModel.Modified()
Exemplo n.º 36
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
Exemplo n.º 37
0
print('texture test')
assert isinstance(st.GetTexture(), vtk.vtkTexture)

###################################### deletePoints
sd = sphere.clone().deletePoints(range(100))
print('deletePoints', sd.N(), sphere.N())
assert sd.N() == sphere.N()
print('deletePoints', sd.NCells(), '<', sphere.NCells())
assert sd.NCells() < sphere.NCells()

###################################### reverse
# this fails on some archs (see issue #185)
# lets comment it out temporarily
sr = sphere.clone().reverse().cutWithPlane()
print('DISABLED: reverse test', sr.N(), 576)
rev = vtk.vtkReverseSense()
rev.SetInputData(sr.polydata())
rev.Update()
print(rev.GetOutput())
print('DISABLED: reverse vtk nr.pts, nr.cells')
print(
    rev.GetOutput().GetNumberOfPoints(),
    sr.polydata().GetNumberOfPoints(),
    rev.GetOutput().GetNumberOfCells(),
    sr.polydata().GetNumberOfCells(),
)
# assert sr.N() == 576

###################################### quantize
sq = sphere.clone().quantize(0.1)
print('quantize', sq.N(), 834)
Exemplo n.º 38
0
def reconstructSurface(folder):
    pointSource = vtk.vtkProgrammableSource()

    def readPoints():
            output = pointSource.GetPolyDataOutput()
            points = vtk.vtkPoints()
            output.SetPoints(points)

            group_points = groupsToPoints(folder)

            for p in group_points:
                points.insertNextPoint(p[0],p[1],p[2])

    pointSource.SetExecuteMethod(readPoints)


    # Construct the surface and create isosurface.
    surf = vtk.vtkSurfaceReconstructionFilter()
    surf.SetInputConnection(pointSource.GetOutputPort())

    cf = vtk.vtkContourFilter()
    cf.SetInputConnection(surf.GetOutputPort())
    cf.SetValue(0, 0.0)

    # Sometimes the contouring algorithm can create a volume whose gradient
    # vector and ordering of polygon (using the right hand rule) are
    # inconsistent. vtkReverseSense cures this problem.
    reverse = vtk.vtkReverseSense()
    reverse.SetInputConnection(cf.GetOutputPort())
    reverse.ReverseCellsOn()
    reverse.ReverseNormalsOn()

    map = vtk.vtkPolyDataMapper()
    map.SetInputConnection(reverse.GetOutputPort())
    map.ScalarVisibilityOff()

    surfaceActor = vtk.vtkActor()
    surfaceActor.SetMapper(map)
    surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)
    surfaceActor.GetProperty().SetSpecularColor(1, 1, 1)
    surfaceActor.GetProperty().SetSpecular(.4)
    surfaceActor.GetProperty().SetSpecularPower(50)

    # Create the RenderWindow, Renderer and both Actors
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size
    ren.AddActor(surfaceActor)
    ren.SetBackground(1, 1, 1)
    renWin.SetSize(400, 400)
    ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
    ren.GetActiveCamera().SetPosition(1, 0, 0)
    ren.GetActiveCamera().SetViewUp(0, 0, 1)
    ren.ResetCamera()
    ren.GetActiveCamera().Azimuth(20)
    ren.GetActiveCamera().Elevation(30)
    ren.GetActiveCamera().Dolly(1.2)
    ren.ResetCameraClippingRange()

    iren.Initialize()
    renWin.Render()
    iren.Start()
Exemplo n.º 39
0
    def testReconstructSurface(self):

        # Read some points. Use a programmable filter to read them.
        #
        pointSource = vtk.vtkProgrammableSource()

        def readPoints():

            fp = open(VTK_DATA_ROOT + "/Data/cactus.3337.pts", "r")

            points = vtk.vtkPoints()
            while True:
                line = fp.readline().split()
                if len(line) == 0:
                    break
                if line[0] == "p":
                    points.InsertNextPoint(float(line[1]), float(line[2]), float(line[3]))
            pointSource.GetPolyDataOutput().SetPoints(points)

        pointSource.SetExecuteMethod(readPoints)

        # Construct the surface and create isosurface
        #
        surf = vtk.vtkSurfaceReconstructionFilter()
        surf.SetInputConnection(pointSource.GetOutputPort())

        cf = vtk.vtkContourFilter()
        cf.SetInputConnection(surf.GetOutputPort())
        cf.SetValue(0, 0.0)

        reverse = vtk.vtkReverseSense()
        reverse.SetInputConnection(cf.GetOutputPort())
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()

        map = vtk.vtkPolyDataMapper()
        map.SetInputConnection(reverse.GetOutputPort())
        map.ScalarVisibilityOff()

        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(map)
        surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)
        surfaceActor.GetProperty().SetSpecularColor(1, 1, 1)
        surfaceActor.GetProperty().SetSpecular(.4)
        surfaceActor.GetProperty().SetSpecularPower(50)

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(surfaceActor)
        ren.SetBackground(1, 1, 1)
        renWin.SetSize(300, 300)
        ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
        ren.GetActiveCamera().SetPosition(1, 0, 0)
        ren.GetActiveCamera().SetViewUp(0, 0, 1)
        ren.ResetCamera()
        ren.GetActiveCamera().Azimuth(20)
        ren.GetActiveCamera().Elevation(30)
        ren.GetActiveCamera().Dolly(1.2)
        ren.ResetCameraClippingRange()

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "reconstructSurface.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemplo n.º 40
0
        points.InsertNextPoint(x, y, x*y+x)

pointSource.SetExecuteMethod(readPoints)

# Construct the surface and create isosurface.
surf = vtk.vtkSurfaceReconstructionFilter()
surf.SetInputConnection(pointSource.GetOutputPort())

cf = vtk.vtkContourFilter()
cf.SetInputConnection(surf.GetOutputPort())
cf.SetValue(0, 0.0)

# Sometimes the contouring algorithm can create a volume whose gradient
# vector and ordering of polygon (using the right hand rule) are
# inconsistent. vtkReverseSense cures this problem.
reverse = vtk.vtkReverseSense()
reverse.SetInputConnection(cf.GetOutputPort())
reverse.ReverseCellsOn()
reverse.ReverseNormalsOn()

map = vtk.vtkPolyDataMapper()
map.SetInputConnection(reverse.GetOutputPort())
map.ScalarVisibilityOff()

surfaceActor = vtk.vtkActor()
surfaceActor.SetMapper(map)
surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)
surfaceActor.GetProperty().SetSpecularColor(1, 1, 1)
surfaceActor.GetProperty().SetSpecular(.4)
surfaceActor.GetProperty().SetSpecularPower(50)
Exemplo n.º 41
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
Exemplo n.º 42
0
def myMain(controller,args):
	fname=args.fname
	controller=args.controller
	myid = controller.GetLocalProcessId();
	numProcs = controller.GetNumberOfProcesses();

	pts=np.loadtxt(fname)
	sf=100
	paint=rgbPainter()
	r,t,z = rec2cyl(pts[:,0],pts[:,1],pts[:,2])

	#im=np.abs(getGeomImperfection(r,z,np.mean(r)))
	if pts.shape[1] == 4:
		im=pts[:,3]
	else:
		im=getGeomImperfection(r,z,np.mean(r))
	rid=r-im
	xx,yy,zz=cyl2rec(rid+im*sf,t,z)


	math = vtk.vtkMath()
	points = vtk.vtkPoints()

	colors =vtk.vtkUnsignedCharArray()
	colors.SetNumberOfComponents(3);
	colors.SetName("Colors");

	for i in range(0,pts.shape[0]):
		#points.InsertPoint(i,pts[i][0],pts[i][1],pts[i][2] )
		points.InsertPoint(i,xx[i],yy[i],zz[i] )
	polydata = vtk.vtkPolyData()
	polydata.SetPoints(points)
	polydata.GetPointData().SetScalars(colors)
	polydata.Update()

	surf =vtk.vtkSurfaceReconstructionFilter()
	surf.SetInput(polydata)
	surf.SetNeighborhoodSize(40)
	#surf.SetSampleSpacing(6.0)
	if (myid != 0):
		controller.AddRMI(surf.Update,'',200)
		controller.ProcessRMIs();
	else:
		contourFilter = vtk.vtkContourFilter()
		contourFilter.SetInputConnection(surf.GetOutputPort())
		reverse = vtk.vtkReverseSense()
		reverse.SetInputConnection(contourFilter.GetOutputPort())
		reverse.ReverseCellsOn()
		reverse.ReverseNormalsOn()
		reverse.Update()


		outputPolyData=reverse.GetOutput()
		#for i in range(0,pts.shape[0]):
		#	dcolor=np.zeros(3)
		#	colorLookupTable.GetColor(im[i],dcolor)
		#	cc=dcolor*255.0
		#	colors.InsertNextTupleValue(cc)
		#outputPolyData.GetPointData().SetScalars(polydata.GetPointData().GetScalars() );



		newSurf = transform_back( points, reverse.GetOutput());

		pts2=np.zeros((newSurf.GetNumberOfPoints(),3))
		for i in range(0,newSurf.GetNumberOfPoints()):
			pts2[i,:]=newSurf.GetPoint(i)
		r2,t2,z2 = rec2cyl(pts2[:,0],pts2[:,1],pts2[:,2])
		im2=getGeomImperfection(r2,z2,np.mean(r2))
		#im2-=np.min(im2)
		#im2=np.abs(im2)
		paint.setValue(np.min(im2))
		paint.setValue(np.max(im2))


		for i in range(0,newSurf.GetNumberOfPoints()):
			colors.InsertNextTupleValue(paint.getRGB(im2[i]))

		newSurf.GetPointData().SetScalars(colors );

		mapper = vtk.vtkPolyDataMapper();
		mapper.InterpolateScalarsBeforeMappingOn()
		#mapper.SetInputConnection(outputPolyData.GetProducerPort())
		mapper.SetInputConnection(newSurf.GetProducerPort())
		mapper.SetScalarModeToUsePointData()
		mapper.ScalarVisibilityOn();

		surfaceActor = vtk.vtkActor();
		surfaceActor.SetMapper(mapper);

		ren = vtk.vtkRenderer();
		renWin = vtk.vtkRenderWindow();
		renWin.AddRenderer(ren);
		iren = vtk.vtkRenderWindowInteractor();
		iren.SetRenderWindow(renWin);
		style = vtk.vtkInteractorStyleTrackballCamera()
		iren.SetInteractorStyle(style)

		ren.AddActor(surfaceActor);
		ren.SetBackground(1, 1, 1);
		renWin.SetSize(800, 600);

		prn=1000.
		pc=-prn
		plXY = vtk.vtkPlaneSource()
		plXY.SetPoint1(prn,-prn,0)
		plXY.SetPoint2(-prn,prn,0)
		plXY.SetOrigin(pc,pc,0)
		plXY.SetCenter(0,0,0)
		plXYmap = vtk.vtkPolyDataMapper()
		plXYmap.SetInput(plXY.GetOutput())
		plXYact = vtk.vtkActor()
		plXYact.SetMapper(plXYmap)
		plXYact.GetProperty().SetOpacity(0.1)


		plYZ = vtk.vtkPlaneSource()
		plYZ.SetCenter(0,pc,pc)
		plYZ.SetPoint1(0,prn,-prn)
		plYZ.SetPoint2(0,-prn,prn)
		plYZmap = vtk.vtkPolyDataMapper()
		plYZmap.SetInput(plYZ.GetOutput())
		plYZact = vtk.vtkActor()
		plYZact.SetMapper(plYZmap)
		plYZact.GetProperty().SetOpacity(0.1)

		plZX = vtk.vtkPlaneSource()
		plZX.SetCenter(pc,0,pc)
		plZX.SetPoint1(prn,0,-prn)
		plZX.SetPoint2(-prn,0,prn)
		plZXmap = vtk.vtkPolyDataMapper()
		plZXmap.SetInput(plZX.GetOutput())
		plZXact = vtk.vtkActor()
		plZXact.SetMapper(plZXmap)
		plZXact.GetProperty().SetOpacity(0.1)


		ren.AddActor(plXYact)
		ren.AddActor(plYZact)
		ren.AddActor(plZXact)

		ax=vtk.vtkAxesActor()
		ax.GetXAxisCaptionActor2D().GetProperty().SetColor(0,0,0)
		ax.GetYAxisCaptionActor2D().GetProperty().SetColor(0,0,0)
		ax.GetZAxisCaptionActor2D().GetProperty().SetColor(0,0,0)
		ow=vtk.vtkOrientationMarkerWidget()
		ow.SetOrientationMarker(ax)
		ow.SetInteractor(iren)
		ow.SetViewport( 0.0, 0.0, 0.4, 0.4 )
		ow.SetEnabled( 1 )
		ow.InteractiveOn()

		lut=vtk.vtkLookupTable()
		lut.SetHueRange( 0.66667, 0.0 )
		lut.SetSaturationRange (1.0, 1.0)
		lut.SetNumberOfColors(50)# len(self.plotables))
		lut.SetTableRange(paint.getMinValue(),paint.getMaxValue())
		lut.Build()
		scalar_bar = vtk.vtkScalarBarActor()
		scalar_bar.SetOrientationToHorizontal()
		scalar_bar.SetLookupTable(lut)
		scalar_bar.SetTitle("Imperfection value");
		scalar_bar.SetNumberOfLabels(11)

		scalar_bar_widget = vtk.vtkScalarBarWidget()
		scalar_bar_widget.SetInteractor(iren)
		scalar_bar_widget.SetScalarBarActor(scalar_bar)
		scalar_bar_widget.On()


		iren.Initialize();
		renWin.Render();
		iren.Start();