def BuildPolyBallSurface(self):
     #Build a surface for displaying the polyball
     if self.PolyBall == None:
         return
     
     #Sample the polyball
     sampler = vtk.vtkSampleFunction()
     sampler.SetImplicitFunction(self.PolyBall)
     
     #Set the bounds to be slightly larger than those of the mesh
     meshBounds = self.Mesh.GetBounds()
     meshCenter = self.Mesh.GetCenter()
     polyBallBounds = [0, 0, 0, 0, 0, 0]
     for i in range(0,3):
         length = 1.2*(meshBounds[2*i+1] - meshCenter[i])
         polyBallBounds[2*i] = meshCenter[i] - length
         polyBallBounds[2*i+1] = meshCenter[i] + length
     
     sampler.SetModelBounds(polyBallBounds)
     sampler.SetSampleDimensions(self.PolyBallResolution)
     sampler.ComputeNormalsOff()
     sampler.Update()
     
     #Extract the isosurface at 0
     contour = vtk.vtkContourFilter()
     contour.SetInput(sampler.GetOutput())
     contour.SetValue(0,0.)
     contour.Update()
     
     #Set the new model as the mapper input
     self.PolyBallActor.GetMapper().SetInput(contour.GetOutput())
Esempio n. 2
0
def actors_step_3(contour_filter_leg):
    """
    Creates the visualization actors for step 3
    :param contour_filter_leg: The data SLC from the leg
    :return: The leg actor and the sphere actor
    """
    # Clipping the knee skin with a sphere
    actor_leg, sphere = clipping_skin_with_sphere(contour_filter_leg)

    sample = vtk.vtkSampleFunction()
    sample.SetImplicitFunction(sphere)
    sample.SetModelBounds(-200.5, 200.5, -200.5, 200.5, -200.5, 200.5)
    sample.SetSampleDimensions(200, 200, 200)
    sample.ComputeNormalsOff()

    contour_filter = vtk.vtkContourFilter()
    contour_filter.SetInputConnection(sample.GetOutputPort())
    contour_filter.SetValue(0, 0.0)

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(contour_filter.GetOutputPort())
    mapper.ScalarVisibilityOff()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d("sphere"))
    actor.GetProperty().SetOpacity(0.4)

    return [actor_leg, actor]
Esempio n. 3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkSampleFunction(), 'Processing.',
         (), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Esempio n. 4
0
 def BuildPolyBallSurface(self):
     #Build a surface for displaying the polyball
     if self.PolyBall == None:
         return
     
     #Sample the polyball
     sampler = vtk.vtkSampleFunction()
     sampler.SetImplicitFunction(self.PolyBall)
     
     #Set the bounds to be slightly larger than those of the mesh
     meshBounds = self.Mesh.GetBounds()
     meshCenter = self.Mesh.GetCenter()
     polyBallBounds = [0, 0, 0, 0, 0, 0]
     for i in range(0,3):
         length = 1.2*(meshBounds[2*i+1] - meshCenter[i])
         polyBallBounds[2*i] = meshCenter[i] - length
         polyBallBounds[2*i+1] = meshCenter[i] + length
     
     sampler.SetModelBounds(polyBallBounds)
     sampler.SetSampleDimensions(self.PolyBallResolution)
     sampler.ComputeNormalsOff()
     sampler.Update()
     
     #Extract the isosurface at 0
     contour = vtk.vtkContourFilter()
     contour.SetInputConnection(sampler.GetOutputPort())
     contour.SetValue(0,0.)
     contour.Update()
     
     #Set the new model as the mapper input
     self.PolyBallActor.GetMapper().SetInputConnection(contour.GetOutputPort())
Esempio n. 5
0
def Ellipsoid_deprecated(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, bounds,
                         sample_dims):
    #create an ellipsoid using a implicit quadric
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)

    # The sample function generates a distance function from the implicit
    # function. This is then contoured to get a polygonal surface.
    sample = vtk.vtkSampleFunction()
    sample.SetImplicitFunction(quadric)
    sample.SetModelBounds(-bounds, bounds, -bounds, bounds, -bounds, bounds)
    sample.SetSampleDimensions(sample_dims, sample_dims, sample_dims)
    sample.ComputeNormalsOff()

    # contour
    surface = vtk.vtkContourFilter()
    surface.SetInputConnection(sample.GetOutputPort())
    surface.GenerateValues(1.0, 1.0, 1.0)

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(surface.GetOutputPort())
    mapper.ScalarVisibilityOff()
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
Esempio n. 6
0
def main():
    colors = vtk.vtkNamedColors()

    aren = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(aren)

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

    #
    # Create surfaces F(x,y,z) = constant
    #
    # Sample quadric function
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(50, 50, 50)
    sample.SetImplicitFunction(quadric)

    contour = vtk.vtkContourFilter()
    contour.SetInputConnection(sample.GetOutputPort())
    contour.GenerateValues(5, 0, 1.2)

    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInputConnection(contour.GetOutputPort())
    contourMapper.SetScalarRange(0, 1.2)

    contourActor = vtk.vtkActor()
    contourActor.SetMapper(contourMapper)

    # Create outline
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d("Brown"))
    outlineActor.GetProperty().SetLineWidth(3.0)

    #
    # Rendering stuff
    #
    aren.SetBackground(colors.GetColor3d("SlateGray"))
    aren.AddActor(contourActor)
    aren.AddActor(outlineActor)

    aren.ResetCamera()
    aren.GetActiveCamera().Azimuth(30)
    aren.GetActiveCamera().Elevation(30)

    renWin.SetSize(640, 512)
    renWin.Render()

    # interact with data
    iren.Start()
Esempio n. 7
0
def CreateIsoSurface(flat):
    """

    :param flat: The interpolation to use (flat or Gouraud).
    :return: the renderer
    """
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(1, 2, 3, 0, 1, 0, 0, 0, 0, 0)
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(25, 25, 25)
    sample.SetImplicitFunction(quadric)
    # Generate the implicit surface.
    contour = vtk.vtkContourFilter()
    contour.SetInputConnection(sample.GetOutputPort())
    range = [1.0, 6.0]
    contour.GenerateValues(5, range)
    # Map the contour.
    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInputConnection(contour.GetOutputPort())
    contourMapper.SetScalarRange(0, 7)
    actor = vtk.vtkActor()
    actor.SetMapper(contourMapper)
    if flat:
        actor.GetProperty().SetInterpolationToFlat()
    else:
        actor.GetProperty().SetInterpolationToGouraud()
    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    return renderer
Esempio n. 8
0
 def SampleFunction(self, currentElement):
     sampFunc = vtk.vtkSampleFunction()
     # Datatype(s) I need for input:  Algorithm
     AlgorithmElement = ''
     for childElement in currentElement.getchildren():
         if childElement.tag in vtkTypes['Algorithm']:
             AlgorithmElement = childElement
     if AlgorithmElement != '':
         dataset = self.namesToFunctions[AlgorithmElement.tag](AlgorithmElement)
         self.logger.debug('  .. <SampleFunction> trying to SetImplicitFunction.')
         try:
             sampFunc.SetImplicitFunction(dataset)
         except:
             self.logger.error('  .. <SampleFunction> failed to SetImplicitFunction.')
     if 'SetSampleDimensions' in currentElement.keys():
         self.logger.debug('  .. <SampleFunction> trying to SetSampleDimensions')
         try:
             sampFunc.SetSampleDimensions( str2ints(currentElement.get('SetSampleDimensions')) )
         except:
             self.logger.error('  .. <SampleFunction> failed to SetSampleDimensions')
     if 'SetModelBounds' in currentElement.keys():
         self.logger.debug('  .. <SampleFunction> trying to SetModelBounds')
         try:
             sampFunc.SetModelBounds( str2floats(currentElement.get('SetModelBounds')) )
         except:
             self.logger.error('  .. <SampleFunction> failed to SetModelBounds')
     sampFunc.ComputeNormalsOff()
     return sampFunc
