Exemplo n.º 1
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.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        superquadricSource = vtk.vtkSuperquadricSource()
        superquadricSource.SetPhiRoundness(3.1)
        superquadricSource.SetThetaRoundness(2.2)

        clipPlane = vtk.vtkPlane()
        clipPlane.SetNormal(1.0, -1.0, -1.0)
        clipPlane.SetOrigin(0, 0, 0)

        clipper = vtk.vtkClipPolyData()
        clipper.SetInputConnection(superquadricSource.GetOutputPort())
        clipper.SetClipFunction(clipPlane)

        superquadricMapper = vtk.vtkPolyDataMapper()
        superquadricMapper.SetInputConnection(clipper.GetOutputPort())

        superquadricActor = vtk.vtkActor()
        superquadricActor.SetMapper(superquadricMapper)

        #create renderers and add actors of plane and cube
        self.ren.AddActor(superquadricActor)

        self.ren.ResetCamera()
        self._initialized = False
Exemplo n.º 2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkSuperquadricSource(), 'Processing.',
         (), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
def MakeTorus():
    '''
    Make a torus as the source.
    :return: vtkPolyData with normal and scalar data.
    '''
    source = vtk.vtkSuperquadricSource();
    source.SetCenter(0.0, 0.0, 0.0)
    source.SetScale(1.0, 1.0, 1.0)
    source.SetPhiResolution(64)
    source.SetThetaResolution(64)
    source.SetThetaRoundness(1)
    source.SetThickness(0.5)
    source.SetSize(10)
    source.SetToroidal(1)

    # The quadric is made of strips, so pass it through a triangle filter as
    # the curvature filter only operates on polys
    tri = vtk.vtkTriangleFilter()
    tri.SetInputConnection(source.GetOutputPort())

    # The quadric has nasty discontinuities from the way the edges are generated
    # so let's pass it though a CleanPolyDataFilter and merge any points which
    # are coincident, or very close
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(tri.GetOutputPort())
    cleaner.SetTolerance(0.005)
    cleaner.Update()
    return CalculateCurvatures(MakeElevations(cleaner.GetOutput()))
Exemplo n.º 4
0
    def SuperquadricSource():
        """
        Make a torus as the source.
        """
        source = vtk.vtkSuperquadricSource()
        source.SetCenter(0.0, 0.0, 0.0)
        source.SetScale(1.0, 1.0, 1.0)
        source.SetPhiResolution(64)
        source.SetThetaResolution(64)
        source.SetThetaRoundness(1)
        source.SetThickness(0.5)
        source.SetSize(10)
        source.SetToroidal(1)

        # The quadric is made of strips, so pass it through a triangle filter as
        # the curvature filter only operates on polys
        tri = vtk.vtkTriangleFilter()
        tri.SetInputConnection(source.GetOutputPort())

        # The quadric has nasty discontinuities from the way the edges are generated
        # so let's pass it though a CleanPolyDataFilter and merge any points which
        # are coincident, or very close
        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputConnection(tri.GetOutputPort())
        cleaner.SetTolerance(0.005)
        cleaner.Update()
        cleanerBounds = cleaner.GetOutput().GetBounds()

        elev = vtk.vtkElevationFilter()
        elev.SetInputConnection(cleaner.GetOutputPort())
        elev.SetLowPoint(0, cleanerBounds[2], 0)
        elev.SetHighPoint(0, cleanerBounds[3], 0)
        elev.Update()
        return elev
Exemplo n.º 5
0
    def add_superquadric(self):
        """Add a new superquadric at a random position.

        This is called by the event handler for the 'Add Superquadric'
        button.
        """

        import random

        # let's add a superquadric actor to the renderer
        sqs = vtk.vtkSuperquadricSource()
        sqs.ToroidalOn()
        sqs.SetSize(0.1) # default is 0.5
        m = vtk.vtkPolyDataMapper()
        m.SetInput(sqs.GetOutput())
        a = vtk.vtkActor()
        a.SetMapper(m)
        pos = [random.random() for _ in range(3)]
        a.SetPosition(pos)
        a.GetProperty().SetColor([random.random() for _ in range(3)])
        self.ren.AddActor(a)
        self.render()

        # add string to files listcontrol showing where the
        # superquadric was placed.
        self._view_frame.files_lc.InsertStringItem(
                sys.maxint, 'Position (%.2f, %.2f, %.2f)' % tuple(pos))
Exemplo n.º 6
0
def MakeTorus():
    """
    Make a torus as the source.
    :return: vtkPolyData with normal and scalar data.
    """
    source = vtk.vtkSuperquadricSource()
    source.SetCenter(0.0, 0.0, 0.0)
    source.SetScale(1.0, 1.0, 1.0)
    source.SetPhiResolution(64)
    source.SetThetaResolution(64)
    source.SetThetaRoundness(1)
    source.SetThickness(0.5)
    source.SetSize(10)
    source.SetToroidal(1)

    # The quadric is made of strips, so pass it through a triangle filter as
    # the curvature filter only operates on polys
    tri = vtk.vtkTriangleFilter()
    tri.SetInputConnection(source.GetOutputPort())

    # The quadric has nasty discontinuities from the way the edges are generated
    # so let's pass it though a CleanPolyDataFilter and merge any points which
    # are coincident, or very close
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(tri.GetOutputPort())
    cleaner.SetTolerance(0.005)
    cleaner.Update()
    return CalculateCurvatures(MakeElevations(cleaner.GetOutput()))
Exemplo n.º 7
0
    def add_superquadric(self):
        """Add a new superquadric at a random position.

        This is called by the event handler for the 'Add Superquadric'
        button.
        """

        import random

        # let's add a superquadric actor to the renderer
        sqs = vtk.vtkSuperquadricSource()
        sqs.ToroidalOn()
        sqs.SetSize(0.1)  # default is 0.5
        m = vtk.vtkPolyDataMapper()
        m.SetInput(sqs.GetOutput())
        a = vtk.vtkActor()
        a.SetMapper(m)
        pos = [random.random() for _ in range(3)]
        a.SetPosition(pos)
        a.GetProperty().SetColor([random.random() for _ in range(3)])
        self.ren.AddActor(a)
        self.render()

        # add string to files listcontrol showing where the
        # superquadric was placed.
        self._view_frame.files_lc.InsertStringItem(
            sys.maxint, 'Position (%.2f, %.2f, %.2f)' % tuple(pos))
Exemplo n.º 8
0
def main():
    res = 6
    plane = vtk.vtkPlaneSource()
    plane.SetResolution(res, res)
    colors = vtk.vtkElevationFilter()
    colors.SetInputConnection(plane.GetOutputPort())
    colors.SetLowPoint(-0.25, -0.25, -0.25)
    colors.SetHighPoint(0.25, 0.25, 0.25)
    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetInputData(colors.GetPolyDataOutput())
    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)
    planeActor.GetProperty().SetRepresentationToWireframe()

    # create simple poly data so we can apply glyph
    squad = vtk.vtkSuperquadricSource()

    def Glyph():
        """
        # procedure for generating glyphs
        :return:
        """
        xyz = glypher.GetPoint()
        x = xyz[0]
        y = xyz[1]
        length = glypher.GetInput(0).GetLength()
        scale = length / (2.0 * res)

        squad.SetScale(scale, scale, scale)
        squad.SetCenter(xyz)
        squad.SetPhiRoundness(abs(x) * 5.0)
        squad.SetThetaRoundness(abs(y) * 5.0)

    glypher = vtk.vtkProgrammableGlyphFilter()
    glypher.SetInputConnection(colors.GetOutputPort())
    glypher.SetSourceConnection(squad.GetOutputPort())
    glypher.SetGlyphMethod(Glyph)
    glyphMapper = vtk.vtkPolyDataMapper()
    glyphMapper.SetInputConnection(glypher.GetOutputPort())
    glyphActor = vtk.vtkActor()
    glyphActor.SetMapper(glyphMapper)

    colors = vtk.vtkNamedColors()

    # Create the rendering stuff
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetMultiSamples(0)
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    ren1.AddActor(planeActor)
    ren1.AddActor(glyphActor)
    ren1.SetBackground(colors.GetColor3d('White'))
    renWin.SetSize(450, 450)
    renWin.Render()

    iren.Start()
Exemplo n.º 9
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        # setup config
        self._config.toroidal = True
        self._config.thickness = 0.3333
        self._config.phiRoundness = 0.2
        self._config.thetaRoundness = 0.8
        self._config.size = 0.5

        self._config.center = (0, 0, 0)
        self._config.scale = (1, 1, 1)

        self._config.thetaResolution = 64
        self._config.phiResolution = 64

        # and then our scripted config
        configList = [
            ('Toroidal: ', 'toroidal', 'base:bool', 'checkbox',
             'Should the quadric be toroidal.'),
            ('Thickness: ', 'thickness', 'base:float', 'text',
             'Thickness of the toroid, scaled between 0 and 1'),
            ('Phi Roundness: ', 'phiRoundness', 'base:float', 'text',
             'Controls shape of superquadric'),
            ('Theta Roundness: ', 'thetaRoundness', 'base:float', 'text',
             'Controls shape of superquadric'),
            ('Size: ', 'size', 'base:float', 'text',
             'The size of the superquadric.'),
            ('Centre: ', 'center', 'tuple:float,3', 'text',
             'The translation transform of the resultant superquadric.'),
            ('Scale: ', 'scale', 'tuple:float,3', 'text',
             'The scale transformof the resultant superquadric.'),
            ('Theta resolution: ', 'thetaResolution', 'base:int', 'text',
             'The resolution of the output polydata'),
            ('Phi resolution: ', 'phiResolution', 'base:int', 'text',
             'The resolution of the output polydata')
        ]

        # now create the necessary VTK modules
        self._superquadric = vtk.vtkSuperquadric()
        self._superquadricSource = vtk.vtkSuperquadricSource()

        # we need these temporary outputs
        self._outputs = [self._superquadric, vtk.vtkPolyData()]

        # setup progress for the processObject
        module_utils.setup_vtk_object_progress(self, self._superquadricSource,
                                               "Synthesizing polydata.")

        # mixin ctor
        ScriptedConfigModuleMixin.__init__(
            self, configList, {
                'Module (self)': self,
                'vtkSuperquadric': self._superquadric,
                'vtkSuperquadricSource': self._superquadricSource
            })

        self.sync_module_logic_with_config()
