Example #1
0
 def subdivide_surface(self):
     if self.divide_algorith == "Butterfly":
         self.vtk_sd = vtk.vtkButterflySubdivisionFilter()
     else:
         self.vtk_sd = vtk.vtkInterpolatingSubdivisionFilter()
     self.vtk_sd.SetNumberOfSubdivisions(self.subdivide)
     self.vtk_sd.SetInputConnection(self.vtk_surface.GetOutputPort())
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkButterflySubdivisionFilter(), 'Processing.',
         ('vtkPolyData',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Example #3
0
    def Subdivide(self, nsub, subfilter='linear'):
        """
        Increase the number of triangles in a single, connected triangular
        mesh.

        Uses one of the following vtk subdivision filters to subdivide a mesh.
        vtkButterflySubdivisionFilter
        vtkLoopSubdivisionFilter
        vtkLinearSubdivisionFilter

        Linear subdivision results in the fastest mesh subdivision, but it
        does not smooth mesh edges, but rather splits each triangle into 4
        smaller triangles.

        Butterfly and loop subdivision perform smoothing when dividing, and may
        introduce artifacts into the mesh when dividing.

        Subdivision filter appears to fail for multiple part meshes.  Should
        be one single mesh.


        Parameters
        ----------
        nsub : int
            Number of subdivisions.  Each subdivision creates 4 new triangles,
            so the number of resulting triangles is nface*4**nsub where nface
            is the current number of faces.
        subfilter : string, optional
            Can be one of the following: 'butterfly', 'loop', 'linear'

        Returns
        -------
        mesh : Polydata object
            vtkInterface polydata object.

        Examples
        --------
        >>> from vtkInterface import examples
        >>> import vtkInterface
        >>> mesh = vtkInterface.LoadMesh(examples.planefile)
        >>> submesh = mesh.Subdivide(1, 'loop')

        """
        subfilter = subfilter.lower()
        if subfilter == 'linear':
            sfilter = vtk.vtkLinearSubdivisionFilter()
        elif subfilter == 'butterfly':
            sfilter = vtk.vtkButterflySubdivisionFilter()
        elif subfilter == 'loop':
            sfilter = vtk.vtkLoopSubdivisionFilter()
        else:
            raise Exception(
                "Subdivision filter must be one of the following: " +
                "'butterfly', 'loop', or 'linear'")

        # Subdivide
        sfilter.SetNumberOfSubdivisions(nsub)
        sfilter.SetInputData(self)
        sfilter.Update()
        return PolyData(sfilter.GetOutput())
Example #4
0
def smooth_mesh(dmc, iterations=20):
    inputPoly = vtk.vtkPolyData()
    inputPoly.ShallowCopy(dmc.GetOutput())

    cleanPolyData = vtk.vtkCleanPolyData()
    cleanPolyData.SetInputData(inputPoly)
    cleanPolyData.Update()

    smooth_butterfly = vtk.vtkButterflySubdivisionFilter()
    smooth_butterfly.SetNumberOfSubdivisions(0)
    smooth_butterfly.SetInputConnection(cleanPolyData.GetOutputPort())
    smooth_butterfly.Update()

    upsampledInputPoly = vtk.vtkPolyData()
    upsampledInputPoly.DeepCopy(smooth_butterfly.GetOutput())

    decimate = vtk.vtkDecimatePro()
    decimate.SetInputData(upsampledInputPoly)
    decimate.SetTargetReduction(0.0)
    decimate.PreserveTopologyOn()
    decimate.Update()

    smoother = vtk.vtkSmoothPolyDataFilter()
    smoother.SetInputConnection(decimate.GetOutputPort())
    smoother.SetNumberOfIterations(iterations)  #
    smoother.SetRelaxationFactor(0.1)
    smoother.FeatureEdgeSmoothingOff()
    smoother.BoundarySmoothingOn()
    smoother.Update()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(smoother.GetOutputPort())
    normals.FlipNormalsOn()

    return normals
Example #5
0
def subdivide(actor, N=1, method=0, legend=None):
    '''
    Increase the number of points in actor surface
        N = number of subdivisions
        method = 0, Loop
        method = 1, Linear
        method = 2, Adaptive
        method = 3, Butterfly
    '''
    triangles = vtk.vtkTriangleFilter()
    setInput(triangles, polydata(actor))
    triangles.Update()
    originalMesh = triangles.GetOutput()
    if method == 0: sdf = vtk.vtkLoopSubdivisionFilter()
    elif method == 1: sdf = vtk.vtkLinearSubdivisionFilter()
    elif method == 2: sdf = vtk.vtkAdaptiveSubdivisionFilter()
    elif method == 3: sdf = vtk.vtkButterflySubdivisionFilter()
    else:
        colors.printc('Error in subdivide: unknown method.', 'r')
        exit(1)
    if method != 2: sdf.SetNumberOfSubdivisions(N)
    setInput(sdf, originalMesh)
    sdf.Update()
    out = sdf.GetOutput()
    if legend is None and hasattr(actor, 'legend'): legend = actor.legend
    sactor = makeActor(out, legend=legend)
    sactor.GetProperty().SetOpacity(actor.GetProperty().GetOpacity())
    sactor.GetProperty().SetColor(actor.GetProperty().GetColor())
    sactor.GetProperty().SetRepresentation(
        actor.GetProperty().GetRepresentation())
    return sactor
Example #6
0
def surface(vertices, faces=None, colors=None, smooth=None, subdivision=3):
    points = vtk.vtkPoints()
    points.SetData(numpy_support.numpy_to_vtk(vertices))
    triangle_poly_data = vtk.vtkPolyData()
    triangle_poly_data.SetPoints(points)

    if colors is not None:
        triangle_poly_data.GetPointData().SetScalars(
            numpy_support.numpy_to_vtk(colors))

    if faces is None:
        tri = Delaunay(vertices[:, [0, 1]])
        faces = np.array(tri.simplices, dtype='i8')

    if faces.shape[1] == 3:
        triangles = np.empty((faces.shape[0], 4), dtype=np.int64)
        triangles[:, -3:] = faces
        triangles[:, 0] = 3
    else:
        triangles = faces

    if not triangles.flags['C_CONTIGUOUS'] or triangles.dtype != 'int64':
        triangles = np.ascontiguousarray(triangles, 'int64')

    cells = vtk.vtkCellArray()
    cells.SetCells(triangles.shape[0],
                   numpy_support.numpy_to_vtkIdTypeArray(triangles, deep=True))
    triangle_poly_data.SetPolys(cells)

    clean_poly_data = vtk.vtkCleanPolyData()
    clean_poly_data.SetInputData(triangle_poly_data)

    mapper = vtk.vtkPolyDataMapper()
    surface_actor = vtk.vtkActor()

    if smooth is None:
        mapper.SetInputData(triangle_poly_data)
        surface_actor.SetMapper(mapper)

    elif smooth == "loop":
        smooth_loop = vtk.vtkLoopSubdivisionFilter()
        smooth_loop.SetNumberOfSubdivisions(subdivision)
        smooth_loop.SetInputConnection(clean_poly_data.GetOutputPort())
        mapper.SetInputConnection(smooth_loop.GetOutputPort())
        surface_actor.SetMapper(mapper)

    elif smooth == "butterfly":
        smooth_butterfly = vtk.vtkButterflySubdivisionFilter()
        smooth_butterfly.SetNumberOfSubdivisions(subdivision)
        smooth_butterfly.SetInputConnection(clean_poly_data.GetOutputPort())
        mapper.SetInputConnection(smooth_butterfly.GetOutputPort())
        surface_actor.SetMapper(mapper)

    return surface_actor
Example #7
0
def subdivision(poly, num, option='linear'):

    if option == 'linear':
        divide = vtk.vtkLinearSubdivisionFilter()
    elif option == 'loop':
        divide = vtk.vtkLoopSubdivisionFilter()
    elif option == 'butterfly':
        divide = vtk.vtkButterflySubdivisionFilter()
    else:
        print("subdivision option: linear, loop or butterfly")
        raise
    divide.SetInputData(poly)
    divide.SetNumberOfSubdivisions(num)
    divide.Update()
    return divide.GetOutput()
Example #8
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.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create source
        sphereSource = vtk.vtkSphereSource()
        sphereSource.Update()
        originalMesh = sphereSource.GetOutput()

        numberOfViewports = 3
        self.vtkWidget.GetRenderWindow().SetSize(200 * numberOfViewports, 200)

        numberOfSubdivisions = 2
        for i in range(numberOfViewports):
            if i == 0:
                subdivisionFilter = vtk.vtkLinearSubdivisionFilter()
            elif i == 1:
                subdivisionFilter = vtk.vtkLoopSubdivisionFilter()
            else:
                subdivisionFilter = vtk.vtkButterflySubdivisionFilter()

            subdivisionFilter.SetNumberOfSubdivisions(numberOfSubdivisions)
            subdivisionFilter.SetInputConnection(
                originalMesh.GetProducerPort())
            subdivisionFilter.Update()

            renderer = vtk.vtkRenderer()
            self.vtkWidget.GetRenderWindow().AddRenderer(renderer)
            renderer.SetViewport(
                float(i) / numberOfViewports, 0, (i + 1.0) / numberOfViewports,
                1)

            # Create a mapper and actor
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(subdivisionFilter.GetOutputPort())

            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            renderer.AddActor(actor)
            renderer.ResetCamera()

        self._initialized = False
Example #9
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.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create source
        sphereSource = vtk.vtkSphereSource()
        sphereSource.Update()
        originalMesh = sphereSource.GetOutput()

        numberOfViewports = 3
        self.vtkWidget.GetRenderWindow().SetSize(200*numberOfViewports, 200)

        numberOfSubdivisions = 2
        for i in range(numberOfViewports):
            if i == 0:
                subdivisionFilter = vtk.vtkLinearSubdivisionFilter()
            elif i == 1:
                subdivisionFilter = vtk.vtkLoopSubdivisionFilter()
            else:
                subdivisionFilter = vtk.vtkButterflySubdivisionFilter()

            subdivisionFilter.SetNumberOfSubdivisions(numberOfSubdivisions)
            subdivisionFilter.SetInputConnection(originalMesh.GetProducerPort())
            subdivisionFilter.Update()

            renderer = vtk.vtkRenderer()
            self.vtkWidget.GetRenderWindow().AddRenderer(renderer)
            renderer.SetViewport(float(i)/numberOfViewports, 0, (i+1.0)/numberOfViewports, 1)

            # Create a mapper and actor
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(subdivisionFilter.GetOutputPort())
 
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            renderer.AddActor(actor)
            renderer.ResetCamera()
 
        self._initialized = False
Example #10
0
    def Execute(self):

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

        subdivisionFilter = None
        if self.Method == 'linear':
            subdivisionFilter = vtk.vtkLinearSubdivisionFilter()
        elif self.Method == 'butterfly':
            subdivisionFilter = vtk.vtkButterflySubdivisionFilter()
        elif self.Method == 'loop':
            subdivisionFilter = vtk.vtkLoopSubdivisionFilter()
        else:
            self.PrintError('Error: Unsupported subdivision method.')
        subdivisionFilter.SetInputData(self.Surface)
        subdivisionFilter.SetNumberOfSubdivisions(self.NumberOfSubdivisions)
        subdivisionFilter.Update()

        self.Surface = subdivisionFilter.GetOutput()
    def Execute(self):

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

        subdivisionFilter = None
        if self.Method == 'linear':
            subdivisionFilter = vtk.vtkLinearSubdivisionFilter()
        elif self.Method == 'butterfly':
            subdivisionFilter = vtk.vtkButterflySubdivisionFilter()
        elif self.Method == 'loop':
            subdivisionFilter = vtk.vtkLoopSubdivisionFilter()
        else:
            self.PrintError('Error: Unsupported subdivision method.')
        subdivisionFilter.SetInputData(self.Surface)
        subdivisionFilter.SetNumberOfSubdivisions(self.NumberOfSubdivisions)
        subdivisionFilter.Update()

        self.Surface = subdivisionFilter.GetOutput()
Example #12
0
    def mesh_subdivision(self, num_subdivisions, method='loop'):
        if method == 'loop':
            subdivision_reader = vtk.vtkLoopSubdivisionFilter()
        elif method == 'butterfly':
            subdivision_reader = vtk.vtkButterflySubdivisionFilter()
        else:
            if self.warning:
                print('Not a valid subdivision method')

        subdivision_reader.SetInputData(self.vtkPolyData)
        subdivision_reader.SetNumberOfSubdivisions(num_subdivisions)
        subdivision_reader.Update()
        self.vtkPolyData = subdivision_reader.GetOutput()
        self.get_mesh_data_from_vtkPolyData()
        if self.warning:
            print(
                'Warning! self.cell_attributes are reset and need to be updated!'
            )
        self.cell_attributes = dict()  #reset
        self.point_attributes = dict()  #reset
Example #13
0
# Add the geometry and topology to the polydata
trianglePolyData.SetPoints(points)
trianglePolyData.GetPointData().SetScalars(colors)
trianglePolyData.SetPolys(triangles)

# Clean the polydata so that the edges are shared !
cleanPolyData = vtk.vtkCleanPolyData()
cleanPolyData.SetInputData(trianglePolyData)

# Use a filter to smooth the data (will add triangles and smooth)
# Use two different filters to show the difference
smooth_loop = vtk.vtkLoopSubdivisionFilter()
smooth_loop.SetNumberOfSubdivisions(3)
smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())
smooth_butterfly = vtk.vtkButterflySubdivisionFilter()
smooth_butterfly.SetNumberOfSubdivisions(3)
smooth_butterfly.SetInputConnection(cleanPolyData.GetOutputPort())