Esempio n. 9
0
def PlotFunction(quadric, value):
    colors = vtk.vtkNamedColors()

    # sample the quadric function
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(50, 50, 50)
    sample.SetImplicitFunction(quadric)
    # double xmin = 0, xmax=1, ymin=0, ymax=1, zmin=0, zmax=1
    xmin = -10
    xmax = 11
    ymin = -10
    ymax = 10
    zmin = -10
    zmax = 10
    sample.SetModelBounds(xmin, xmax, ymin, ymax, zmin, zmax)

    # create the 0 isosurface
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(1, value, value)

    # map the contours to graphical primitives
    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInputConnection(contours.GetOutputPort())
    contourMapper.SetScalarRange(0.0, 1.2)

    # create an actor for the contours
    contourActor = vtk.vtkActor()
    contourActor.SetMapper(contourMapper)

    # -- create a box around the function to indicate the sampling volume --

    # create outline
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    # map it to graphics primitives
    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    # create an actor for it
    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    # setup the window
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # add the actors to the scene
    ren1.AddActor(contourActor)
    ren1.AddActor(outlineActor)
    ren1.SetBackground(colors.GetColor3d('AliceBlue'))

    # render and interact
    renWin.Render()
    iren.Start()
Esempio n. 10
0
def createImageData():
    sphere = vtk.vtkSphere()
    sphere.SetRadius(0.1)
    sphere.SetCenter(0.0, 0.0, 0.0)

    sampleFunction = vtk.vtkSampleFunction()
    sampleFunction.SetImplicitFunction(sphere)
    sampleFunction.SetOutputScalarTypeToDouble()
    sampleFunction.SetSampleDimensions(127, 127, 127)
    sampleFunction.SetModelBounds(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
    sampleFunction.SetCapping(False)
    sampleFunction.SetComputeNormals(False)
    sampleFunction.SetScalarArrayName("values")
    sampleFunction.Update()

    a = sampleFunction.GetOutput().GetPointData().GetScalars("values")
    range = a.GetRange()
    print range
    t = vtk.vtkImageShiftScale()
    t.SetInputConnection(sampleFunction.GetOutputPort())

    t.SetShift(-range[0])
    magnitude = range[1] - range[0]
    if magnitude == 0.0:
        magnitude = 1.0
    t.SetScale(255.0 / magnitude)
    t.SetOutputScalarTypeToUnsignedChar()
    t.Update()
    return t.GetOutput()
Esempio n. 11
0
def visQuadFunc():
    """ vtk sample scene with iso contours """

    # VTK supports implicit functions of the form f(x,y,z)=constant. These
    # functions can represent things spheres, cones, etc. Here we use a
    # general form for a quadric to create an elliptical data field.
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

    # vtkSampleFunction samples an implicit function over the x-y-z range
    # specified (here it defaults to -1,1 in the x,y,z directions).
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(30, 30, 30)
    sample.SetImplicitFunction(quadric)

    # Create five surfaces F(x,y,z) = constant between range specified. The
    # GenerateValues() method creates n isocontour values between the range
    # specified.
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(8, 0.0, 1.2)

    contMapper = vtk.vtkPolyDataMapper()
    contMapper.SetInputConnection(contours.GetOutputPort())
    contMapper.SetScalarRange(0.0, 1.2)

    contActor = vtk.vtkActor()
    contActor.SetMapper(contMapper)

    # We'll put a simple outline around the data.
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1, 0.5, 0)

    # extract data from the volume
    extract = vtk.vtkExtractVOI()
    extract.SetInputConnection(sample.GetOutputPort())
    extract.SetVOI(0, 29, 0, 29, 15, 15)
    extract.SetSampleRate(1, 2, 3)

    contours2 = vtk.vtkContourFilter()
    contours2.SetInputConnection(extract.GetOutputPort())
    contours2.GenerateValues(8, 0.0, 1.2)

    contMapper2 = vtk.vtkPolyDataMapper()
    contMapper2.SetInputConnection(contours2.GetOutputPort())
    contMapper2.SetScalarRange(0.0, 1.2)

    contActor2 = vtk.vtkActor()
    contActor2.SetMapper(contMapper2)

    return contActor, contActor2, outlineActor, contours, contours2
Esempio n. 12
0
def visQuadFunc():
    """ vtk sample scene with iso contours """

    # VTK supports implicit functions of the form f(x,y,z)=constant. These
    # functions can represent things spheres, cones, etc. Here we use a
    # general form for a quadric to create an elliptical data field.
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

    # vtkSampleFunction samples an implicit function over the x-y-z range
    # specified (here it defaults to -1,1 in the x,y,z directions).
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(30, 30, 30)
    sample.SetImplicitFunction(quadric)

    # Create five surfaces F(x,y,z) = constant between range specified. The
    # GenerateValues() method creates n isocontour values between the range
    # specified.
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(8, 0.0, 1.2)

    contMapper = vtk.vtkPolyDataMapper()
    contMapper.SetInputConnection(contours.GetOutputPort())
    contMapper.SetScalarRange(0.0, 1.2)

    contActor = vtk.vtkActor()
    contActor.SetMapper(contMapper)

    # We'll put a simple outline around the data.
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1, 0.5, 0)

    # extract data from the volume
    extract = vtk.vtkExtractVOI()
    extract.SetInputConnection(sample.GetOutputPort())
    extract.SetVOI(0, 29, 0, 29, 15, 15)
    extract.SetSampleRate(1, 2, 3)

    contours2 = vtk.vtkContourFilter()
    contours2.SetInputConnection(extract.GetOutputPort())
    contours2.GenerateValues(8, 0.0, 1.2)

    contMapper2 = vtk.vtkPolyDataMapper()
    contMapper2.SetInputConnection(contours2.GetOutputPort())
    contMapper2.SetScalarRange(0.0, 1.2)

    contActor2 = vtk.vtkActor()
    contActor2.SetMapper(contMapper2)

    return contActor, contActor2, outlineActor, contours, contours2
Esempio n. 13
0
    def planeModel(self, scene, normal, origin, name, color):
        """ Create a plane model node which can be viewed in the 3D View """
        #A plane source

        plane = vtk.vtkPlane()

        plane.SetOrigin(origin)

        plane.SetNormal(normal)

        planeSample = vtk.vtkSampleFunction()

        planeSample.SetImplicitFunction(plane)

        planeSample.SetModelBounds(-100, 100, -100, 100, -100, 100)

        planeSample.SetSampleDimensions(100, 100, 100)

        planeSample.ComputeNormalsOff()

        planeContour = vtk.vtkContourFilter()

        #        planeContour.SetInput(planeSample.GetOutput())
        planeContour.SetInputData(planeSample.GetOutput())

        # Create plane model node

        planeNode = slicer.vtkMRMLModelNode()

        planeNode.SetScene(scene)

        planeNode.SetName(name)

        planeNode.SetAndObservePolyData(planeContour.GetOutput())

        # Create plane display model node

        planeModelDisplay = slicer.vtkMRMLModelDisplayNode()

        planeModelDisplay.SetColor(color)

        planeModelDisplay.SetBackfaceCulling(0)

        planeModelDisplay.SetScene(scene)

        scene.AddNode(planeModelDisplay)

        planeNode.SetAndObserveDisplayNodeID(planeModelDisplay.GetID())

        #Add to scene

        #        planeModelDisplay.SetInputPolyData(planeContour.GetOutput())
        planeModelDisplay.SetInputPolyDataConnection(
            planeContour.GetOutputPort())

        scene.AddNode(planeNode)

        return plane
Esempio n. 14
0
    def __init__(self, parent):
        QVTKRenderWindowInteractor.__init__(self, parent)

        self.renderer = vtk.vtkRenderer()
        self.GetRenderWindow().AddRenderer(self.renderer)
        
        interactor = vtk.vtkInteractorStyleSwitch()
        self._Iren.SetInteractorStyle(interactor)
                
        self.surface = None

        # Remainng calls set up axes.
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(1,1,1)

        # Create a faint outline to go with the axes.
        self.outline = vtk.vtkOutlineFilter()

        # Initially set up with a box as input.  This will be changed
        # to a plot once the user clicks something.
        self.box = vtk.vtkBox()
        self.box.SetBounds(0,10,0,10,0,10)
        sample = vtk.vtkSampleFunction()
        sample.SetImplicitFunction(self.box)
        sample.SetSampleDimensions(2,2,2)
        sample.SetModelBounds(0,10,0,10,0,5)
        sample.ComputeNormalsOff()

        self.outline.SetInputConnection(sample.GetOutputPort())
        mapOutline = vtk.vtkPolyDataMapper()
        mapOutline.SetInputConnection(self.outline.GetOutputPort())
        self.outlineActor = vtk.vtkActor()
        self.outlineActor.SetMapper(mapOutline)
        self.outlineActor.GetProperty().SetColor(1,1,1)
        self.outlineActor.GetProperty().SetOpacity(.25)
        self.renderer.AddActor(self.outlineActor)

        self.axes = vtk.vtkCubeAxesActor2D()
        self.axes.SetCamera(self.renderer.GetActiveCamera())
        self.axes.SetFlyModeToOuterEdges()

        self.axes.SetLabelFormat("%6.4g")
        self.axes.SetFontFactor(0.8)
        self.axes.SetAxisTitleTextProperty(tprop)
        self.axes.SetAxisLabelTextProperty(tprop)
        self.axes.SetXLabel("MPI Rank")
        self.axes.SetYLabel("Progress")
        self.axes.SetZLabel("Effort")
        self.axes.SetInput(sample.GetOutput())
        self.renderer.AddViewProp(self.axes)

        # Keep original camera around in case it gets changed
        self.originalCamera = self.renderer.GetActiveCamera()

        self.renderer.GetActiveCamera().Pitch(90)     # Want effort to be vertical
        self.renderer.GetActiveCamera().OrthogonalizeViewUp()
        self.renderer.ResetCamera()
        self.renderer.GetActiveCamera().Elevation(15)  # Be slightly above the data