Exemplo n.º 10
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        # setup config
        self._config.toroidal = True
        self._config.thickness = 0.3333
        self._config.phiRoundness = 0.2
        self._config.thetaRoundness = 0.8
        self._config.size = 0.5

        self._config.center = (0,0,0)
        self._config.scale = (1,1,1)

        self._config.thetaResolution = 64
        self._config.phiResolution = 64

        # and then our scripted config
        configList = [
            ('Toroidal: ', 'toroidal', 'base:bool', 'checkbox',
             'Should the quadric be toroidal.'),
            ('Thickness: ', 'thickness', 'base:float', 'text',
             'Thickness of the toroid, scaled between 0 and 1'),
            ('Phi Roundness: ', 'phiRoundness', 'base:float', 'text',
             'Controls shape of superquadric'),
            ('Theta Roundness: ', 'thetaRoundness', 'base:float', 'text',
             'Controls shape of superquadric'),
            ('Size: ', 'size', 'base:float', 'text',
             'The size of the superquadric.'),
            ('Centre: ', 'center', 'tuple:float,3', 'text',
             'The translation transform of the resultant superquadric.'),
            ('Scale: ', 'scale', 'tuple:float,3', 'text',
             'The scale transformof the resultant superquadric.'),
            ('Theta resolution: ', 'thetaResolution', 'base:int', 'text',
             'The resolution of the output polydata'),
            ('Phi resolution: ', 'phiResolution', 'base:int', 'text',
             'The resolution of the output polydata')]

        # now create the necessary VTK modules
        self._superquadric = vtk.vtkSuperquadric()
        self._superquadricSource = vtk.vtkSuperquadricSource()

        # we need these temporary outputs
        self._outputs = [self._superquadric, vtk.vtkPolyData()]
        
        # setup progress for the processObject
        module_utils.setup_vtk_object_progress(self, self._superquadricSource,
                                           "Synthesizing polydata.")

        # mixin ctor
        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)' : self,
             'vtkSuperquadric' : self._superquadric,
             'vtkSuperquadricSource' : self._superquadricSource})

        self.sync_module_logic_with_config()
Exemplo n.º 11
0
 def __init__(self, thetaresolution, phiresolution, thetaroundness,
              phiroundness):
     self.tres = thetaresolution
     self.phires = phiresolution
     self.tround = thetaroundness
     self.phiround = phiroundness
     self.probe = vtk.vtkProbeFilter()
     self.datacutmapper = vtk.vtkPolyDataMapper()
     self.dataCutActor = vtk.vtkActor()
     self.tensorEllipsoids = vtk.vtkTensorGlyph()
     self.superquad = vtk.vtkSuperquadricSource()
Exemplo n.º 12
0
def main():
    colors = vtk.vtkNamedColors()

    # Create a superquadric
    superquadricSource = vtk.vtkSuperquadricSource()
    superquadricSource.SetPhiRoundness(3.1)
    superquadricSource.SetThetaRoundness(1.0)
    superquadricSource.Update()  # needed to GetBounds later

    renderer = vtk.vtkRenderer()

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

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

    cubeAxesActor = vtk.vtkCubeAxesActor()
    cubeAxesActor.SetBounds(superquadricSource.GetOutput().GetBounds())
    cubeAxesActor.SetCamera(renderer.GetActiveCamera())
    cubeAxesActor.GetTitleTextProperty(0).SetColor(colors.GetColor3d('Red'))
    cubeAxesActor.GetLabelTextProperty(0).SetColor(colors.GetColor3d('Red'))

    cubeAxesActor.GetTitleTextProperty(1).SetColor(colors.GetColor3d('LimeGreen'))
    cubeAxesActor.GetLabelTextProperty(1).SetColor(colors.GetColor3d('LimeGreen'))

    cubeAxesActor.GetTitleTextProperty(2).SetColor(colors.GetColor3d('Blue'))
    cubeAxesActor.GetLabelTextProperty(2).SetColor(colors.GetColor3d('Blue'))

    cubeAxesActor.DrawXGridlinesOn()
    cubeAxesActor.DrawYGridlinesOn()
    cubeAxesActor.DrawZGridlinesOn()
    cubeAxesActor.SetGridLineLocation(cubeAxesActor.VTK_GRID_LINES_FURTHEST)

    cubeAxesActor.XAxisMinorTickVisibilityOff()
    cubeAxesActor.YAxisMinorTickVisibilityOff()
    cubeAxesActor.ZAxisMinorTickVisibilityOff()

    renderer.AddActor(cubeAxesActor)
    renderer.AddActor(superquadricActor)
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)

    renderer.ResetCamera()

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

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

    renderWindow.Render()
    renderWindowInteractor.Start()
Exemplo n.º 13
0
def GenTorus(programArguments):
    ''' programArguments: ini file containing model parameters'''
    
    # Load relevant parameters from ini file
    conf = ConfigObj(programArguments)
    parameters = conf['Parameters']
    majorCirc = parameters['surfaceLength']
    minorCirc = parameters['surfaceWidth']
    thetaMesh = parameters['xMesh']

    # Minor and major radii
    r = float(minorCirc)/(2*np.pi)
    R = float(majorCirc)/(2*np.pi)

    # Mesh sizes
    thetaResolution = int(thetaMesh)    
    phiResolution = int(thetaResolution*(R/r))
    
    # Generate a torus 
    torusSource = vtk.vtkSuperquadricSource()
    torusSource.SetCenter(0.0, 0.0, 0.0)
    torusSource.SetScale(1.0, 1.0, 1.0)
    torusSource.SetToroidal(1) 
    torusSource.SetThetaRoundness(1)
    torusSource.SetPhiRoundness(1)

    # SuperquadricSource reverses phi and theta to be confusing - this is not an error
    torusSource.SetPhiResolution(thetaResolution)   
    torusSource.SetThetaResolution(phiResolution)

    # Don't change these!
    torusSource.SetSize(R + r)      
    torusSource.SetThickness(r/R)    

    # The quadric has nasty discontinuities from the way the edges are generated
    # so let's pass it though a CleanPolyDataFilter and merge any points which
    # are coincident, or very close. First convert quads into triangles
    tri = vtk.vtkTriangleFilter()
    tri.SetInputConnection(torusSource.GetOutputPort())
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(tri.GetOutputPort())
    cleaner.SetTolerance(0.00005)
    cleaner.Update()
    
    outputFileName = "torus_R" + majorCirc + "_r" + minorCirc + "_mesh" + thetaMesh + ".vtp"

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetInputData(cleaner.GetOutput())
    writer.SetFileName(outputFileName)
    writer.Update()
    
    print "Saving output to file", outputFileName 