# Create a mapper and actor for initial dataset
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(trianglePolyData)
actor = vtk.vtkActor()
actor.SetMapper(mapper)

# Create a mapper and actor for smoothed dataset (vtkLoopSubdivisionFilter)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(smooth_loop.GetOutputPort())
actor_loop = vtk.vtkActor()
actor_loop.SetMapper(mapper)
actor_loop.SetPosition(32, 0, 0)
Example #14
0
af4.AddInputConnection(af3.GetOutputPort())
af4.AddInputConnection(tf6.GetOutputPort())
# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
clean = vtk.vtkCleanPolyData()
clean.SetTolerance(.001)
clean.SetInputData(model)
clean.SetInputConnection(af2.GetOutputPort())
clean.SetInputConnection(af3.GetOutputPort())
clean.SetInputConnection(af4.GetOutputPort())
subdivide = vtk.vtkButterflySubdivisionFilter()
subdivide.SetInputConnection(clean.GetOutputPort())
subdivide.SetNumberOfSubdivisions(3)
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(subdivide.GetOutputPort())
surface = vtk.vtkActor()
surface.SetMapper(mapper)
fe = vtk.vtkFeatureEdges()
fe.SetInputConnection(subdivide.GetOutputPort())
fe.SetFeatureAngle(100)
feStripper = vtk.vtkStripper()
feStripper.SetInputConnection(fe.GetOutputPort())
feTubes = vtk.vtkTubeFilter()
feTubes.SetInputConnection(feStripper.GetOutputPort())
feTubes.SetRadius(.1)
feMapper = vtk.vtkPolyDataMapper()
Example #15
0
def main():
    nc = vtk.vtkNamedColors()

    # Make a 32 x 32 grid
    size = 32

    rn = vtk.vtkMinimalStandardRandomSequence()
    rn.SetSeed(1)

    # Define z values for the topography (random height)
    topography = numpy.zeros([size, size])
    for i in range(size):
        for j in range(size):
            topography[i][j] = rn.GetRangeValue(0, 5)
            rn.Next()

    # Define points, triangles and colors
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    points = vtk.vtkPoints()
    triangles = vtk.vtkCellArray()

    # Build the meshgrid manually
    count = 0
    for i in range(size - 1):
        for j in range(size - 1):
            z1 = topography[i][j]
            z2 = topography[i][j + 1]
            z3 = topography[i + 1][j]

            # Triangle 1
            points.InsertNextPoint(i, j, z1)
            points.InsertNextPoint(i, (j + 1), z2)
            points.InsertNextPoint((i + 1), j, z3)

            triangle = vtk.vtkTriangle()
            triangle.GetPointIds().SetId(0, count)
            triangle.GetPointIds().SetId(1, count + 1)
            triangle.GetPointIds().SetId(2, count + 2)

            triangles.InsertNextCell(triangle)

            z1 = topography[i][j + 1]
            z2 = topography[i + 1][j + 1]
            z3 = topography[i + 1][j]

            # Triangle 2
            points.InsertNextPoint(i, (j + 1), z1)
            points.InsertNextPoint((i + 1), (j + 1), z2)
            points.InsertNextPoint((i + 1), j, z3)

            triangle = vtk.vtkTriangle()
            triangle.GetPointIds().SetId(0, count + 3)
            triangle.GetPointIds().SetId(1, count + 4)
            triangle.GetPointIds().SetId(2, count + 5)

            count += 6

            triangles.InsertNextCell(triangle)

            # Add some color
            r = [int(i / float(size) * 255), int(j / float(size) * 255), 0]
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)

    # Create a polydata object
    trianglePolyData = vtk.vtkPolyData()

    # Add the geometry and topology to the polydata
    trianglePolyData.SetPoints(points)
    trianglePolyData.GetPointData().SetScalars(colors)
    trianglePolyData.SetPolys(triangles)

    # Clean the polydata so that the edges are shared !
    cleanPolyData = vtk.vtkCleanPolyData()
    cleanPolyData.SetInputData(trianglePolyData)

    # Use a filter to smooth the data (will add triangles and smooth)
    # Use two different filters to show the difference
    smooth_loop = vtk.vtkLoopSubdivisionFilter()
    smooth_loop.SetNumberOfSubdivisions(3)
    smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())
    smooth_butterfly = vtk.vtkButterflySubdivisionFilter()
    smooth_butterfly.SetNumberOfSubdivisions(3)
    smooth_butterfly.SetInputConnection(cleanPolyData.GetOutputPort())

    # Create a mapper and actor for initial dataset
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(trianglePolyData)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Create a mapper and actor for smoothed dataset (vtkLoopSubdivisionFilter)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(smooth_loop.GetOutputPort())
    actor_loop = vtk.vtkActor()
    actor_loop.SetMapper(mapper)
    actor_loop.SetPosition(32, 0, 0)

    # Create a mapper and actor for smoothed dataset (vtkButterflySubdivisionFilter)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(smooth_butterfly.GetOutputPort())
    actor_butterfly = vtk.vtkActor()
    actor_butterfly.SetMapper(mapper)
    actor_butterfly.SetPosition(64, 0, 0)

    # Visualise
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add actors and render
    renderer.AddActor(actor)
    renderer.AddActor(actor_loop)
    renderer.AddActor(actor_butterfly)
    renderer.SetBackground(nc.GetColor3d('AliceBlue'))

    renderWindow.SetSize(900, 300)
    renderWindow.Render()
    renderer.GetActiveCamera().Elevation(-45)
    renderer.GetActiveCamera().Zoom(3)
    renderWindow.Render()
    renderWindowInteractor.Start()