Esempio n. 15
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkSampleFunction(),
                                       'Processing.', (),
                                       ('vtkImageData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Esempio n. 16
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
        sphere = vtk.vtkSphere()

        # Sample the function
        sample = vtk.vtkSampleFunction()
        sample.SetSampleDimensions(50, 50, 50)
        sample.SetImplicitFunction(sphere)
        sample.SetModelBounds(-2, 2, -2, 2, -2, 2)

        # Create the 0 isosurface
        contours = vtk.vtkContourFilter()
        contours.SetInputConnection(sample.GetOutputPort())
        contours.GenerateValues(1, 1, 1)

        # Map the contours to graphical primitives
        contourMapper = vtk.vtkPolyDataMapper()
        contourMapper.SetInputConnection(contours.GetOutputPort())
        contourMapper.SetScalarRange(0, 1.2)

        # Create an actor for the contours
        contourActor = vtk.vtkActor()
        contourActor.SetMapper(contourMapper)

        # -- Create a box around the function to indicated the sampling volume

        # Create outline
        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(sample.GetOutputPort())

        # Map it to graphics primitives
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())

        # Create an actor for it
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)
        outlineActor.GetProperty().SetColor(0, 0, 0)

        self.ren.AddActor(contourActor)
        self.ren.AddActor(outlineActor)
        self.ren.ResetCamera()

        self._initialized = False
    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.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create cylinder
        cylinder = vtk.vtkCylinder()
        cylinder.SetCenter(0, 0, 0)
        cylinder.SetRadius(1.0)
        
        # Create plane
        plane = vtk.vtkPlane()
        plane.SetOrigin(0, 0, 0)
        plane.SetNormal(0, -1, 0)

        # Cut the cylinder
        cuted_cylinder = vtk.vtkImplicitBoolean()
        cuted_cylinder.SetOperationTypeToIntersection()
        #cuted_cylinder.SetOperationTypeToUnion()
        cuted_cylinder.AddFunction(cylinder)
        cuted_cylinder.AddFunction(plane)

        # Sample 
        sample = vtk.vtkSampleFunction()
        sample.SetImplicitFunction(cuted_cylinder)
        sample.SetModelBounds(-1.5 , 1.5 , -1.5 , 1.5 , -1.5 , 1.5)
        sample.SetSampleDimensions(60, 60, 60)
        sample.SetComputeNormals(0)

        #
        surface = vtk.vtkContourFilter()
        #surface.SetInput(sample.GetOutput())
        surface.SetInputConnection(sample.GetOutputPort())
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        #mapper.SetInput(surface.GetOutput())
        mapper.SetInputConnection(surface.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Esempio n. 18
0
def hyperboloid(pos=[0, 0, 0],
                a2=1,
                value=0.5,
                height=1,
                axis=[0, 0, 1],
                c='magenta',
                alpha=1,
                legend=None,
                texture=None,
                res=100):
    '''
    Build a hyperboloid of specified aperture `a2` and `height`, centered at `pos`.
    
    Full volumetric expression is:
        :math:`F(x,y,z)=a_0x^2+a_1y^2+a_2z^2+a_3xy+a_4yz+a_5xz+ a_6x+a_7y+a_8z+a_9`

    .. hint:: Example: `mesh_bands.py <https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/mesh_bands.py>`_

        .. image:: https://user-images.githubusercontent.com/32848391/51211548-26a78b00-1916-11e9-9306-67b677d1be3a.png
    '''
    q = vtk.vtkQuadric()
    q.SetCoefficients(2, 2, -1 / a2, 0, 0, 0, 0, 0, 0, 0)
    # F(x,y,z) = a0*x^2 + a1*y^2 + a2*z^2
    #         + a3*x*y + a4*y*z + a5*x*z
    #         + a6*x   + a7*y   + a8*z  +a9
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(res, res, res)
    sample.SetImplicitFunction(q)

    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(1, value, value)
    contours.Update()

    axis = np.array(axis) / np.linalg.norm(axis)
    theta = np.arccos(axis[2])
    phi = np.arctan2(axis[1], axis[0])
    t = vtk.vtkTransform()
    t.PostMultiply()
    t.RotateY(theta * 57.3)
    t.RotateZ(phi * 57.3)
    t.Scale(1, 1, height)
    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetInputData(contours.GetOutput())
    tf.SetTransform(t)
    tf.Update()
    pd = tf.GetOutput()

    actor = Actor(pd, c=c, alpha=alpha, legend=legend, texture=texture)
    actor.GetProperty().SetInterpolationToPhong()
    actor.GetMapper().ScalarVisibilityOff()
    actor.SetPosition(pos)
    return actor
Esempio n. 19
0
def paraboloid(pos=[0, 0, 0],
               r=1,
               height=1,
               axis=[0, 0, 1],
               c='cyan',
               alpha=1,
               legend=None,
               texture=None,
               res=100):
    '''
    Build a paraboloid of specified height and radius `r`, centered at `pos`.
    
    .. note::
        Full volumetric expression is:
            :math:`F(x,y,z)=a_0x^2+a_1y^2+a_2z^2+a_3xy+a_4yz+a_5xz+ a_6x+a_7y+a_8z+a_9`
    
        .. image:: https://user-images.githubusercontent.com/32848391/51211547-260ef480-1916-11e9-95f6-4a677e37e355.png
    '''
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(1, 1, 0, 0, 0, 0, 0, 0, height / 4, 0)
    # F(x,y,z) = a0*x^2 + a1*y^2 + a2*z^2
    #         + a3*x*y + a4*y*z + a5*x*z
    #         + a6*x   + a7*y   + a8*z  +a9
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(res, res, res)
    sample.SetImplicitFunction(quadric)

    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(1, .01, .01)
    contours.Update()

    axis = np.array(axis) / np.linalg.norm(axis)
    theta = np.arccos(axis[2])
    phi = np.arctan2(axis[1], axis[0])
    t = vtk.vtkTransform()
    t.PostMultiply()
    t.RotateY(theta * 57.3)
    t.RotateZ(phi * 57.3)
    t.Scale(r, r, r)
    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetInputData(contours.GetOutput())
    tf.SetTransform(t)
    tf.Update()
    pd = tf.GetOutput()

    actor = Actor(pd, c=c, alpha=alpha, legend=legend, texture=texture)
    actor.GetProperty().SetInterpolationToPhong()
    actor.GetMapper().ScalarVisibilityOff()
    actor.SetPosition(pos)
    return actor
Esempio n. 20
0
    def __init__(self, geom, ident=None):

        self.src = vtkContourFilter()

        ODE_Object.__init__(self, geom, ident)

        (radius, height) = geom.getParams()

        cylinder = vtkCylinder()
        cylinder.SetRadius(radius)

        vertPlane = vtkPlane()
        vertPlane.SetOrigin(0, height / 2, 0)
        vertPlane.SetNormal(0, 1, 0)

        basePlane = vtkPlane()
        basePlane.SetOrigin(0, -height / 2, 0)
        basePlane.SetNormal(0, -1, 0)

        sphere_1 = vtkSphere()
        sphere_1.SetCenter(0, -height / 2, 0)
        sphere_1.SetRadius(radius)

        sphere_2 = vtkSphere()
        sphere_2.SetCenter(0, height / 2, 0)
        sphere_2.SetRadius(radius)

        # Combine primitives, Clip the cone with planes.
        cylinder_fct = vtkImplicitBoolean()
        cylinder_fct.SetOperationTypeToIntersection()
        cylinder_fct.AddFunction(cylinder)
        cylinder_fct.AddFunction(vertPlane)
        cylinder_fct.AddFunction(basePlane)

        # Take a bite out of the ice cream.
        capsule = vtkImplicitBoolean()
        capsule.SetOperationTypeToUnion()
        capsule.AddFunction(cylinder_fct)
        capsule.AddFunction(sphere_1)
        capsule.AddFunction(sphere_2)

        capsule_fct = vtkSampleFunction()
        capsule_fct.SetImplicitFunction(capsule)
        capsule_fct.ComputeNormalsOff()
        capsule_fct.SetModelBounds(-height - radius, height + radius,
                                   -height - radius, height + radius,
                                   -height - radius, height + radius)

        self.src.SetInputConnection(capsule_fct.GetOutputPort())
        self.src.SetValue(0, 0.0)
Esempio n. 21
0
def main():
    colors = vtk.vtkNamedColors()

    # create an ellipsoid using a implicit quadric
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0)

    # The sample function generates a distance function from the implicit
    # function. This is then contoured to get a polygonal surface.
    sample = vtk.vtkSampleFunction()
    sample.SetImplicitFunction(quadric)
    sample.SetModelBounds(-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)
    sample.SetSampleDimensions(40, 40, 40)
    sample.ComputeNormalsOff()

    # contour
    surface = vtk.vtkContourFilter()
    surface.SetInputConnection(sample.GetOutputPort())
    surface.SetValue(0, 0.0)

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(surface.GetOutputPort())
    mapper.ScalarVisibilityOff()
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().EdgeVisibilityOn()
    actor.GetProperty().SetColor(colors.GetColor3d('AliceBlue'))
    actor.GetProperty().SetEdgeColor(colors.GetColor3d('SteelBlue'))

    # A renderer and render window
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Silver'))

    # add the actor
    renderer.AddActor(actor)

    # render window
    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    renwin.SetWindowName('ImplicitQuadric')

    # An interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    # Start
    interactor.Initialize()
    renwin.Render()
    interactor.Start()