def make_polydata_actor(centers, normals, return_pdm=False, type='circle'):
    """ Create the actor and set colors

    :param return_pdm: if True give back the polydatamapper
    :param centers: list of centers as tuples 
    :param normals: list of list of normals as tuples
    """

    # In order to build the bounding box it is convenient to combine
    # All sources using a vtkAppenPolyData
    apd = vtk.vtkAppendPolyData()

    mappers = []
    # create source
    for i in range(len(centers)):
        normal = normals[i]
        if normal is None:
            source = vtk.vtkSphereSource()
            source.SetRadius(80)
        else:
            if type=='torus':
                source = vtk.vtkSuperquadricSource();
                source.SetScale(1.0, 1.0, 1.0)
                source.SetPhiResolution (16)
                source.SetThetaResolution(16)
                source.SetThetaRoundness (1)
                source.SetThickness (0.1)
                source.SetSize(100.5)
                source.SetToroidal(1)
                source.SetNormal(normal)
            elif type=='circle':
                source = vtk.vtkRegularPolygonSource()
                source.SetNumberOfSides(16)
                source.SetRadius(100)
                source.SetNormal(normal)
        source.SetCenter(*centers[i])
        apd.AddInput(source.GetOutput())
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(apd.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    if return_pdm:
        return actor, apd
    else:
        return actor
Exemplo n.º 15
0
def make_polydata_actor(centers, normals, return_pdm=False, type='circle'):
    """ Create the actor and set colors

    :param return_pdm: if True give back the polydatamapper
    :param centers: list of centers as tuples 
    :param normals: list of list of normals as tuples
    """

    # In order to build the bounding box it is convenient to combine
    # All sources using a vtkAppenPolyData
    apd = vtk.vtkAppendPolyData()

    mappers = []
    # create source
    for i in range(len(centers)):
        normal = normals[i]
        if normal is None:
            source = vtk.vtkSphereSource()
            source.SetRadius(80)
        else:
            if type == 'torus':
                source = vtk.vtkSuperquadricSource()
                source.SetScale(1.0, 1.0, 1.0)
                source.SetPhiResolution(16)
                source.SetThetaResolution(16)
                source.SetThetaRoundness(1)
                source.SetThickness(0.1)
                source.SetSize(100.5)
                source.SetToroidal(1)
                source.SetNormal(normal)
            elif type == 'circle':
                source = vtk.vtkRegularPolygonSource()
                source.SetNumberOfSides(16)
                source.SetRadius(100)
                source.SetNormal(normal)
        source.SetCenter(*centers[i])
        apd.AddInput(source.GetOutput())
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(apd.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    if return_pdm:
        return actor, apd
    else:
        return actor
Exemplo n.º 16
0
    def __init__(self, parent, id):
        # create wx.Frame and wxVTKRenderWindowInteractor to put in it
        wx.Frame.__init__(self, parent, id, "DRE wxVTK demo", size=(400, 400))

        # create a menu
        menuBar = wx.MenuBar()
        menu = wx.Menu()
        quitMenu = menu.Append(-1, "&Quit", "Quit")
        self.Bind(wx.EVT_MENU, self.onQuit, quitMenu)
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        # create a donut polydata source
        superquadric = vtk.vtkSuperquadricSource()
        superquadric.ToroidalOn()

        # connect it to Polydatamapper
        m = vtk.vtkPolyDataMapper()
        m.SetInput(superquadric.GetOutput())

        # create an actor to represent the donut in the scene
        a = vtk.vtkActor()
        a.SetMapper(m)
        a.GetProperty().SetColor(0.8, 0.5, 0.3)
        a.GetProperty().SetSpecular(0.3)

        # the render is a 3D Scene
        self.ren = vtk.vtkRenderer()
        self.ren.AddActor(a)
        self.ren.SetBackground(0.2, 0.5, 0.7)

        #make sure the RWI sizes to fill the frame
        self.rwi = wxVTKRenderWindow(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.rwi, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.Layout()

        # sequence of init is different
        self.rwi.Enable(1)

        # add created renderer to the RWI's buit-in renderer window
        self.rwi.GetRenderWindow().AddRenderer(self.ren)
Exemplo n.º 17
0
    def __init__(self, parent, id):
        # create wx.Frame and wxVTKRenderWindowInteractor to put in it
        wx.Frame.__init__(self, parent, id, "DRE wxVTK demo", size=(400,400))
        
        # create a menu
        menuBar = wx.MenuBar()
        menu = wx.Menu()
        quitMenu = menu.Append(-1, "&Quit", "Quit")
        self.Bind(wx.EVT_MENU, self.onQuit, quitMenu)
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)
        
        # create a donut polydata source
        superquadric = vtk.vtkSuperquadricSource()
        superquadric.ToroidalOn()
        
        # connect it to Polydatamapper
        m = vtk.vtkPolyDataMapper()
        m.SetInput(superquadric.GetOutput())
        
        # create an actor to represent the donut in the scene
        a = vtk.vtkActor()
        a.SetMapper(m)
        a.GetProperty().SetColor(0.8, 0.5, 0.3)
        a.GetProperty().SetSpecular(0.3)
        
        # the render is a 3D Scene
        self.ren = vtk.vtkRenderer()
        self.ren.AddActor(a)
        self.ren.SetBackground(0.2, 0.5, 0.7)

        #make sure the RWI sizes to fill the frame
        self.rwi = wxVTKRenderWindow(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.rwi, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.Layout()
        
        # sequence of init is different
        self.rwi.Enable(1)
        
        # add created renderer to the RWI's buit-in renderer window
        self.rwi.GetRenderWindow().AddRenderer(self.ren)
Exemplo n.º 18
0
    def testICPTransform(self):

        renWin = vtk.vtkRenderWindow()

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

        # Create objects

        sscale = {2:[0.7, 0.7, 0.7],
                  3:[0.5, 0.5, 0.5]}
        scenter = {2:[-0.25, 0.25, 0.0],
                   3:[ 0.4, -0.3, 0.0]}
        scolors = {2:[0.2, 0.6, 0.1],
                   3:[0.1, 0.2, 0.6]}

        s = dict() # The super quadric sources

        for sidx in range(1, 4):
            s.update({sidx:vtk.vtkSuperquadricSource()})
            s[sidx].ToroidalOff()
            s[sidx].SetThetaResolution(20)
            s[sidx].SetPhiResolution(20)
            s[sidx].SetPhiRoundness(0.7 + (sidx - 2) * 0.4)
            s[sidx].SetThetaRoundness(0.85 + (sidx - 1) * 0.4)
            if sidx in sscale:
                s[sidx].SetScale(sscale[sidx])
            if sidx in scenter:
                s[sidx].SetCenter(scenter[sidx])

            s[sidx].Update()

        ren = dict() # Renderers
        sm = dict() # Mappers for the super quadric source
        sa = dict() # Actors for the super quadric source
        fe = dict() # Feature edges
        fem = dict() # Feature edges mappers
        fea = dict() # Feature edges actors
        icp = dict() # Iterated closest point transforms

        # Create the renderers

        for ridx in range(1, 4):
            ren.update({ridx: vtk.vtkRenderer()})
            ren[ridx].SetViewport((ridx - 1) / 3.0, 0.0, ridx / 3.0, 1.0)
            ren[ridx].SetBackground(0.7, 0.8, 1.0)
            cam = ren[ridx].GetActiveCamera()
            cam.SetPosition(1.7, 1.4, 1.7)
            renWin.AddRenderer(ren[ridx])

            # renderer 1 has all 3 objects, render i has object 1 and i (i=2, 3)
            # add actors (corresponding to the objects) to each renderer
            # and ICP transforms from objects i or to 1.
            # object 1 has feature edges too.

            for sidx in range(1, 4):

                if ridx == 1 or sidx == 1 or ridx == sidx:
                    sm.update({ridx:{sidx:vtk.vtkPolyDataMapper()}})
                    sm[ridx][sidx].SetInputConnection(s[sidx].GetOutputPort())

                    sa.update({ridx:{sidx:vtk.vtkActor()}})
                    sa[ridx][sidx].SetMapper(sm[ridx][sidx])

                    prop = sa[ridx][sidx].GetProperty()
                    if sidx in scolors:
                        prop.SetColor(scolors[sidx])

                    if sidx == 1:
                        prop.SetOpacity(0.2)

                        fe.update({ridx:{sidx:vtk.vtkFeatureEdges()}})
                        src = s[sidx]
                        fe[ridx][sidx].SetInputConnection(src.GetOutputPort())
                        fe[ridx][sidx].BoundaryEdgesOn()
                        fe[ridx][sidx].ColoringOff()
                        fe[ridx][sidx].ManifoldEdgesOff()

                        fem.update({ridx:{sidx:vtk.vtkPolyDataMapper()}})
                        fem[ridx][sidx].SetInputConnection(fe[ridx][sidx].GetOutputPort())
                        fem[ridx][sidx].SetResolveCoincidentTopologyToPolygonOffset()

                        fea.update({ridx:{sidx:vtk.vtkActor()}})
                        fea[ridx][sidx].SetMapper(fem[ridx][sidx])

                        ren[ridx].AddActor(fea[ridx][sidx])


                    ren[ridx].AddActor(sa[ridx][sidx])


                if ridx > 1 and ridx == sidx:
                    icp.update({ridx:{sidx:vtk.vtkIterativeClosestPointTransform()}})
                    icp[ridx][sidx].SetSource(s[sidx].GetOutput())
                    icp[ridx][sidx].SetTarget(s[1].GetOutput())
                    icp[ridx][sidx].SetCheckMeanDistance(1)
                    icp[ridx][sidx].SetMaximumMeanDistance(0.001)
                    icp[ridx][sidx].SetMaximumNumberOfIterations(30)
                    icp[ridx][sidx].SetMaximumNumberOfLandmarks(50)
                    sa[ridx][sidx].SetUserTransform(icp[ridx][sidx])


        icp[3][3].StartByMatchingCentroidsOn()

        renWin.SetSize(400, 100)

        # render and interact with data

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

        img_file = "TestICPTransform.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemplo n.º 19
0
def main(argv):
    #  Verify input arguments
    if len(argv) > 1:
        # Read the image
        jpeg_reader = vtkJPEGReader()
        if not jpeg_reader.CanReadFile(argv[1]):
            print("Error reading file %s" % argv[1])
            return

        jpeg_reader.SetFileName(argv[1])
        jpeg_reader.Update()
        image_data = jpeg_reader.GetOutput()
    else:
        canvas_source = vtk.vtkImageCanvasSource2D()
        canvas_source.SetExtent(0, 100, 0, 100, 0, 0)
        canvas_source.SetScalarTypeToUnsignedChar()
        canvas_source.SetNumberOfScalarComponents(3)
        canvas_source.SetDrawColor(127, 127, 100)
        canvas_source.FillBox(0, 100, 0, 100)
        canvas_source.SetDrawColor(100, 255, 255)
        canvas_source.FillTriangle(10, 10, 25, 10, 25, 25)
        canvas_source.SetDrawColor(255, 100, 255)
        canvas_source.FillTube(75, 75, 0, 75, 5.0)
        canvas_source.Update()
        image_data = canvas_source.GetOutput()

    # Create an image actor to display the image
    image_actor = vtkImageActor()

    if VTK_MAJOR_VERSION <= 5:
        image_actor.SetInput(image_data)
    else:
        image_actor.SetInputData(image_data)

    # Create a superquadric
    superquadric_source = vtkSuperquadricSource()
    superquadric_source.SetPhiRoundness(1.1)
    superquadric_source.SetThetaRoundness(.2)

    # Create a mapper and actor
    superquadric_mapper = vtkPolyDataMapper()
    superquadric_mapper.SetInputConnection(superquadric_source.GetOutputPort())

    superquadric_actor = vtkActor()
    superquadric_actor.SetMapper(superquadric_mapper)

    vtk_renderer = vtkRenderer()
    vtk_renderer.SetLayer(1)

    # Set up the render window and renderers such that there is
    # a background layer and a foreground layer
    background_renderer = vtkRenderer()
    background_renderer.SetLayer(0)
    background_renderer.InteractiveOff()
    background_renderer.AddActor(image_actor)

    render_window = vtkRenderWindow()
    render_window.SetNumberOfLayers(2)
    render_window.AddRenderer(background_renderer)
    render_window.AddRenderer(vtk_renderer)

    render_window_interactor = vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # Add actors to the renderers
    vtk_renderer.AddActor(superquadric_actor)

    # Render once to figure out where the background camera will be
    render_window.Render()

    # Set up the background camera to fill the renderer with the image
    origin = image_data.GetOrigin()
    spacing = image_data.GetSpacing()
    extent = image_data.GetExtent()

    camera = background_renderer.GetActiveCamera()
    camera.ParallelProjectionOn()

    xc = origin[0] + 0.5*(extent[0] + extent[1]) * spacing[0]
    yc = origin[1] + 0.5*(extent[2] + extent[3]) * spacing[1]
    # xd = (extent[1] - extent[0] + 1) * spacing[0]
    yd = (extent[3] - extent[2] + 1) * spacing[1]
    d = camera.GetDistance()
    camera.SetParallelScale(0.5 * yd)
    camera.SetFocalPoint(xc, yc, 0.0)
    camera.SetPosition(xc, yc, d)

    # Render again to set the correct view
    render_window.Render()

    # Interact with the window
    render_window_interactor.Start()
Exemplo n.º 20
0
def rerender():
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    img = convert_to_vtk(gray)
    image_actor = vtkImageActor()
    image_actor.SetInputData(img)
    background_renderer = vtkRenderer()
    background_renderer.SetLayer(0)
    render_window.AddRenderer(background_renderer)
    background_renderer.AddActor(image_actor)
    render_window.Render()


cap = cv2.VideoCapture(0)
superquadric_source = vtkSuperquadricSource()
superquadric_source.SetPhiRoundness(1.1)
superquadric_source.SetThetaRoundness(.4)
superquadric_mapper = vtkPolyDataMapper()
superquadric_mapper.SetInputConnection(superquadric_source.GetOutputPort())
superquadric_actor = vtkActor()
superquadric_actor.SetMapper(superquadric_mapper)
scene_renderer = vtkRenderer()
render_window = vtkRenderWindow()

scene_renderer.SetLayer(1)
render_window.SetNumberOfLayers(2)
render_window.AddRenderer(scene_renderer)
render_window_interactor = vtkRenderWindowInteractor()
render_window_interactor.SetRenderWindow(render_window)
scene_renderer.AddActor(superquadric_actor)
Exemplo n.º 21
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        # Create source
        # We are going to handle two different sources.
        # The first source is a superquadric source.
        torus = vtk.vtkSuperquadricSource();
        torus.SetCenter(0.0, 0.0, 0.0)
        torus.SetScale(1.0, 1.0, 1.0)
        torus.SetPhiResolution (64)
        torus.SetThetaResolution(64)
        torus.SetThetaRoundness (1)
        torus.SetThickness (0.5)
        torus.SetSize(0.5)
        torus.SetToroidal(1) 
 
        # Rotate the torus towards the observer (around the x-axis)
        torusT = vtk.vtkTransform()
        torusT.RotateX(55)
 
        torusTF = vtk.vtkTransformFilter()
        torusTF.SetInputConnection(torus.GetOutputPort())
        torusTF.SetTransform(torusT)
 
        # The quadric is made of strips, so pass it through a triangle filter as
        # the curvature filter only operates on polys
        tri = vtk.vtkTriangleFilter()
        tri.SetInputConnection(torusTF.GetOutputPort())
 
        # The quadric has nasty discontinuities from the way the edges are generated
        # so let's pass it though a CleanPolyDataFilter and merge any points which
        # are coincident, or very close
 
        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputConnection(tri.GetOutputPort())
        cleaner.SetTolerance(0.005)
 
        # The next source will be a parametric function
        rh = vtk.vtkParametricRandomHills()
        rhFnSrc = vtk.vtkParametricFunctionSource()
        rhFnSrc.SetParametricFunction(rh)
 
        # Now we have the sources, lets put them into a list.
        sources = list()
        sources.append(cleaner)
        sources.append(cleaner)
        sources.append(rhFnSrc)
        sources.append(rhFnSrc)
 
        # Colour transfer function.
        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
        ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
        cc = list()
        for i in range(256):
            cc.append(ctf.GetColor(float(i) / 255.0)) 
 
        # Lookup table.
        lut = list()
        for idx in range(len(sources)):
            lut.append(vtk.vtkLookupTable())
            lut[idx].SetNumberOfColors(256)
            for i, item in enumerate(cc):
                lut[idx].SetTableValue(i, item[0], item[1], item[2], 1.0)
            if idx == 0:
                lut[idx].SetRange(-10, 10)
            if idx == 1:
                lut[idx].SetRange(0, 4)
            if idx == 2:
                lut[idx].SetRange(-1, 1)
            if idx == 3:
                lut[idx].SetRange(-1, 1)
            lut[idx].Build()
 
        curvatures = list()        
        for idx in range(len(sources)):
            curvatures.append(vtk.vtkCurvatures())
            if idx % 2 == 0:
                curvatures[idx].SetCurvatureTypeToGaussian()
            else:
                curvatures[idx].SetCurvatureTypeToMean()
 
        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()
 
        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()
 
        names = ['Torus - Gaussian Curvature', 'Torus - Mean Curvature', 'Random Hills - Gaussian Curvature', 'Random Hills - Mean Curvature']
 
        # Link the pipeline together. 
        for idx, item in enumerate(sources):
            sources[idx].Update()
 
            curvatures[idx].SetInputConnection(sources[idx].GetOutputPort())
 
            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(curvatures[idx].GetOutputPort())
            mappers[idx].SetLookupTable(lut[idx])
            mappers[idx].SetUseLookupTableScalarRange(1)
 
            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])
 
            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(names[idx])
            textmappers[idx].SetTextProperty(textProperty)
 
            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(150, 16)
 
            renderers.append(vtk.vtkRenderer())
 
        gridDimensions = 2
 
        for idx in range(len(sources)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)
 
        rendererSize = 300
 
        # Create the RenderWindow
        self.vtkWidget.GetRenderWindow().SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)
 
        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col
 
                viewport[:] = []
                viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize))
 
                if idx > (len(sources) - 1):
                    continue
 
                renderers[idx].SetViewport(viewport)
                self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx])
 
                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4,0.3,0.2)
        
        self._initialized = False