Example #16
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()
def vtk_mesh_subdivision():
    """Subdivide a mesh into more triangles

    The subdivisions are increasing the faces by 4^# subdivisions
    """
    
    # get the polydata for a mesh
    v, f = wavefront.ellipsoid_mesh(1, 2, 3, density=20)
    polydata = wavefront.meshtopolydata(v, f)

    # subdivide using appropriate filter
    smooth_loop = vtk.vtkLoopSubdivisionFilter()
    smooth_loop.SetNumberOfSubdivisions(1) # can define the number of subdivisions
    smooth_loop.SetInputData(polydata)
    smooth_loop.Update()
    poly_loop = vtk.vtkPolyData()
    poly_loop.ShallowCopy(smooth_loop.GetOutput())

    smooth_butterfly = vtk.vtkButterflySubdivisionFilter()
    smooth_butterfly.SetNumberOfSubdivisions(3)
    smooth_butterfly.SetInputData(polydata)
    smooth_butterfly.Update() 
    poly_butterfly = vtk.vtkPolyData()
    poly_butterfly.ShallowCopy(smooth_butterfly.GetOutput())

    # Create a mapper and actor for initial dataset
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polydata)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    
    # Create a mapper and actor for smoothed dataset (vtkLoopSubdivisionFilter)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(smooth_loop.GetOutputPort())
    actor_loop = vtk.vtkActor()
    actor_loop.SetMapper(mapper)
    actor_loop.SetPosition(3, 0, 0)
    
    # Create a mapper and actor for smoothed dataset (vtkButterflySubdivisionFilter)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(smooth_butterfly.GetOutputPort())
    actor_butterfly = vtk.vtkActor()
    actor_butterfly.SetMapper(mapper)
    actor_butterfly.SetPosition(6, 0, 0)
    
    # Visualise
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    
    # Add actors and render
    renderer.AddActor(actor)
    renderer.AddActor(actor_loop)
    renderer.AddActor(actor_butterfly)
    
    renderer.SetBackground(1, 1, 1) # Background color white
    renderWindow.SetSize(800, 800)
    renderWindow.Render()
    renderWindowInteractor.Start()
    
    # output to a new v, f array
    # convert polydata to numpy
    v_loop, f_loop = wavefront.polydatatomesh(poly_loop)
    v_butterfly, f_butterfly = wavefront.polydatatomesh(poly_butterfly)
    print('Original #V : {} #F : {}'.format(v.shape[0], f.shape[0]))
    print('Loop     #V : {} #F : {}'.format(v_loop.shape[0], f_loop.shape[0]))
    print('BFly     #V : {} #F : {}'.format(v_butterfly.shape[0], f_butterfly.shape[0]))