Esempio n. 22
0
def Hyperboloid(pos=(0, 0, 0),
                a2=1,
                value=0.5,
                height=1,
                axis=(0, 0, 1),
                c="magenta",
                alpha=1,
                res=100):
    """
    Build a hyperboloid of specified aperture `a2` and `height`, centered at `pos`.

    Full volumetric expression is:
        :math:`F(x,y,z)=a_0x^2+a_1y^2+a_2z^2+a_3xy+a_4yz+a_5xz+ a_6x+a_7y+a_8z+a_9`

    .. hint:: |mesh_bands| |mesh_bands.py|_
    """
    q = vtk.vtkQuadric()
    q.SetCoefficients(2, 2, -1 / a2, 0, 0, 0, 0, 0, 0, 0)
    # F(x,y,z) = a0*x^2 + a1*y^2 + a2*z^2
    #         + a3*x*y + a4*y*z + a5*x*z
    #         + a6*x   + a7*y   + a8*z  +a9
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(res, res, res)
    sample.SetImplicitFunction(q)

    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(1, value, value)
    contours.Update()

    axis = np.array(axis) / np.linalg.norm(axis)
    theta = np.arccos(axis[2])
    phi = np.arctan2(axis[1], axis[0])
    t = vtk.vtkTransform()
    t.PostMultiply()
    t.RotateY(np.rad2deg(theta))
    t.RotateZ(np.rad2deg(phi))
    t.Scale(1, 1, height)
    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetInputData(contours.GetOutput())
    tf.SetTransform(t)
    tf.Update()
    pd = tf.GetOutput()

    actor = Actor(pd, c, alpha).flipNormals()
    actor.GetProperty().SetInterpolationToPhong()
    actor.mapper.ScalarVisibilityOff()
    actor.SetPosition(pos)
    settings.collectable_actors.append(actor)
    return actor
Esempio n. 23
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the background color.
    colors.SetColor("BkgColor", [51, 77, 102, 255])

    sphere = vtk.vtkSphere()

    # Sample the function
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(50, 50, 50)
    sample.SetImplicitFunction(sphere)
    value = 2.0
    xmin = -value
    xmax = value
    ymin = -value
    ymax = value
    zmin = -value
    zmax = value
    sample.SetModelBounds(xmin, xmax, ymin, ymax, zmin, zmax)

    # Create the 0 isosurface
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(1, 1, 1)

    # Map the contours to graphical primitives
    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInputConnection(contours.GetOutputPort())
    contourMapper.ScalarVisibilityOff()

    # Create an actor for the contours
    contourActor = vtk.vtkActor()
    contourActor.SetMapper(contourMapper)

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName('ImplicitSphere')

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

    renderer.AddActor(contourActor)
    renderer.SetBackground(colors.GetColor3d("BkgColor"))

    renderWindow.Render()
    interactor.Start()
Esempio n. 24
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()

        sphere1 = vtk.vtkSphere()
        sphere1.SetCenter(0.9, 0, 0)
        sphere2 = vtk.vtkSphere()
        sphere2.SetCenter(-0.9, 0, 0)

        implicitBoolean = vtk.vtkImplicitBoolean()
        implicitBoolean.AddFunction(sphere1)
        implicitBoolean.AddFunction(sphere2)
        implicitBoolean.SetOperationTypeToUnion()
        #implicitBoolean.SetOperationTypeToIntersection()

        # Sample the function
        sample = vtk.vtkSampleFunction()
        sample.SetSampleDimensions(50, 50, 50)
        sample.SetImplicitFunction(implicitBoolean)
        sample.SetModelBounds(-3, 3, -3, 3, -3, 3)

        # Create the 0 isosurface
        contours = vtk.vtkContourFilter()
        contours.SetInputConnection(sample.GetOutputPort())
        contours.GenerateValues(1, 1, 1)

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

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

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

        self._initialized = False
Esempio n. 25
0
def LST_create_mirror_plane():
    # create a sphere
    sphere = vtk.vtkSphere()
    sphere.SetRadius(12)
    sphere.SetCenter(0, 0, 0)

    # create a box
    box = vtk.vtkSphere()
    box.SetRadius(28.)
    box.SetCenter(25, 0, 0)

    # box = vtk.vtkBox()
    # box.SetBounds(-1, 1, -1, 1, -1, 1)

    # combine the two implicit functions
    boolean = vtk.vtkImplicitBoolean()
    boolean.SetOperationTypeToDifference()

    # boolean.SetOperationTypeToUnion()
    # boolean.SetOperationTypeToIntersection()
    boolean.AddFunction(sphere)
    boolean.AddFunction(box)

    # The sample function generates a distance function from the implicit
    # function. This is then contoured to get a polygonal surface.
    sample = vtk.vtkSampleFunction()
    sample.SetImplicitFunction(boolean)
    sample.SetModelBounds(-50, 50, -50, 50, -50, 50)
    sample.SetSampleDimensions(200, 200, 200)
    sample.ComputeNormalsOff()

    # contour
    surface = vtk.vtkContourFilter()
    surface.SetInputConnection(sample.GetOutputPort())
    surface.SetValue(0, 0.0)

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(surface.GetOutputPort())
    #mapper.ScalarVisibilityOff()
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    #actor.GetProperty().EdgeVisibilityOn()
    actor.GetProperty().SetColor(tomato)
    # actor.SetPosition(cam_height, 0, 0)

    return actor
Esempio n. 26
0
def make_blob(n, radius):
    blob_image = vtk.vtkImageData()

    max_r = 50 - 2.0 * radius
    random_sequence = vtk.vtkMinimalStandardRandomSequence()
    random_sequence.SetSeed(5071)
    for i in range(0, n):

        sphere = vtk.vtkSphere()
        sphere.SetRadius(radius)

        x = random_sequence.GetRangeValue(-max_r, max_r)
        random_sequence.Next()
        y = random_sequence.GetRangeValue(-max_r, max_r)
        random_sequence.Next()
        z = random_sequence.GetRangeValue(-max_r, max_r)
        random_sequence.Next()

        sphere.SetCenter(int(x), int(y), int(z))

        sampler = vtk.vtkSampleFunction()
        sampler.SetImplicitFunction(sphere)
        sampler.SetOutputScalarTypeToFloat()
        sampler.SetSampleDimensions(100, 100, 100)
        sampler.SetModelBounds(-50, 50, -50, 50, -50, 50)

        thres = vtk.vtkImageThreshold()
        thres.SetInputConnection(sampler.GetOutputPort())
        thres.ThresholdByLower(radius * radius)
        thres.ReplaceInOn()
        thres.ReplaceOutOn()
        thres.SetInValue(i + 1)
        thres.SetOutValue(0)
        thres.Update()
        if i == 0:
            blob_image.DeepCopy(thres.GetOutput())

        max_value = vtk.vtkImageMathematics()
        max_value.SetInputData(0, blob_image)
        max_value.SetInputData(1, thres.GetOutput())
        max_value.SetOperationToMax()
        max_value.Modified()
        max_value.Update()

        blob_image.DeepCopy(max_value.GetOutput())

    return blob_image