def main():
    colors = vtk.vtkNamedColors()

    file_name = get_program_parameters()

    # Read the polydata for the icon
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(file_name)

    icon_mapper = vtk.vtkDataSetMapper()
    icon_mapper.SetInputConnection(reader.GetOutputPort())

    icon_actor = vtk.vtkActor()
    icon_actor.SetMapper(icon_mapper)
    icon_actor.GetProperty().SetColor(colors.GetColor3d('Silver'))

    # Set up the renderer, window, and interactor
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(renderer)
    ren_win.SetSize(400, 400)
    ren_win.SetWindowName('OrientationMarkerWidget1')

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

    rgb = [0.0, 0.0, 0.0]
    colors.GetColorRGB('Wheat', rgb)
    # Set up the widget
    widget = vtk.vtkOrientationMarkerWidget()
    widget.SetOrientationMarker(icon_actor)
    widget.SetInteractor(iren)
    widget.SetViewport(0.0, 0.0, 0.2, 0.2)
    widget.SetOutlineColor(*rgb)
    widget.SetEnabled(1)
    widget.InteractiveOn()

    # Create a superquadric
    superquadric_source = vtk.vtkSuperquadricSource()
    superquadric_source.SetPhiRoundness(.2)
    superquadric_source.SetThetaRoundness(.8)

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

    superquadric_actor = vtk.vtkActor()
    superquadric_actor.SetMapper(superquadric_mapper)
    superquadric_actor.GetProperty().SetInterpolationToFlat()
    superquadric_actor.GetProperty().SetDiffuseColor(
        colors.GetColor3d('Carrot'))
    superquadric_actor.GetProperty().SetSpecularColor(
        colors.GetColor3d('White'))
    superquadric_actor.GetProperty().SetDiffuse(0.6)
    superquadric_actor.GetProperty().SetSpecular(0.5)
    superquadric_actor.GetProperty().SetSpecularPower(5.0)

    renderer.AddActor(superquadric_actor)
    renderer.ResetCamera()

    ren_win.Render()

    iren.Initialize()

    iren.Start()