Example #18
0
# Add the geometry and topology to the polydata
trianglePolyData.SetPoints(points)
trianglePolyData.GetPointData().SetScalars(colors)
trianglePolyData.SetPolys(triangles)

# Clean the polydata so that the edges are shared !
cleanPolyData = vtk.vtkCleanPolyData()
cleanPolyData.SetInputData(trianglePolyData)

# Use a filter to smooth the data (will add triangles and smooth)
# Use two different filters to show the difference
smooth_loop = vtk.vtkLoopSubdivisionFilter()
smooth_loop.SetNumberOfSubdivisions(3)
smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())
smooth_butterfly = vtk.vtkButterflySubdivisionFilter()
smooth_butterfly.SetNumberOfSubdivisions(3)
smooth_butterfly.SetInputConnection(cleanPolyData.GetOutputPort())

# Create a mapper and actor for initial dataset
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(trianglePolyData)
actor = vtk.vtkActor()
actor.SetMapper(mapper)

# Create a mapper and actor for smoothed dataset (vtkLoopSubdivisionFilter)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(smooth_loop.GetOutputPort())
actor_loop = vtk.vtkActor()
actor_loop.SetMapper(mapper)
actor_loop.SetPosition(32, 0, 0)
def main():
    def FlatInterpolation():
        for actor in actors:
            actor.GetProperty().SetInterpolationToFlat()
        renWin.Render()

    def GouraudInterpolation():
        for actor in actors:
            actor.GetProperty().SetInterpolationToGouraud()
        renWin.Render()

    sourceToUse, displayNormals, gouraudInterpolation, glyphPoints = GetProgramParameters(
    )

    if sourceToUse in Sources().sources:
        src = Sources().sources[sourceToUse]
    else:
        print('The source {:s} is not available.'.format(sourceToUse))
        print('Available sources are:\n',
              ', '.join(sorted(list(Sources().sources.keys()))))
        return

    src.Update()

    # The size of the render window.
    renWinXSize = 1200
    renWinYSize = renWinXSize // 3
    minRenWinDim = min(renWinXSize, renWinYSize)

    # [xMin, xMax, yMin, yMax, zMin, zMax]
    bounds = src.GetOutput().GetBounds()
    # Use this to scale the normal glyph.
    scaleFactor = min(map(lambda x, y: x - y, bounds[1::2], bounds[::2])) * 0.2
    src.GetOutput().GetPointData().GetScalars().SetName("Elevation")
    scalarRange = src.GetOutput().GetScalarRange()

    butterfly = vtk.vtkButterflySubdivisionFilter()
    butterfly.SetInputConnection(src.GetOutputPort())
    butterfly.SetNumberOfSubdivisions(3)
    butterfly.Update()

    linear = vtk.vtkLinearSubdivisionFilter()
    linear.SetInputConnection(src.GetOutputPort())
    linear.SetNumberOfSubdivisions(3)
    linear.Update()

    lut = MakeLUT(scalarRange)

    actors = list()
    actors.append(MakeSurfaceActor(butterfly, scalarRange, lut))
    actors.append(MakeSurfaceActor(linear, scalarRange, lut))
    actors.append(MakeSurfaceActor(src, scalarRange, lut))

    # Let's visualise the normals.
    glyphActors = list()
    if displayNormals:
        glyphActors.append(
            GlyphActor(butterfly, glyphPoints, scalarRange, scaleFactor, lut))
        glyphActors.append(
            GlyphActor(linear, glyphPoints, scalarRange, scaleFactor, lut))
        glyphActors.append(
            GlyphActor(src, glyphPoints, scalarRange, scaleFactor, lut))

    labelActors = list()
    labelActors.append(MakeLabel('Butterfly Subdivision', minRenWinDim))
    labelActors.append(MakeLabel('Linear Subdivision', minRenWinDim))
    labelActors.append(MakeLabel('Original', minRenWinDim))

    ren = list()
    ren.append(vtk.vtkRenderer())
    ren.append(vtk.vtkRenderer())
    ren.append(vtk.vtkRenderer())
    ren[2].SetViewport(0, 0, 1.0 / 3.0, 1)  # Original
    ren[1].SetViewport(1.0 / 3.0, 0, 2.0 / 3.0, 1)  # Linear
    ren[0].SetViewport(2.0 / 3.0, 0, 1, 1)  # Butterfly

    renWin = vtk.vtkRenderWindow()
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Orientation markers.
    om = list()
    # Make the imaging pipelines.
    for i in range(0, len(ren)):
        renWin.AddRenderer(ren[i])

        ren[i].AddActor(actors[i])
        ren[i].AddActor(labelActors[i])
        ren[i].SetBackground(nc.GetColor3d('SlateGray'))

        if displayNormals:
            ren[i].AddActor(glyphActors[i])

        om.append(MakeOrientationMarker(ren[i], iren))

    if gouraudInterpolation:
        GouraudInterpolation()
    else:
        FlatInterpolation()

    renWin.SetSize(renWinXSize, renWinYSize)
    renWin.Render()
    # renWin.SetWindowName() needs to be called after renWin.Render()
    renWin.SetWindowName('Point Data Subdivision Example')

    iren.Initialize()
    # WritePNG(iren.GetRenderWindow().GetRenderers().GetFirstRenderer(), "TestPointDataSubdivision.png")
    iren.Start()
Example #20
0
af4.AddInputConnection(af3.GetOutputPort())
af4.AddInputConnection(tf6.GetOutputPort())
# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
clean = vtk.vtkCleanPolyData()
clean.SetTolerance(.001)
clean.SetInputData(model)
clean.SetInputConnection(af2.GetOutputPort())
clean.SetInputConnection(af3.GetOutputPort())
clean.SetInputConnection(af4.GetOutputPort())
subdivide = vtk.vtkButterflySubdivisionFilter()
subdivide.SetInputConnection(clean.GetOutputPort())
subdivide.SetNumberOfSubdivisions(3)
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(subdivide.GetOutputPort())
surface = vtk.vtkActor()
surface.SetMapper(mapper)
fe = vtk.vtkFeatureEdges()
fe.SetInputConnection(subdivide.GetOutputPort())
fe.SetFeatureAngle(100)
feStripper = vtk.vtkStripper()
feStripper.SetInputConnection(fe.GetOutputPort())
feTubes = vtk.vtkTubeFilter()
feTubes.SetInputConnection(feStripper.GetOutputPort())
feTubes.SetRadius(.1)
feMapper = vtk.vtkPolyDataMapper()