Esempio n. 27
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()
 
        sphere1 = vtk.vtkSphere()
        sphere1.SetCenter(0.9, 0, 0)
        sphere2 = vtk.vtkSphere()
        sphere2.SetCenter(-0.9, 0, 0)

        implicitBoolean = vtk.vtkImplicitBoolean()
        implicitBoolean.AddFunction(sphere1)
        implicitBoolean.AddFunction(sphere2)
        implicitBoolean.SetOperationTypeToUnion()
        #implicitBoolean.SetOperationTypeToIntersection()

        # Sample the function
        sample = vtk.vtkSampleFunction()
        sample.SetSampleDimensions(50, 50, 50)
        sample.SetImplicitFunction(implicitBoolean)
        sample.SetModelBounds(-3, 3, -3, 3, -3, 3)

        # Create the 0 isosurface
        contours = vtk.vtkContourFilter()
        contours.SetInputConnection(sample.GetOutputPort())
        contours.GenerateValues(1, 1, 1)
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(contours.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Esempio n. 28
0
def Paraboloid(
        pos=(0, 0, 0), r=1, height=1, axis=(0, 0, 1), c="cyan", alpha=1,
        res=50):
    """
    Build a paraboloid of specified height and radius `r`, centered at `pos`.

    .. note::
        Full volumetric expression is:
            :math:`F(x,y,z)=a_0x^2+a_1y^2+a_2z^2+a_3xy+a_4yz+a_5xz+ a_6x+a_7y+a_8z+a_9`

            |paraboloid|
    """
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(1, 1, 0, 0, 0, 0, 0, 0, height / 4, 0)
    # F(x,y,z) = a0*x^2 + a1*y^2 + a2*z^2
    #         + a3*x*y + a4*y*z + a5*x*z
    #         + a6*x   + a7*y   + a8*z  +a9
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(res, res, res)
    sample.SetImplicitFunction(quadric)

    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(1, 0.01, 0.01)
    contours.Update()

    axis = np.array(axis) / np.linalg.norm(axis)
    theta = np.arccos(axis[2])
    phi = np.arctan2(axis[1], axis[0])
    t = vtk.vtkTransform()
    t.PostMultiply()
    t.RotateY(np.rad2deg(theta))
    t.RotateZ(np.rad2deg(phi))
    t.Scale(r, r, r)
    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetInputData(contours.GetOutput())
    tf.SetTransform(t)
    tf.Update()
    pd = tf.GetOutput()

    actor = Actor(pd, c, alpha).flipNormals()
    actor.GetProperty().SetInterpolationToPhong()
    actor.mapper.ScalarVisibilityOff()
    actor.SetPosition(pos)
    settings.collectable_actors.append(actor)
    return actor
Esempio n. 29
0
  def drawPlane(self, m, V_norm):
    scene = slicer.mrmlScene

    #create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0)
    planex=vtk.vtkPlane()
    planex.SetOrigin(m[0],m[1],m[2])
    planex.SetNormal(V_norm[0],V_norm[1],V_norm[2])

    renderer = slicer.app.layoutManager().threeDWidget(0).threeDView().renderWindow().GetRenderers().GetFirstRenderer()
    viewSize = renderer.ComputeVisiblePropBounds()
    #viewSize = (-50.0, 50.0, -50.0, 50.0, -50.0, 50.0)


    planexSample = vtk.vtkSampleFunction()
    planexSample.SetImplicitFunction(planex)
    planexSample.SetModelBounds(viewSize)
    #planexSample.SetSampleDimensions(200,200,200)
    planexSample.ComputeNormalsOff()
    plane1 = vtk.vtkContourFilter()
    plane1.SetInputConnection(planexSample.GetOutputPort())


    # Create model Plane A node
    planeA = slicer.vtkMRMLModelNode()
    planeA.SetScene(scene)
    planeA.SetName("X-Y Plane")
    planeA.SetAndObservePolyData(plane1.GetOutput())

    # Create display model Plane A node
    planeAModelDisplay = slicer.vtkMRMLModelDisplayNode()
    planeAModelDisplay.SetColor(0.145,0.77,0.596)
    
    planeAModelDisplay.BackfaceCullingOff()
    planeAModelDisplay.SetScene(scene)
    scene.AddNode(planeAModelDisplay)
    planeA.SetAndObserveDisplayNodeID(planeAModelDisplay.GetID())

    #Add to scene
    planeAModelDisplay.SetInputPolyDataConnection(plane1.GetOutputPort())
    scene.AddNode(planeA)

    # adjust center of 3d view to plane
    layoutManager = slicer.app.layoutManager()
    threeDWidget = layoutManager.threeDWidget(0)
    threeDView = threeDWidget.threeDView()
    threeDView.resetFocalPoint()
Esempio n. 30
0
    def add_ellipsoid(self,
                      center=[0, 0, 0],
                      orientation=[0, 0, 0],
                      radius=5.2,
                      color='blue',
                      opacity=1.0,
                      contours='latitude'):

        # create an ellipsoid using an implicit quadric
        quadric = vtk.vtkQuadric()
        quadric.SetCoefficients(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0)

        # The sample function generates a distance function from the implicit
        # function. This is then contoured to get a polygonal surface.
        sample = vtk.vtkSampleFunction()
        sample.SetImplicitFunction(quadric)
        sample.SetModelBounds(-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)
        sample.SetSampleDimensions(40, 40, 40)
        sample.ComputeNormalsOff()

        # contour
        surface = vtk.vtkContourFilter()
        surface.SetInputConnection(sample.GetOutputPort())
        surface.SetValue(0, 0.0)

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(surface.GetOutputPort())
        mapper.ScalarVisibilityOff()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().EdgeVisibilityOn()
        actor.GetProperty().SetColor(self.colors.GetColor3d('AliceBlue'))
        actor.GetProperty().SetEdgeColor(self.colors.GetColor3d('SteelBlue'))

        # Append elements
        self.sources.append(quadric)
        self.mappers.append(mapper)
        self.actors.append(actor)

        # add the actor
        self.renderer.AddActor(actor)

        # Initialize must be called prior to creating timer events.
        self.interactor.Initialize()
def hyperboloid(pos=[0, 0, 0],
                a2=1,
                value=0.5,
                height=1,
                axis=[0, 0, 1],
                c='magenta',
                alpha=1,
                legend=None,
                texture=None,
                res=50):
    '''
    Build a hyperboloid of specified aperture a2 and height, centered at pos.
    '''
    q = vtk.vtkQuadric()
    q.SetCoefficients(2, 2, -1 / a2, 0, 0, 0, 0, 0, 0, 0)
    #F(x,y,z) = a0*x^2 + a1*y^2 + a2*z^2
    #         + a3*x*y + a4*y*z + a5*x*z
    #         + a6*x   + a7*y   + a8*z  +a9
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(res, res, res)
    sample.SetImplicitFunction(q)

    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(1, value, value)
    contours.Update()

    axis = np.array(axis) / np.linalg.norm(axis)
    theta = np.arccos(axis[2])
    phi = np.arctan2(axis[1], axis[0])
    t = vtk.vtkTransform()
    t.PostMultiply()
    t.RotateY(theta * 57.3)
    t.RotateZ(phi * 57.3)
    t.Scale(1, 1, height)
    tf = vtk.vtkTransformPolyDataFilter()
    vu.setInput(tf, contours.GetOutput())
    tf.SetTransform(t)
    tf.Update()
    pd = tf.GetOutput()

    actor = vu.makeActor(pd, c=c, alpha=alpha, legend=legend, texture=texture)
    actor.GetProperty().SetInterpolationToPhong()
    actor.GetMapper().ScalarVisibilityOff()
    actor.SetPosition(pos)
    return actor
Esempio n. 32
0
def create_renderer_3(bone, skin):
    '''
    Return the third renderer
    bone: the bone dataset
    skin: the skin dataset
    '''
    # creating the sphere clipping
    radius = 60
    center = [70, 30, 100]
    sphere = vtk.vtkSphere()
    sphere.SetRadius(radius)
    sphere.SetCenter(center)

    # clipping
    clipper = vtk.vtkClipDataSet()
    clipper.SetClipFunction(sphere)
    clipper.SetInputConnection(skin.GetOutputPort())
    skin = clipper

    # creating actors
    bone_actor = create_actor(bone)
    bone_actor.GetProperty().SetColor(0.94, 0.94, 0.94)

    skin_actor = create_actor(skin)
    skin_actor.GetProperty().SetColor(0.8, 0.62, 0.62)

    # creating the sphere actor ----
    # sampling using the sphere implicit function
    sample = vtk.vtkSampleFunction()
    sample.SetImplicitFunction(sphere)
    sample.SetSampleDimensions(50, 50, 50)
    sample.SetModelBounds(center[0] - radius, center[0] + radius,
                          center[1] - radius, center[1] + radius,
                          center[2] - radius, center[2] + radius)
    # contouring. The sphere is described by a 0 iso-value
    sphere_actor = create_iso_actor(sample, 0)
    # design
    sphere_actor.GetProperty().SetColor(0.85, 0.8, 0.1)
    sphere_actor.GetProperty().SetOpacity(0.15)

    # creating renderer
    ren = create_renderer([bone_actor, skin_actor, sphere_actor])
    ren.SetBackground(0.827, 0.824, 1)

    return ren
Esempio n. 33
0
    def opImplement(self):
         
        
        sample_implicit = vtk.vtkSampleFunction();
        #sample_implicit.CappingOn();
        sample_implicit.ComputeNormalsOn();
        #sample_implicit.SetCapValue(.05);
        from math import ceil;
        from random import randint;

        x_len = self.bbox.x_max  - self.bbox.x_min ;
        y_len = self.bbox.y_max -self.bbox.y_min ;
        z_len = self.bbox.z_max -self.bbox.z_min ;
        x_res = int(ceil(x_len/self.resoulation[0]));
        y_res = int(ceil(y_len/self.resoulation[1]));
        z_res = int(ceil(z_len/self.resoulation[2]));
        
        import time;
        threshold = 1.5;
        #Main slower....
        #sample_implicit.SetSampleDimensions(x_res,y_res,z_res);
        sample_implicit.SetSampleDimensions(int(VOLUME_SETP),int(VOLUME_SETP),int(VOLUME_SETP));
        #sample_implicit.SetSampleDimensions(100,100,100);
        sample_implicit.SetImplicitFunction(self.data);
        sample_implicit.SetOutputScalarTypeToUnsignedChar();
        sample_implicit.SetModelBounds(self.bbox.x_min * threshold,self.bbox.x_max * threshold,self.bbox.y_min * threshold,self.bbox.y_max * threshold,self.bbox.z_min * threshold,self.bbox.z_max * threshold);
        sample_implicit.Update();
        sampled_result = sample_implicit.GetOutput();

        #Difference between Marching cubes and contour filter?????
        structed_point2Poly = vtk.vtkMarchingCubes();
        #structed_point2Poly = vtk.vtkContourFilter();
        structed_point2Poly.SetInputData(sampled_result);
        structed_point2Poly.ComputeScalarsOff();
        structed_point2Poly.ComputeNormalsOff();
        structed_point2Poly.ComputeGradientsOff();
        structed_point2Poly.GenerateValues(1,1,1);
        #structed_point2Poly.SetValue(0,int(IMAGEIN+1)); #threshold
        structed_point2Poly.SetValue(0,int((IMAGEIN+IMAGEOUT)/2.0)); #threshold
        structed_point2Poly.Update();
                
        result = structed_point2Poly.GetOutput();
        return result;
Esempio n. 34
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 the quadric function definition
        quadric = vtk.vtkQuadric()
        quadric.SetCoefficients(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0)
        #quadric.SetCoefficients(0.5, 0, 0.2, 0, 0, 0, 0, 0, 0, -0.1)

        # Sample the quadric function
        sample = vtk.vtkSampleFunction()
        sample.SetSampleDimensions(50, 50, 50)
        sample.SetImplicitFunction(quadric)
        sample.SetModelBounds(-1, 1, -1, 1, -1, 1)

        contourFilter = vtk.vtkContourFilter()
        contourFilter.SetInputConnection(sample.GetOutputPort())
        #contourFilter.GenerateValues(1, 1, 1)
        contourFilter.Update()
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(contourFilter.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Esempio n. 35
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 the quadric function definition
        quadric = vtk.vtkQuadric()
        quadric.SetCoefficients(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0)
        #quadric.SetCoefficients(0.5, 0, 0.2, 0, 0, 0, 0, 0, 0, -0.1)

        # Sample the quadric function
        sample = vtk.vtkSampleFunction()
        sample.SetSampleDimensions(50, 50, 50)
        sample.SetImplicitFunction(quadric)
        sample.SetModelBounds(-1, 1, -1, 1, -1, 1)

        contourFilter = vtk.vtkContourFilter()
        contourFilter.SetInputConnection(sample.GetOutputPort())
        #contourFilter.GenerateValues(1, 1, 1)
        contourFilter.Update()

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

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

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

        self._initialized = False
Esempio n. 36
0
    def Execute(self):

        if self.Seeds == None:
            self.PrintError('Error: No input seeds.')

        rbf = vtkvmtk.vtkvmtkRBFInterpolation()
        rbf.SetSource(self.Seeds)
        if self.RBFType == "thinplatespline":
            rbf.SetRBFTypeToThinPlateSpline()
        elif self.RBFType == "biharmonic":
            rbf.SetRBFTypeToBiharmonic()
        elif self.RBFType == "triharmonic":
            rbf.SetRBFTypeToTriharmonic()
        rbf.ComputeCoefficients()

        if self.Image:
            origin = self.Image.GetOrigin()
            spacing = self.Image.GetSpacing()
            extent = self.Image.GetExtent()
            dimensions = self.Image.GetDimensions()
            modelBounds = [0.0,0.0,0.0,0.0,0.0,0.0]
            modelBounds[0] = origin[0] + spacing[0]*extent[0]
            modelBounds[1] = origin[0] + spacing[0]*extent[1]
            modelBounds[2] = origin[1] + spacing[1]*extent[2]
            modelBounds[3] = origin[1] + spacing[1]*extent[3]
            modelBounds[4] = origin[2] + spacing[2]*extent[4]
            modelBounds[5] = origin[2] + spacing[2]*extent[5]
        else:
            dimensions = self.Dimensions
            modelBounds = self.Bounds
        
        sampleFunction = vtk.vtkSampleFunction()
        sampleFunction.SetImplicitFunction(rbf)
        sampleFunction.SetOutputScalarTypeToDouble()
        sampleFunction.SetSampleDimensions(dimensions)
        sampleFunction.SetModelBounds(modelBounds)
        sampleFunction.CappingOff()
        sampleFunction.ComputeNormalsOff()
        sampleFunction.Update()
        
        self.Image = sampleFunction.GetOutput() 
Esempio n. 37
0
    def drawPlane(self, m, V_norm):

        scene = slicer.mrmlScene
        #create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0)
        planex = vtk.vtkPlane()
        planex.SetOrigin(m[0], m[1], m[2])
        planex.SetNormal(V_norm[0], V_norm[1], V_norm[2])
        renderer = slicer.app.layoutManager().threeDWidget(
            0).threeDView().renderWindow().GetRenderers().GetFirstRenderer()
        viewSize = renderer.ComputeVisiblePropBounds()
        planexSample = vtk.vtkSampleFunction()
        planexSample.SetImplicitFunction(planex)
        planexSample.SetModelBounds(viewSize)
        planexSample.SetSampleDimensions(50, 50, 50)
        planexSample.ComputeNormalsOff()
        plane1 = vtk.vtkContourFilter()
        plane1.SetInputConnection(planexSample.GetOutputPort())
        # Create model Plane A node
        planeA = slicer.vtkMRMLModelNode()
        planeA.SetScene(scene)
        planeA.SetName("Symmetry Plane")
        planeA.SetAndObservePolyData(plane1.GetOutput())
        # Create display model Plane A node
        planeAModelDisplay = slicer.vtkMRMLModelDisplayNode()
        planeAModelDisplay.SetColor(0, 170, 127)
        planeAModelDisplay.BackfaceCullingOff()
        planeAModelDisplay.SetScene(scene)
        scene.AddNode(planeAModelDisplay)
        planeA.SetAndObserveDisplayNodeID(planeAModelDisplay.GetID())
        #Add to scene
        planeAModelDisplay.SetInputPolyDataConnection(plane1.GetOutputPort())
        scene.AddNode(planeA)
        # adjust center of 3d view to plane
        layoutManager = slicer.app.layoutManager()
        threeDWidget = layoutManager.threeDWidget(0)
        threeDView = threeDWidget.threeDView()
        threeDView.resetFocalPoint()

        return plane1
Esempio n. 38
0
def create_renderer():
    """
    vtk renderer with a sample scene
    """
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(50, 50, 50)
    sample.SetImplicitFunction(quadric)

    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(5, 0.0, 1.2)

    contour_mapper = vtk.vtkPolyDataMapper()
    contour_mapper.SetInputConnection(contours.GetOutputPort())
    contour_mapper.SetScalarRange(0.0, 1.2)

    contour_actor = vtk.vtkActor()
    contour_actor.SetMapper(contour_mapper)

    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    outline_mapper = vtk.vtkPolyDataMapper()
    outline_mapper.SetInputConnection(outline.GetOutputPort())

    outline_actor = vtk.vtkActor()
    outline_actor.SetMapper(outline_mapper)
    outline_actor.GetProperty().SetColor(0, 0, 0)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(contour_actor)
    renderer.AddActor(outline_actor)
    renderer.SetBackground(.75, .75, .75)

    return renderer
Esempio n. 39
0
def main():
    colors = vtk.vtkNamedColors()
    perlinNoise = vtk.vtkPerlinNoise()
    perlinNoise.SetFrequency(2, 1.25, 1.5)
    perlinNoise.SetPhase(0, 0, 0)

    sample = vtk.vtkSampleFunction()
    sample.SetImplicitFunction(perlinNoise)
    sample.SetSampleDimensions(65, 65, 20)
    sample.ComputeNormalsOff()

    surface = vtk.vtkContourFilter()
    surface.SetInputConnection(sample.GetOutputPort())
    surface.SetValue(0, 0.0)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(surface.GetOutputPort())
    mapper.ScalarVisibilityOff()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('SteelBlue'))

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    # Add the actors to the renderer, set the background and size
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    renderWindow.SetWindowName('PerlinNoise')
    renderWindow.SetSize(300, 300)
    renderer.ResetCamera()
    renderWindow.Render()
    interactor.Start()
Esempio n. 40
0
def create_renderer():
    """
    vtk renderer with a sample scene
    """
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(50, 50, 50)
    sample.SetImplicitFunction(quadric)

    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(5, 0.0, 1.2)

    contour_mapper = vtk.vtkPolyDataMapper()
    contour_mapper.SetInputConnection(contours.GetOutputPort())
    contour_mapper.SetScalarRange(0.0, 1.2)

    contour_actor = vtk.vtkActor()
    contour_actor.SetMapper(contour_mapper)

    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    outline_mapper = vtk.vtkPolyDataMapper()
    outline_mapper.SetInputConnection(outline.GetOutputPort())

    outline_actor = vtk.vtkActor()
    outline_actor.SetMapper(outline_mapper)
    outline_actor.GetProperty().SetColor(0, 0, 0)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(contour_actor)
    renderer.AddActor(outline_actor)
    renderer.SetBackground(.75, .75, .75)

    return renderer
Esempio n. 41
0
def Ellipsoid(center, color, U):
    # create the quadric function definition
    a0 = U[0][0]
    a1 = U[1][1]
    a2 = U[2][2]
    a3 = 2*U[0][1]
    a4 = 2*U[1][2]
    a5 = 2*U[0][2]
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(a0,a1,a2,a3,a4,a5,0,0,0,-1.5282)
    # F(x,y,z) = a0*x^2 + a1*y^2 + a2*z^2 + a3*x*y + a4*y*z + a5*x*z + a6*x + a7*y + a8*z + a9
 
    # sample the quadric function
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(36,36,36)
    sample.SetImplicitFunction(quadric)
    sample.SetModelBounds(-2, 2, -2, 2, -2, 2)
 
    #create the 0 isosurface
    contours = vtk.vtkContourFilter()
    contours.SetInput(sample.GetOutput())
    contours.GenerateValues(1,1,1)

    transform = vtk.vtkTransform()
    transform.Translate(center)
 
    # map the contours to graphical primitives
    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInput(contours.GetOutput())
    contourMapper.ScalarVisibilityOff()
 
    # create an actor for the contours
    contourActor = vtk.vtkActor()
    contourActor.SetMapper(contourMapper)
    contourActor.GetProperty().SetColor(color) # (R,G,B)
    contourActor.SetUserTransform(transform)
    return contourActor
Esempio n. 42
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        # setup config
        self._config.sampleDimensions = (64, 64, 64)
        self._config.modelBounds = (-1, 1, -1, 1, -1, 1)
        # we init normals to off, they EAT memory (3 elements per point!)
        self._config.computeNormals = False

        # and then our scripted config
        configList = [
            ('Sample dimensions: ', 'sampleDimensions', 'tuple:int,3',
             'text', 'The dimensions of the output volume.'),
            ('Model bounds: ', 'modelBounds', 'tuple:float,6', 'text',
             'Region in world space over which the sampling is performed.'),
            ('Compute normals: ', 'computeNormals', 'base:bool', 'checkbox',
             'Must normals also be calculated and stored.')]

        
        # now create the necessary VTK modules
        self._sampleFunction = vtk.vtkSampleFunction()
        # this is more than good enough.
        self._sampleFunction.SetOutputScalarTypeToFloat()
        # setup progress for the processObject
        module_utils.setup_vtk_object_progress(self, self._sampleFunction,
                                           "Sampling implicit function.")
        

        self._example_input = None

        # mixin ctor
        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)' : self,
             'vtkSampleFunction' : self._sampleFunction})

        self.sync_module_logic_with_config()
    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.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Construct a Cylinder from (x1, y1, z1) to (x2, y2, z2), the inner and outer radius r1, r2
        x1, y1, z1 = 10, 2, 3
        x2, y2, z2 = 10, 20, 30
        r1, r2 = 3, 8

        dx, dy, dz = x2-x1, y2-y1, z2-z1

        # create axis object
        axisSource = vtk.vtkLineSource()
        axisSource = vtk.vtkLineSource()
        axisSource.SetPoint1(x1, y1, z1)
        axisSource.SetPoint2(x2, y2, z2)
        axisMapper = vtk.vtkPolyDataMapper()
        axisMapper.SetInputConnection(axisSource.GetOutputPort())
        axisActor = vtk.vtkActor()
        axisActor.GetProperty().SetColor(0, 0, 1)
        axisActor.SetMapper(axisMapper)
        self.ren.AddActor(axisActor)

        # Create planes
        plane1 = vtk.vtkPlane()
        plane1.SetOrigin(x1, y1, z1)
        plane1.SetNormal(-dx, -dy, -dz)

        plane2 = vtk.vtkPlane()
        plane2.SetOrigin(x2, y2, z2)
        plane2.SetNormal(dx, dy, dz)
 
        # Create cylinders
        out_cylinder = vtk.vtkCylinder()
        out_cylinder.SetCenter(0, 0, 0)
        out_cylinder.SetRadius(r2)

        in_cylinder = vtk.vtkCylinder()
        in_cylinder.SetCenter(0, 0, 0)
        in_cylinder.SetRadius(r1)

        # The rotation axis of cylinder is along the y-axis
        # What we need is the axis (x2-x1, y2-y1, z2-z1)
        angle = math.acos(dy/math.sqrt(dx**2 + dy**2 + dz**2)) * 180.0 / math.pi
        transform = vtk.vtkTransform()
        transform.RotateWXYZ(-angle, dz, 1, -dx)
        transform.Translate(-x1, -y1, -z1)

        out_cylinder.SetTransform(transform)
        in_cylinder.SetTransform(transform)

        # Cutted object
        cuted = vtk.vtkImplicitBoolean()
        cuted.SetOperationTypeToIntersection()
        cuted.AddFunction(out_cylinder)
        cuted.AddFunction(plane1)
        cuted.AddFunction(plane2)

        cuted2 = vtk.vtkImplicitBoolean()
        cuted2.SetOperationTypeToDifference()
        cuted2.AddFunction(cuted)
        cuted2.AddFunction(in_cylinder)

        # Sample 
        sample = vtk.vtkSampleFunction()
        sample.SetImplicitFunction(cuted2)
        sample.SetModelBounds(-100 , 100 , -100 , 100 , -100 , 100)
        sample.SetSampleDimensions(300, 300, 300)
        sample.SetComputeNormals(0)

        # Filter
        surface = vtk.vtkContourFilter()
        surface.SetInputConnection(sample.GetOutputPort())
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(surface.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
# tree.
sph = vtk.vtkSphereSource()
sph.SetPhiResolution(6)
sph.SetThetaResolution(12)
sph.SetRadius(1)

# Three dataset types will be defined in the following: image data,
# structured grid, and unstructured grid. This sampling of datasets tests the
# three execution paths currently in the sphere tree.

# Create a synthetic image data: sample a sphere across a volume
sphere = vtk.vtkSphere()
sphere.SetCenter(0.0,0.0,0.0)
sphere.SetRadius(0.25)

image = vtk.vtkSampleFunction()
image.SetImplicitFunction(sphere)
image.SetModelBounds(-0.5,0.5, -0.5,0.5, -0.5,0.5)
image.SetSampleDimensions(res,res,res)
image.Update()

# Handy dandy filter converts image data to structured grid
sgrid = vtk.vtkImageDataToPointSet()
sgrid.SetInputConnection(image.GetOutputPort())
sgrid.Update()

# Convert the image data to unstructured grid
extractionSphere = vtk.vtkSphere()
extractionSphere.SetRadius(100)
extractionSphere.SetCenter(0,0,0)
#!/usr/bin/env python
import vtk

# Test vtkExtractCells
# Control test size
#res = 200
res = 50

# Test cell extraction
#
# Quadric definition
quadric = vtk.vtkQuadric()
quadric.SetCoefficients([.5,1,.2,0,.1,0,0,.2,0,0])
sample = vtk.vtkSampleFunction()
sample.SetSampleDimensions(res,res,res)
sample.SetImplicitFunction(quadric)
sample.ComputeNormalsOff()
sample.Update()

# Now extract the cells: use badly formed range
extract = vtk.vtkExtractCells()
extract.SetInputConnection(sample.GetOutputPort())
extract.AddCellRange(0,sample.GetOutput().GetNumberOfCells())

extrMapper = vtk.vtkDataSetMapper()
extrMapper.SetInputConnection(extract.GetOutputPort())
extrMapper.ScalarVisibilityOff()

extrActor = vtk.vtkActor()
extrActor.SetMapper(extrMapper)
extrActor.GetProperty().SetColor(.8,.4,.4)
Esempio n. 46
0
    mapper_axes_coor = vtk.vtkPolyDataMapper()
    mapper_axes_coor.SetInputConnection(axes_coor.GetOutputPort())
    actor_axes_coor = vtk.vtkActor()
    actor_axes_coor.SetMapper(mapper_axes_coor)
    renderer_1.AddActor(actor_axes_coor)
    renderer_2.AddActor(actor_axes_coor)

    iren.Initialize()
    iren.Start()

# ===========================================================================
# Left view: Quadric defined with vtkQuadric
quadric_1 = vtk.vtkQuadric()
quadric_1.SetCoefficients(coef)

sample_1 = vtk.vtkSampleFunction()
sample_1.SetImplicitFunction(quadric_1)
sample_1.ComputeNormalsOff()

contour_1 = vtk.vtkContourFilter()
contour_1.SetInputConnection(sample_1.GetOutputPort())
contour_1.SetValue(0, contour_value)

# ===========================================================================
# Right view: Quadric defined with meshgrid
range_x = [-1, 1]
range_y = [-1, 1]
range_z = [-1, 1]
step = 0.05
offset = 0.1
step_x = np.arange(range_x[0] - offset, range_x[1] + offset, step)
# vtkCompositeDataSet

# Control test size
res = 50
#res = 250
serialProcessing = 0
mergePoints = 1
interpolateAttr = 0
computeNormals = 0
computeScalarRange = 0

#
# Quadric definition
quadricL = vtk.vtkQuadric()
quadricL.SetCoefficients([.5,1,.2,0,.1,0,0,.2,0,0])
sampleL = vtk.vtkSampleFunction()
sampleL.SetModelBounds(-1,0, -1,1, -1,1)
sampleL.SetSampleDimensions(int(res/2),res,res)
sampleL.SetImplicitFunction(quadricL)
sampleL.ComputeNormalsOn()
sampleL.Update()

#
# Quadric definition
quadricR = vtk.vtkQuadric()
quadricR.SetCoefficients([.5,1,.2,0,.1,0,0,.2,0,0])
sampleR = vtk.vtkSampleFunction()
sampleR.SetModelBounds(0,1, -1,1, -1,1)
sampleR.SetSampleDimensions(int(res/2),res,res)
sampleR.SetImplicitFunction(quadricR)
sampleR.ComputeNormalsOn()
Esempio n. 48
0
iceCream.SetRadius(0.5)
bite = vtk.vtkSphere()
bite.SetCenter(1.5,0,0.5)
bite.SetRadius(0.25)
# combine primitives to build ice-cream cone
theCone = vtk.vtkImplicitBoolean()
theCone.SetOperationTypeToIntersection()
theCone.AddFunction(cone)
theCone.AddFunction(vertPlane)
theCone.AddFunction(basePlane)
theCream = vtk.vtkImplicitBoolean()
theCream.SetOperationTypeToDifference()
theCream.AddFunction(iceCream)
theCream.AddFunction(bite)
# iso-surface to create geometry
theConeSample = vtk.vtkSampleFunction()
theConeSample.SetImplicitFunction(theCone)
theConeSample.SetModelBounds(-1,1.5,-1.25,1.25,-1.25,1.25)
theConeSample.SetSampleDimensions(60,60,60)
theConeSample.ComputeNormalsOff()
theConeSurface = vtk.vtkMarchingContourFilter()
theConeSurface.SetInputConnection(theConeSample.GetOutputPort())
theConeSurface.SetValue(0,0.0)
coneMapper = vtk.vtkPolyDataMapper()
coneMapper.SetInputConnection(theConeSurface.GetOutputPort())
coneMapper.ScalarVisibilityOff()
coneActor = vtk.vtkActor()
coneActor.SetMapper(coneMapper)
coneActor.GetProperty().SetColor(chocolate)
# iso-surface to create geometry
theCreamSample = vtk.vtkSampleFunction()
Esempio n. 49
0
    def makeModels(self):
        """
        make vtk model
        """

        # Here we create two ellipsoidal implicit functions and boolean them
        # together to form a "cross" shaped implicit function.
        quadric = vtk.vtkQuadric()
        quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

        sample = vtk.vtkSampleFunction()
        sample.SetSampleDimensions(50, 50, 50)
        sample.SetImplicitFunction(quadric)
        sample.ComputeNormalsOff()

        trans = vtk.vtkTransform()
        trans.Scale(1, .5, .333)
        sphere = vtk.vtkSphere()
        sphere.SetRadius(self.radius)
        sphere.SetTransform(trans)

        trans2 = vtk.vtkTransform()
        trans2.Scale(.25, .5, 1.0)
        sphere2 = vtk.vtkSphere()
        sphere2.SetRadius(self.radius)
        sphere2.SetTransform(trans2)

        self.sphere_geom_1 = sphere
        self.sphere_geom_2 = sphere2

        union = vtk.vtkImplicitBoolean()
        union.AddFunction(sphere)
        union.AddFunction(sphere2)
        union.SetOperationType(0)

        # Here is where it gets interesting. The implicit function is used to
        # extract those cells completely inside the function. They are then
        # shrunk to helpr show what was extracted.
        extract = vtk.vtkExtractGeometry()
        extract.SetInputConnection(sample.GetOutputPort())
        extract.SetImplicitFunction(union)
        shrink = vtk.vtkShrinkFilter()
        shrink.SetInputConnection(extract.GetOutputPort())
        shrink.SetShrinkFactor(self.shrink_factor)
        dataMapper = vtk.vtkDataSetMapper()
        dataMapper.SetInputConnection(shrink.GetOutputPort())

        self.shrink_geom = shrink

        # data actor
        self.data_actor = vtk.vtkActor()
        self.data_actor.SetMapper(dataMapper)

        # The outline gives context to the original data.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(sample.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())

        # outline actor
        self.outline_actor = vtk.vtkActor()
        self.outline_actor.SetMapper(outlineMapper)
        outlineProp = self.outline_actor.GetProperty()
        outlineProp.SetColor(0, 0, 0)