Exemplo n.º 23
0
def main():
    colors = vtk.vtkNamedColors()

    #  Verify input arguments
    fn = get_program_parameters()
    if fn:
        # Read the image
        jpeg_reader = vtk.vtkJPEGReader()
        if not jpeg_reader.CanReadFile(fn):
            print('Error reading file:', fn)
            return

        jpeg_reader.SetFileName(fn)
        jpeg_reader.Update()
        image_data = jpeg_reader.GetOutput()
    else:
        canvas_source = vtk.vtkImageCanvasSource2D()
        canvas_source.SetExtent(0, 100, 0, 100, 0, 0)
        canvas_source.SetScalarTypeToUnsignedChar()
        canvas_source.SetNumberOfScalarComponents(3)
        canvas_source.SetDrawColor(colors.GetColor4ub('warm_grey'))
        canvas_source.FillBox(0, 100, 0, 100)
        canvas_source.SetDrawColor(colors.GetColor4ub('DarkCyan'))
        canvas_source.FillTriangle(10, 10, 25, 10, 25, 25)
        canvas_source.SetDrawColor(colors.GetColor4ub('LightCoral'))
        canvas_source.FillTube(75, 75, 0, 75, 5.0)
        canvas_source.Update()
        image_data = canvas_source.GetOutput()

    # Create an image actor to display the image
    image_actor = vtk.vtkImageActor()
    image_actor.SetInputData(image_data)

    # Create a renderer to display the image in the background
    background_renderer = vtk.vtkRenderer()

    # Create a superquadric
    superquadric_source = vtk.vtkSuperquadricSource()
    superquadric_source.SetPhiRoundness(1.1)
    superquadric_source.SetThetaRoundness(.2)

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

    superquadric_actor = vtk.vtkActor()
    superquadric_actor.SetMapper(superquadric_mapper)
    superquadric_actor.GetProperty().SetColor(colors.GetColor3d('NavajoWhite'))

    scene_renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()

    # Set up the render window and renderers such that there is
    # a background layer and a foreground layer
    background_renderer.SetLayer(0)
    background_renderer.InteractiveOff()
    scene_renderer.SetLayer(1)
    render_window.SetNumberOfLayers(2)
    render_window.AddRenderer(background_renderer)
    render_window.AddRenderer(scene_renderer)
    render_window.SetWindowName('BackgroundImage')

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # Add actors to the renderers
    scene_renderer.AddActor(superquadric_actor)
    background_renderer.AddActor(image_actor)

    # Render once to figure out where the background camera will be
    render_window.Render()

    # Set up the background camera to fill the renderer with the image
    origin = image_data.GetOrigin()
    spacing = image_data.GetSpacing()
    extent = image_data.GetExtent()

    camera = background_renderer.GetActiveCamera()
    camera.ParallelProjectionOn()

    xc = origin[0] + 0.5 * (extent[0] + extent[1]) * spacing[0]
    yc = origin[1] + 0.5 * (extent[2] + extent[3]) * spacing[1]
    # xd = (extent[1] - extent[0] + 1) * spacing[0]
    yd = (extent[3] - extent[2] + 1) * spacing[1]
    d = camera.GetDistance()
    camera.SetParallelScale(0.5 * yd)
    camera.SetFocalPoint(xc, yc, 0.0)
    camera.SetPosition(xc, yc, d)

    # Render again to set the correct view
    render_window.Render()

    # Interact with the window
    render_window_interactor.Start()
Exemplo n.º 24
0
def main():
    colors = vtk.vtkNamedColors()

    backgroundColor = colors.GetColor3d("DarkSlateGray")
    actorColor = colors.GetColor3d("Tomato")
    axis1Color = colors.GetColor3d("Salmon")
    axis2Color = colors.GetColor3d("PaleGreen")
    axis3Color = colors.GetColor3d("LightSkyBlue")

    # Create a superquadric
    superquadricSource = vtk.vtkSuperquadricSource()
    superquadricSource.SetPhiRoundness(3.1)
    superquadricSource.SetThetaRoundness(1.0)
    superquadricSource.Update()  # needed to GetBounds later

    renderer = vtk.vtkRenderer()

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

    superquadricActor = vtk.vtkActor()
    superquadricActor.SetMapper(mapper)
    superquadricActor.GetProperty().SetDiffuseColor(actorColor)
    superquadricActor.GetProperty().SetDiffuse(.7)
    superquadricActor.GetProperty().SetSpecular(.7)
    superquadricActor.GetProperty().SetSpecularPower(50.0)

    cubeAxesActor = vtk.vtkCubeAxesActor()
    cubeAxesActor.SetUseTextActor3D(1)
    cubeAxesActor.SetBounds(superquadricSource.GetOutput().GetBounds())
    cubeAxesActor.SetCamera(renderer.GetActiveCamera())
    cubeAxesActor.GetTitleTextProperty(0).SetColor(axis1Color)
    cubeAxesActor.GetTitleTextProperty(0).SetFontSize(48)
    cubeAxesActor.GetLabelTextProperty(0).SetColor(axis1Color)

    cubeAxesActor.GetTitleTextProperty(1).SetColor(axis2Color)
    cubeAxesActor.GetLabelTextProperty(1).SetColor(axis2Color)

    cubeAxesActor.GetTitleTextProperty(2).SetColor(axis3Color)
    cubeAxesActor.GetLabelTextProperty(2).SetColor(axis3Color)

    cubeAxesActor.DrawXGridlinesOn()
    cubeAxesActor.DrawYGridlinesOn()
    cubeAxesActor.DrawZGridlinesOn()
    cubeAxesActor.SetGridLineLocation(cubeAxesActor.VTK_GRID_LINES_FURTHEST)

    cubeAxesActor.XAxisMinorTickVisibilityOff()
    cubeAxesActor.YAxisMinorTickVisibilityOff()
    cubeAxesActor.ZAxisMinorTickVisibilityOff()

    cubeAxesActor.SetFlyModeToStaticEdges()
    renderer.AddActor(cubeAxesActor)
    renderer.AddActor(superquadricActor)
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)

    renderer.ResetCamera()
    renderer.SetBackground(backgroundColor)

    renderWindow = vtk.vtkRenderWindow()

    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(640, 480)
    renderWindow.SetWindowName('CubeAxesActor')

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

    renderWindow.Render()
    renderer.GetActiveCamera().Zoom(0.8)
    renderWindowInteractor.Start()
Exemplo n.º 25
0
    def testICPTransform(self):

        renWin = vtk.vtkRenderWindow()

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

        # Create objects

        sscale = {2: [0.7, 0.7, 0.7], 3: [0.5, 0.5, 0.5]}
        scenter = {2: [-0.25, 0.25, 0.0], 3: [0.4, -0.3, 0.0]}
        scolors = {2: [0.2, 0.6, 0.1], 3: [0.1, 0.2, 0.6]}

        s = dict()  # The super quadric sources

        for sidx in range(1, 4):
            s.update({sidx: vtk.vtkSuperquadricSource()})
            s[sidx].ToroidalOff()
            s[sidx].SetThetaResolution(20)
            s[sidx].SetPhiResolution(20)
            s[sidx].SetPhiRoundness(0.7 + (sidx - 2) * 0.4)
            s[sidx].SetThetaRoundness(0.85 + (sidx - 1) * 0.4)
            if sidx in sscale:
                s[sidx].SetScale(sscale[sidx])
            if sidx in scenter:
                s[sidx].SetCenter(scenter[sidx])

            s[sidx].Update()

        ren = dict()  # Renderers
        sm = dict()  # Mappers for the super quadric source
        sa = dict()  # Actors for the super quadric source
        fe = dict()  # Feature edges
        fem = dict()  # Feature edges mappers
        fea = dict()  # Feature edges actors
        icp = dict()  # Iterated closest point transforms

        # Create the renderers

        for ridx in range(1, 4):
            ren.update({ridx: vtk.vtkRenderer()})
            ren[ridx].SetViewport((ridx - 1) / 3.0, 0.0, ridx / 3.0, 1.0)
            ren[ridx].SetBackground(0.7, 0.8, 1.0)
            cam = ren[ridx].GetActiveCamera()
            cam.SetPosition(1.7, 1.4, 1.7)
            renWin.AddRenderer(ren[ridx])

            # renderer 1 has all 3 objects, render i has object 1 and i (i=2, 3)
            # add actors (corresponding to the objects) to each renderer
            # and ICP transforms from objects i or to 1.
            # object 1 has feature edges too.

            for sidx in range(1, 4):

                if ridx == 1 or sidx == 1 or ridx == sidx:
                    sm.update({ridx: {sidx: vtk.vtkPolyDataMapper()}})
                    sm[ridx][sidx].SetInputConnection(s[sidx].GetOutputPort())

                    sa.update({ridx: {sidx: vtk.vtkActor()}})
                    sa[ridx][sidx].SetMapper(sm[ridx][sidx])

                    prop = sa[ridx][sidx].GetProperty()
                    if sidx in scolors:
                        prop.SetColor(scolors[sidx])

                    if sidx == 1:
                        prop.SetOpacity(0.2)

                        fe.update({ridx: {sidx: vtk.vtkFeatureEdges()}})
                        src = s[sidx]
                        fe[ridx][sidx].SetInputConnection(src.GetOutputPort())
                        fe[ridx][sidx].BoundaryEdgesOn()
                        fe[ridx][sidx].ColoringOff()
                        fe[ridx][sidx].ManifoldEdgesOff()

                        fem.update({ridx: {sidx: vtk.vtkPolyDataMapper()}})
                        fem[ridx][sidx].SetInputConnection(
                            fe[ridx][sidx].GetOutputPort())
                        fem[ridx][
                            sidx].SetResolveCoincidentTopologyToPolygonOffset(
                            )

                        fea.update({ridx: {sidx: vtk.vtkActor()}})
                        fea[ridx][sidx].SetMapper(fem[ridx][sidx])

                        ren[ridx].AddActor(fea[ridx][sidx])

                    ren[ridx].AddActor(sa[ridx][sidx])

                if ridx > 1 and ridx == sidx:
                    icp.update({
                        ridx: {
                            sidx: vtk.vtkIterativeClosestPointTransform()
                        }
                    })
                    icp[ridx][sidx].SetSource(s[sidx].GetOutput())
                    icp[ridx][sidx].SetTarget(s[1].GetOutput())
                    icp[ridx][sidx].SetCheckMeanDistance(1)
                    icp[ridx][sidx].SetMaximumMeanDistance(0.001)
                    icp[ridx][sidx].SetMaximumNumberOfIterations(30)
                    icp[ridx][sidx].SetMaximumNumberOfLandmarks(50)
                    sa[ridx][sidx].SetUserTransform(icp[ridx][sidx])

        icp[3][3].StartByMatchingCentroidsOn()

        renWin.SetSize(400, 100)

        # render and interact with data

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

        img_file = "TestICPTransform.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
Exemplo n.º 26
0
def main():
    # Create a superquadric
    superquadric_source = vtk.vtkSuperquadricSource()
    superquadric_source.SetPhiRoundness(3.1)
    superquadric_source.SetThetaRoundness(2.2)

    # Define a clipping plane
    clip_plane = vtk.vtkPlane()
    clip_plane.SetNormal(1.0, -1.0, -1.0)
    clip_plane.SetOrigin(0.0, 0.0, 0.0)

    # Clip the source with the plane
    clipper = vtk.vtkClipPolyData()
    clipper.SetInputConnection(superquadric_source.GetOutputPort())
    clipper.SetClipFunction(clip_plane)
    # This will give us the polygonal data that is clipped away
    clipper.GenerateClippedOutputOn()

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

    superquadric_actor = vtk.vtkActor()
    superquadric_actor.SetMapper(superquadric_mapper)

    colors = vtk.vtkNamedColors()

    # Create a property to be used for the back faces. Turn off all
    # shading by specifying 0 weights for specular and diffuse. Max the
    # ambient.
    back_faces = vtk.vtkProperty()
    back_faces.SetSpecular(0.0)
    back_faces.SetDiffuse(0.0)
    back_faces.SetAmbient(1.0)
    back_faces.SetAmbientColor(colors.GetColor3d('Tomato'))

    superquadric_actor.SetBackfaceProperty(back_faces)

    # Here we get the the polygonal data that is clipped away
    clipped_away_mapper = vtk.vtkPolyDataMapper()
    clipped_away_mapper.SetInputData(clipper.GetClippedOutput())
    clipped_away_mapper.ScalarVisibilityOff()

    # Let us display it as a faint object
    clipped_away_actor = vtk.vtkActor()
    clipped_away_actor.SetMapper(clipped_away_mapper)
    clipped_away_actor.GetProperty().SetDiffuseColor(
        colors.GetColor3d("Silver"))
    clipped_away_actor.GetProperty().SetOpacity(0.1)

    # Create a renderer
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    render_window = vtk.vtkRenderWindow()

    render_window.AddRenderer(renderer)

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # Add the actor to the renderer
    renderer.AddActor(superquadric_actor)
    renderer.AddActor(clipped_away_actor)
    render_window.SetSize(600, 600)
    renderer.ResetCamera()
    renderer.GetActiveCamera().Dolly(1.5)
    renderer.ResetCameraClippingRange()
    render_window.Render()
    render_window.SetWindowName('SolidClip')

    # Interact with the window
    render_window_interactor.Start()
Exemplo n.º 27
0
import vtk

reader = vtk.vtkSTLReader()
reader.SetFileName("skull.stl")

sphere = vtk.vtkSuperquadricSource()
sphere.ToroidalOn()
sphere.SetThetaResolution(50)
sphere.SetPhiResolution(50)

mapper = vtk.vtkOpenGLPolyDataMapper()
mapper.SetInputConnection(sphere.GetOutputPort())

mapper.SetVertexShaderCode("""
    #version 330

    uniform mat4 modelViewMatrix;
    uniform mat4 modelMatrix;
    uniform mat4 viewMatrix;
    uniform mat4 projectionMatrix;
    uniform mat4 textureMatrix;
    uniform mat4 modelViewProjectionMatrix;
    uniform mat4 normalMatrix;

    in vec4 position;
    in vec4 color;
    in vec4 normal;
    in vec2 texcoord;
    
    in vec3 n;
    in vec3 l;
#!/usr/bin/env python

import vtk

# Create a superquadric
superquadricSource = vtk.vtkSuperquadricSource()
superquadricSource.SetPhiRoundness(3.1)
superquadricSource.SetThetaRoundness(1.0)
superquadricSource.Update()  # needed to GetBounds later

renderer = vtk.vtkRenderer()

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

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

cubeAxesActor = vtk.vtkCubeAxesActor()
cubeAxesActor.SetBounds(superquadricSource.GetOutput().GetBounds())
cubeAxesActor.SetCamera(renderer.GetActiveCamera())
cubeAxesActor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0)
cubeAxesActor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0)

cubeAxesActor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0)
cubeAxesActor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0)

cubeAxesActor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0)
cubeAxesActor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0)

cubeAxesActor.DrawXGridlinesOn()
Exemplo n.º 29
0
def main(argv):
    colors = vtk.vtkNamedColors()
    imageData = None

    # Verify input arguments
    if len(argv) > 1:
        # Read the image
        readerFactory = vtk.vtkImageReader2Factory()
        imageReader = readerFactory.CreateImageReader2(argv[1])
        imageReader.SetFileName(argv[1])
        imageReader.Update()
        imageData = imageReader.GetOutput()
    else:
        drawColor1 = 4 * [255]
        drawColor2 = 4 * [255]
        drawColor3 = 4 * [255]
        color1 = colors.GetColor3ub("warm_grey")
        color2 = colors.GetColor3ub("DarkCyan")
        color3 = colors.GetColor3ub("LightCoral")
        for i in range(3):
            drawColor1[i] = color1[i]
            drawColor2[i] = color2[i]
            drawColor3[i] = color3[i]

        canvasSource = vtk.vtkImageCanvasSource2D()
        canvasSource.SetExtent(0, 100, 0, 100, 0, 0)
        canvasSource.SetScalarTypeToUnsignedChar()
        canvasSource.SetNumberOfScalarComponents(3)
        canvasSource.SetDrawColor(drawColor1)
        canvasSource.FillBox(0, 100, 0, 100)
        canvasSource.SetDrawColor(drawColor2)
        canvasSource.FillTriangle(10, 10, 25, 10, 25, 25)
        canvasSource.SetDrawColor(drawColor3)
        canvasSource.FillTube(75, 75, 0, 75, 5.0)
        canvasSource.Update()
        imageData = canvasSource.GetOutput()

    # Create an image actor to display the image
    imageActor = vtk.vtkImageActor()
    imageActor.SetInputData(imageData)

    # Create a renderer to display the image in the background
    backgroundRenderer = vtk.vtkRenderer()

    # Create a superquadric
    superquadricSource = vtk.vtkSuperquadricSource()
    superquadricSource.SetPhiRoundness(1.1)
    superquadricSource.SetThetaRoundness(.2)

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

    superquadricActor = vtk.vtkActor()
    superquadricActor.SetMapper(superquadricMapper)
    superquadricActor.GetProperty().SetColor(colors.GetColor3d("NavajoWhite"))

    sceneRenderer = vtk.vtkRenderer()

    renderWindow = vtk.vtkRenderWindow()

    # Set up the render window and renderers such that there is
    # a background layer and a foreground layer
    backgroundRenderer.SetLayer(0)
    backgroundRenderer.InteractiveOff()
    sceneRenderer.SetLayer(1)
    renderWindow.SetNumberOfLayers(2)
    renderWindow.AddRenderer(backgroundRenderer)
    renderWindow.AddRenderer(sceneRenderer)
    renderWindow.SetWindowName("BackgroundImage")

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

    # Add actors to the renderers
    sceneRenderer.AddActor(superquadricActor)
    backgroundRenderer.AddActor(imageActor)

    # Render once to figure out where the background camera will be
    renderWindow.Render()

    # Set up the background camera to fill the renderer with the image
    origin = imageData.GetOrigin()
    spacing = imageData.GetSpacing()
    extent = imageData.GetExtent()

    camera = backgroundRenderer.GetActiveCamera()
    camera.ParallelProjectionOn()

    xc = origin[0] + 0.5 * (extent[0] + extent[1]) * spacing[0]
    yc = origin[1] + 0.5 * (extent[2] + extent[3]) * spacing[1]
    yd = (extent[3] - extent[2] + 1) * spacing[1]
    d = camera.GetDistance()
    camera.SetParallelScale(0.5 * yd)
    camera.SetFocalPoint(xc, yc, 0.0)
    camera.SetPosition(xc, yc, d)

    # Render again to set the correct view
    renderWindow.Render()

    # Interact with the window
    renderWindowInteractor.Start()
Exemplo n.º 30
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create renderer stuff
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Pipeline stuff
#
torus = vtk.vtkSuperquadricSource()
torus.SetCenter(0.0, 0.0, 0.0)
torus.SetScale(1.0, 1.0, 1.0)
torus.SetPhiResolution(64)
torus.SetThetaResolution(64)
torus.SetPhiRoundness(1.0)
torus.SetThetaRoundness(1.0)
torus.SetThickness(0.5)
torus.SetSize(0.5)
torus.SetToroidal(1)
# The quadric is made of strips, so pass it through a triangle filter as
# the curvature filter only operates on polys
tri = vtk.vtkTriangleFilter()
tri.SetInputConnection(torus.GetOutputPort())
# The quadric has nasty discontinuities from the way the edges are generated
# so let's pass it though a CleanPolyDataFilter and merge any points which
Exemplo n.º 31
0
def main(argv):
    #  Verify input arguments
    if len(argv) > 1:
        # Read the image
        jpeg_reader = vtkJPEGReader()
        if not jpeg_reader.CanReadFile(argv[1]):
            print("Error reading file %s" % argv[1])
            return

        jpeg_reader.SetFileName(argv[1])
        jpeg_reader.Update()
        image_data = jpeg_reader.GetOutput()
    else:
        canvas_source = vtk.vtkImageCanvasSource2D()
        canvas_source.SetExtent(0, 100, 0, 100, 0, 0)
        canvas_source.SetScalarTypeToUnsignedChar()
        canvas_source.SetNumberOfScalarComponents(3)
        canvas_source.SetDrawColor(127, 127, 100)
        canvas_source.FillBox(0, 100, 0, 100)
        canvas_source.SetDrawColor(100, 255, 255)
        canvas_source.FillTriangle(10, 10, 25, 10, 25, 25)
        canvas_source.SetDrawColor(255, 100, 255)
        canvas_source.FillTube(75, 75, 0, 75, 5.0)
        canvas_source.Update()
        image_data = canvas_source.GetOutput()

    # Create an image actor to display the image
    image_actor = vtkImageActor()

    if VTK_MAJOR_VERSION <= 5:
        image_actor.SetInput(image_data)
    else:
        image_actor.SetInputData(image_data)

    # Create a superquadric
    superquadric_source = vtkSuperquadricSource()
    superquadric_source.SetPhiRoundness(1.1)
    superquadric_source.SetThetaRoundness(.2)

    # Create a mapper and actor
    superquadric_mapper = vtkPolyDataMapper()
    superquadric_mapper.SetInputConnection(superquadric_source.GetOutputPort())

    superquadric_actor = vtkActor()
    superquadric_actor.SetMapper(superquadric_mapper)

    vtk_renderer = vtkRenderer()
    vtk_renderer.SetLayer(1)

    # Set up the render window and renderers such that there is
    # a background layer and a foreground layer
    background_renderer = vtkRenderer()
    background_renderer.SetLayer(0)
    background_renderer.InteractiveOff()
    background_renderer.AddActor(image_actor)

    render_window = vtkRenderWindow()
    render_window.SetNumberOfLayers(2)
    render_window.AddRenderer(background_renderer)
    render_window.AddRenderer(vtk_renderer)

    render_window_interactor = vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # Add actors to the renderers
    vtk_renderer.AddActor(superquadric_actor)

    # Render once to figure out where the background camera will be
    render_window.Render()

    # Set up the background camera to fill the renderer with the image
    origin = image_data.GetOrigin()
    spacing = image_data.GetSpacing()
    extent = image_data.GetExtent()

    camera = background_renderer.GetActiveCamera()
    camera.ParallelProjectionOn()

    xc = origin[0] + 0.5 * (extent[0] + extent[1]) * spacing[0]
    yc = origin[1] + 0.5 * (extent[2] + extent[3]) * spacing[1]
    # xd = (extent[1] - extent[0] + 1) * spacing[0]
    yd = (extent[3] - extent[2] + 1) * spacing[1]
    d = camera.GetDistance()
    camera.SetParallelScale(0.5 * yd)
    camera.SetFocalPoint(xc, yc, 0.0)
    camera.SetPosition(xc, yc, d)

    # Render again to set the correct view
    render_window.Render()

    # Interact with the window
    render_window_interactor.Start()
    def SetUp(self):
        '''
        Set up squadViewer
        '''
        def OnClosing():
            self.root.quit()

        def SetPhi(squad, win, phi):
            squad.SetPhiRoundness(float(phi))
            win.Render()

        def SetTheta(squad, win, theta):
            squad.SetThetaRoundness(float(theta))
            win.Render()

        def SetThickness(squad, win, thickness):
            squad.SetThickness(float(thickness))
            win.Render()

        def SetTexture(actor, texture, win):
            if doTexture.get():
                actor.SetTexture(texture)
            else:
                actor.SetTexture(None)
            win.Render()

        def SetToroid(squad, scale, win):
            squad.SetToroidal(toroid.get())
            if toroid.get():
                scale.config(state=NORMAL, fg='black')
            else:
                scale.config(state=DISABLED, fg='gray')
            win.Render()

        self.root = tkinter.Tk()
        self.root.title("superquadric viewer")
        # Define what to do when the user explicitly closes a window.
        self.root.protocol("WM_DELETE_WINDOW", OnClosing)

        # Create render window
        self.tkrw = vtkTkRenderWidget(self.root, width=550, height=450)
        self.tkrw.BindTkRenderWidget()
        renWin = self.tkrw.GetRenderWindow()

        # Create parameter sliders
        #
        prs = tkinter.Scale(self.root, from_=0, to=3.5, res=0.1,
                             orient=HORIZONTAL, label="phi roundness")
        trs = tkinter.Scale(self.root, from_=0, to=3.5, res=0.1,
                             orient=HORIZONTAL, label="theta roundness")
        thicks = tkinter.Scale(self.root, from_=0.01, to=1.0, res=0.01,
                             orient=HORIZONTAL, label="thickness")

        # Create check buttons
        #
        toroid = tkinter.IntVar()
        toroid.set(0)
        doTexture = tkinter.IntVar()
        doTexture.set(0)

        rframe = tkinter.Frame(self.root)
        torbut = tkinter.Checkbutton(rframe, text="Toroid", variable=toroid)
        texbut = tkinter.Checkbutton(rframe, text="Texture", variable=doTexture)

        # Put it all together
        #
        torbut.pack(padx=10, pady=5, ipadx=20, ipady=5, side=RIGHT, anchor=S)
        texbut.pack(padx=10, pady=5, ipadx=20, ipady=5, side=RIGHT, anchor=S)

        self.tkrw.grid(sticky=N+E+W+S, columnspan=2)
        rframe.grid(sticky=N+E+W+S)
        thicks.grid(sticky=N+S+E+W, padx=10, ipady=5, row=1, column=1)
        prs.grid(sticky=N+E+W+S, padx=10, ipady=5, row = 2, column = 0)
        trs.grid(sticky=N+E+W+S, padx=10, ipady=5, row = 2, column = 1)
        tkinter.Pack.propagate(rframe,NO)

        prs.set(1.0)
        trs.set(0.7)
        thicks.set(0.3)
        toroid.set(1)
        doTexture.set(0)

        # Create pipeline
        #
        squad = vtk.vtkSuperquadricSource()
        squad.SetPhiResolution(20)
        squad.SetThetaResolution(25)

        pnmReader = vtk.vtkPNMReader()
        pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/earth.ppm")
        atext = vtk.vtkTexture()
        atext.SetInputConnection(pnmReader.GetOutputPort())
        atext.InterpolateOn()

        appendSquads = vtk.vtkAppendPolyData()
        appendSquads.AddInputConnection(squad.GetOutputPort())

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(squad.GetOutputPort())
        mapper.ScalarVisibilityOff()
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.SetTexture(atext)
        actor.GetProperty().SetDiffuseColor(0.5, 0.8, 0.8)
        actor.GetProperty().SetAmbient(0.2)
        actor.GetProperty().SetAmbientColor(0.2, 0.2, 0.2)

        squad.SetPhiRoundness(prs.get())
        squad.SetThetaRoundness(trs.get())
        squad.SetToroidal(toroid.get())
        squad.SetThickness(thicks.get())
        squad.SetScale(1, 1, 1)
        SetTexture(actor, atext, renWin)

        # Create renderer stuff
        #
        ren = vtk.vtkRenderer()
        ren.SetAmbient(1.0, 1.0, 1.0)
        renWin.AddRenderer(ren)


        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(actor)
        ren.SetBackground(0.25, 0.2, 0.2)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.2)
        ren.GetActiveCamera().Elevation(40)
        ren.GetActiveCamera().Azimuth(-20)

        # Associate the functions with the sliders and check buttons.
        #
        prs.config(command=partial(SetPhi, squad, self.tkrw))
        trs.config(command=partial(SetTheta, squad, self.tkrw))
        thicks.config(command=partial(SetThickness,squad, self.tkrw))
        torbut.config(command=partial(SetToroid, squad, thicks, self.tkrw))
        texbut.config(command=partial(SetTexture, actor, atext, self.tkrw))
Exemplo n.º 33
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create renderer stuff
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Pipeline stuff
#
torus = vtk.vtkSuperquadricSource()
torus.SetCenter(0.0,0.0,0.0)
torus.SetScale(1.0,1.0,1.0)
torus.SetPhiResolution(64)
torus.SetThetaResolution(64)
torus.SetPhiRoundness(1.0)
torus.SetThetaRoundness(1.0)
torus.SetThickness(0.5)
torus.SetSize(0.5)
torus.SetToroidal(1)
# The quadric is made of strips, so pass it through a triangle filter as
# the curvature filter only operates on polys
tri = vtk.vtkTriangleFilter()
tri.SetInputConnection(torus.GetOutputPort())
# The quadric has nasty discontinuities from the way the edges are generated
# so let's pass it though a CleanPolyDataFilter and merge any points which
Exemplo n.º 34
0
    def CurvaturesDemo(self):

        # We are going to handle two different sources.
        # The first source is a superquadric source.
        torus = vtk.vtkSuperquadricSource()
        torus.SetCenter(0.0, 0.0, 0.0)
        torus.SetScale(1.0, 1.0, 1.0)
        torus.SetPhiResolution(64)
        torus.SetThetaResolution(64)
        torus.SetThetaRoundness(1)
        torus.SetThickness(0.5)
        torus.SetSize(0.5)
        torus.SetToroidal(1)

        # Rotate the torus towards the observer (around the x-axis)
        torusT = vtk.vtkTransform()
        torusT.RotateX(55)

        torusTF = vtk.vtkTransformFilter()
        torusTF.SetInputConnection(torus.GetOutputPort())
        torusTF.SetTransform(torusT)

        # The quadric is made of strips, so pass it through a triangle filter as
        # the curvature filter only operates on polys
        tri = vtk.vtkTriangleFilter()
        tri.SetInputConnection(torusTF.GetOutputPort())

        # The quadric has nasty discontinuities from the way the edges are generated
        # so let's pass it though a CleanPolyDataFilter and merge any points which
        # are coincident, or very close

        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputConnection(tri.GetOutputPort())
        cleaner.SetTolerance(0.005)

        # The next source will be a parametric function
        rh = vtk.vtkParametricRandomHills()
        rhFnSrc = vtk.vtkParametricFunctionSource()
        rhFnSrc.SetParametricFunction(rh)

        # Now we have the sources, lets put them into a list.
        sources = list()
        sources.append(cleaner)
        sources.append(cleaner)
        sources.append(rhFnSrc)
        sources.append(rhFnSrc)

        # Colour transfer function.
        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
        ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
        cc = list()
        for i in range(256):
            cc.append(ctf.GetColor(float(i) / 255.0))

        # Lookup table.
        lut = list()
        for idx in range(len(sources)):
            lut.append(vtk.vtkLookupTable())
            lut[idx].SetNumberOfColors(256)
            for i, item in enumerate(cc):
                lut[idx].SetTableValue(i, item[0], item[1], item[2], 1.0)
            if idx == 0:
                lut[idx].SetRange(-10, 10)
            if idx == 1:
                lut[idx].SetRange(0, 4)
            if idx == 2:
                lut[idx].SetRange(-1, 1)
            if idx == 3:
                lut[idx].SetRange(-1, 1)
            lut[idx].Build()

        curvatures = list()
        for idx in range(len(sources)):
            curvatures.append(vtk.vtkCurvatures())
            if idx % 2 == 0:
                curvatures[idx].SetCurvatureTypeToGaussian()
            else:
                curvatures[idx].SetCurvatureTypeToMean()

        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()

        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()

        names = [
            'Torus - Gaussian Curvature', 'Torus - Mean Curvature',
            'Random Hills - Gaussian Curvature',
            'Random Hills - Mean Curvature'
        ]

        # Link the pipeline together.
        for idx, item in enumerate(sources):
            sources[idx].Update()

            curvatures[idx].SetInputConnection(sources[idx].GetOutputPort())

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(curvatures[idx].GetOutputPort())
            mappers[idx].SetLookupTable(lut[idx])
            mappers[idx].SetUseLookupTableScalarRange(1)

            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])

            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(names[idx])
            textmappers[idx].SetTextProperty(textProperty)

            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(150, 16)

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 2

        for idx in range(len(sources)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)

        rendererSize = 300

        # Create the RenderWindow
        #
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.SetSize(rendererSize * gridDimensions,
                             rendererSize * gridDimensions)

        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col

                viewport[:] = []
                viewport.append(
                    float(col) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - (row + 1)) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(col + 1) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - row) * rendererSize /
                    (gridDimensions * rendererSize))

                if idx > (len(sources) - 1):
                    continue

                renderers[idx].SetViewport(viewport)
                renderWindow.AddRenderer(renderers[idx])

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4, 0.3, 0.2)

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

        renderWindow.Render()

        interactor.Start()
Exemplo n.º 35
0
    def SetUp(self):
        '''
        Set up squadViewer
        '''
        def OnClosing():
            self.root.quit()

        def SetPhi(squad, win, phi):
            squad.SetPhiRoundness(float(phi))
            win.Render()

        def SetTheta(squad, win, theta):
            squad.SetThetaRoundness(float(theta))
            win.Render()

        def SetThickness(squad, win, thickness):
            squad.SetThickness(float(thickness))
            win.Render()

        def SetTexture(actor, texture, win):
            if doTexture.get():
                actor.SetTexture(texture)
            else:
                actor.SetTexture(None)
            win.Render()

        def SetToroid(squad, scale, win):
            squad.SetToroidal(toroid.get())
            if toroid.get():
                scale.config(state=NORMAL, fg='black')
            else:
                scale.config(state=DISABLED, fg='gray')
            win.Render()

        self.root = Tkinter.Tk()
        self.root.title("superquadric viewer")
        # Define what to do when the user explicitly closes a window.
        self.root.protocol("WM_DELETE_WINDOW", OnClosing)

        # Create render window
        self.tkrw = vtkTkRenderWidget(self.root, width=550, height=450)
        self.tkrw.BindTkRenderWidget()
        self.renWin = self.tkrw.GetRenderWindow()

        # Create parameter sliders
        #
        prs = Tkinter.Scale(self.root,
                            from_=0,
                            to=3.5,
                            res=0.1,
                            orient=HORIZONTAL,
                            label="phi roundness")
        trs = Tkinter.Scale(self.root,
                            from_=0,
                            to=3.5,
                            res=0.1,
                            orient=HORIZONTAL,
                            label="theta roundness")
        thicks = Tkinter.Scale(self.root,
                               from_=0.01,
                               to=1.0,
                               res=0.01,
                               orient=HORIZONTAL,
                               label="thickness")

        # Create check buttons
        #
        toroid = Tkinter.IntVar()
        toroid.set(0)
        doTexture = Tkinter.IntVar()
        doTexture.set(0)

        rframe = Tkinter.Frame(self.root)
        torbut = Tkinter.Checkbutton(rframe, text="Toroid", variable=toroid)
        texbut = Tkinter.Checkbutton(rframe,
                                     text="Texture",
                                     variable=doTexture)

        # Put it all together
        #
        torbut.pack(padx=10, pady=5, ipadx=20, ipady=5, side=RIGHT, anchor=S)
        texbut.pack(padx=10, pady=5, ipadx=20, ipady=5, side=RIGHT, anchor=S)

        self.tkrw.grid(sticky=N + E + W + S, columnspan=2)
        rframe.grid(sticky=N + E + W + S)
        thicks.grid(sticky=N + S + E + W, padx=10, ipady=5, row=1, column=1)
        prs.grid(sticky=N + E + W + S, padx=10, ipady=5, row=2, column=0)
        trs.grid(sticky=N + E + W + S, padx=10, ipady=5, row=2, column=1)
        Tkinter.Pack.propagate(rframe, NO)

        prs.set(1.0)
        trs.set(0.7)
        thicks.set(0.3)
        toroid.set(1)
        doTexture.set(0)

        # Create pipeline
        #
        squad = vtk.vtkSuperquadricSource()
        squad.SetPhiResolution(20)
        squad.SetThetaResolution(25)

        pnmReader = vtk.vtkPNMReader()
        pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/earth.ppm")
        atext = vtk.vtkTexture()
        atext.SetInputConnection(pnmReader.GetOutputPort())
        atext.InterpolateOn()

        appendSquads = vtk.vtkAppendPolyData()
        appendSquads.AddInputConnection(squad.GetOutputPort())

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(squad.GetOutputPort())
        mapper.ScalarVisibilityOff()
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.SetTexture(atext)
        actor.GetProperty().SetDiffuseColor(0.5, 0.8, 0.8)
        actor.GetProperty().SetAmbient(0.2)
        actor.GetProperty().SetAmbientColor(0.2, 0.2, 0.2)

        squad.SetPhiRoundness(prs.get())
        squad.SetThetaRoundness(trs.get())
        squad.SetToroidal(toroid.get())
        squad.SetThickness(thicks.get())
        squad.SetScale(1, 1, 1)
        SetTexture(actor, atext, self.renWin)

        # Create renderer stuff
        #
        ren = vtk.vtkRenderer()
        ren.SetAmbient(1.0, 1.0, 1.0)
        self.renWin.AddRenderer(ren)

        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(actor)
        ren.SetBackground(0.25, 0.2, 0.2)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.2)
        ren.GetActiveCamera().Elevation(40)
        ren.GetActiveCamera().Azimuth(-20)

        # Associate the functions with the sliders and check buttons.
        #
        prs.config(command=partial(SetPhi, squad, self.renWin))
        trs.config(command=partial(SetTheta, squad, self.renWin))
        thicks.config(command=partial(SetThickness, squad, self.renWin))
        torbut.config(command=partial(SetToroid, squad, thicks, self.renWin))
        texbut.config(command=partial(SetTexture, actor, atext, self.renWin))