示例#1
0
def BuildBackdrop (minX, maxX, minY, maxY, minZ, maxZ, thickness):
    global basePlane
    global baseMapper
    global base
    global backPlane
    global backMapper
    global back
    global left
    global leftPlane
    global leftMapper

    if not basePlane:
        basePlane = vtk.vtkCubeSource()
    basePlane.SetCenter( (maxX + minX)/2.0, minY, (maxZ + minZ)/2.0)
    basePlane.SetXLength(maxX-minX)
    basePlane.SetYLength(thickness)
    basePlane.SetZLength(maxZ - minZ)

    if not baseMapper:
        baseMapper = vtk.vtkPolyDataMapper()
    baseMapper.SetInputConnection(basePlane.GetOutputPort())

    if not base:
        base = vtk.vtkActor()
    base.SetMapper(baseMapper)

    if not backPlane:
        backPlane = vtk.vtkCubeSource()
    backPlane.SetCenter( (maxX + minX)/2.0, (maxY + minY)/2.0, minZ)
    backPlane.SetXLength(maxX-minX)
    backPlane.SetYLength(maxY - minY)
    backPlane.SetZLength(thickness)

    if not backMapper:
        backMapper = vtk.vtkPolyDataMapper()
    backMapper.SetInputConnection(backPlane.GetOutputPort())

    if not back:
        back = vtk.vtkActor()
    back.SetMapper(backMapper)

    if not leftPlane:
        leftPlane = vtk.vtkCubeSource()
    leftPlane.SetCenter( minX, (maxY+minY)/2.0, (maxZ+minZ)/2.0)
    leftPlane.SetXLength(thickness)
    leftPlane.SetYLength(maxY-minY)
    leftPlane.SetZLength(maxZ-minZ)

    if not leftMapper:
        leftMapper = vtk.vtkPolyDataMapper()
    leftMapper.SetInputConnection(leftPlane.GetOutputPort())

    if not left:
        left = vtk.vtkActor()
    left.SetMapper(leftMapper)

    return [base, back, left]
示例#2
0
def BuildBackdrop (minX, maxX, minY, maxY, minZ, maxZ, thickness):
    global basePlane
    global baseMapper
    global base
    global backPlane
    global backMapper
    global back
    global left
    global leftPlane
    global leftMapper
    
    if not basePlane:
        basePlane = vtk.vtkCubeSource()
    basePlane.SetCenter( (maxX + minX)/2.0, minY, (maxZ + minZ)/2.0)
    basePlane.SetXLength(maxX-minX)
    basePlane.SetYLength(thickness)
    basePlane.SetZLength(maxZ - minZ)

    if not baseMapper:
        baseMapper = vtk.vtkPolyDataMapper()
    baseMapper.SetInput(basePlane.GetOutput())

    if not base:
        base = vtk.vtkActor()
    base.SetMapper(baseMapper)

    if not backPlane:
        backPlane = vtk.vtkCubeSource()
    backPlane.SetCenter( (maxX + minX)/2.0, (maxY + minY)/2.0, minZ)
    backPlane.SetXLength(maxX-minX)
    backPlane.SetYLength(maxY - minY)
    backPlane.SetZLength(thickness)

    if not backMapper:
        backMapper = vtk.vtkPolyDataMapper()
    backMapper.SetInput(backPlane.GetOutput())

    if not back:
        back = vtk.vtkActor()
    back.SetMapper(backMapper)

    if not leftPlane:
        leftPlane = vtk.vtkCubeSource()
    leftPlane.SetCenter( minX, (maxY+minY)/2.0, (maxZ+minZ)/2.0)
    leftPlane.SetXLength(thickness)
    leftPlane.SetYLength(maxY-minY)
    leftPlane.SetZLength(maxZ-minZ)

    if not leftMapper:
        leftMapper = vtk.vtkPolyDataMapper()
    leftMapper.SetInput(leftPlane.GetOutput())

    if not left:
        left = vtk.vtkActor()
    left.SetMapper(leftMapper)

    return [base, back, left] 
示例#3
0
    def renderSetup(self):
        if self.drawType == "arrow":
            arrowSource = vtk.vtkArrowSource()
            mapper = vtk.vtkPolyDataMapper()
            if vtk.VTK_MAJOR_VERSION <= 5:
                mapper.SetInput(arrowSource.GetOutput())
            else:
                mapper.SetInputConnection(arrowSource.GetOutputPort())
            # Create actor that we will position according to dVRK
            self.arrowActor = makeArrowActor()
            self.targetActor = makeArrowActor(coneRadius=.07, shaftRadius=.02)
            self.targetActor.GetProperty().SetOpacity(.2)
            self.ren.AddActor(self.arrowActor)
            self.ren.AddActor(self.targetActor)

        elif self.drawType == "bar":
            # Make two color bars to show current force
            source = vtk.vtkCubeSource()
            source.SetBounds((-.002, .002, 0, .05, 0, .001))
            mapper = vtk.vtkPolyDataMapper()
            if vtk.VTK_MAJOR_VERSION <= 5:
                mapper.SetInput(source.GetOutput())
            else:
                mapper.SetInputConnection(source.GetOutputPort())
            self.bar = vtk.vtkActor()
            self.bar.SetMapper(mapper)
            self.bar.GetProperty().SetColor(.2, .2, .2)
            self.bar.GetProperty().LightingOff()
            self.forceBar = vtk.vtkActor()
            self.forceBar.SetMapper(mapper)
            self.forceBar.GetProperty().LightingOff()
            self.ren.AddActor(self.bar)
            self.ren.AddActor(self.forceBar)
            # Make a green line to show target force
            source2 = vtk.vtkCubeSource()
            source2.SetBounds((-.002, .002, .0245, .0255, 0, .001001))
            mapper2 = vtk.vtkPolyDataMapper()
            if vtk.VTK_MAJOR_VERSION <= 5:
                mapper2.SetInput(source2.GetOutput())
            else:
                mapper2.SetInputConnection(source2.GetOutputPort())
            self.greenLine = vtk.vtkActor()
            self.greenLine.SetMapper(mapper2)
            self.greenLine.GetProperty().SetColor(.9, .9, .9)
            self.greenLine.GetProperty().LightingOff()
            self.ren.AddActor(self.greenLine)

        # Setup interactor
        self.iren = self.GetRenderWindow().GetInteractor()
        self.iren.RemoveObservers('LeftButtonPressEvent')
        self.iren.RemoveObservers('LeftButtonReleaseEvent')
        self.iren.RemoveObservers('MouseMoveEvent')
        self.iren.RemoveObservers('MiddleButtonPressEvent')
        self.iren.RemoveObservers('MiddleButtonPressEvent')
        self.currentForce
示例#4
0
    def __init__(self, renderer):
        Visualizer.__init__(self)

        assert isinstance(renderer, vtk.vtkRenderer)
        self.ren = renderer

        # -------- add the beam ----
        # geometry
        self.beam = vtk.vtkCubeSource()
        self.beam.SetXLength(st.visBeamLength)
        self.beam.SetYLength(st.visBeamWidth)
        self.beam.SetZLength(st.visBeamDepth)

        # mapper
        self.beamMapper = vtk.vtkPolyDataMapper()
        self.beamMapper.SetInputConnection(self.beam.GetOutputPort())

        # actor
        self.beamActor = vtk.vtkLODActor()
        self.beamActor.SetMapper(self.beamMapper)

        # make it look nice
        self.beamProp = self.beamActor.GetProperty()
        self.beamProp.SetColor(101 / 255, 123 / 255, 131 / 255)

        self.ren.AddActor(self.beamActor)

        # -------- add the ball ----
        # geometry
        self.ball = vtk.vtkSphereSource()
        self.ball.SetRadius(st.visR)
        self.ball.SetThetaResolution(20)
        self.ball.SetPhiResolution(20)

        # mapper
        self.ballMapper = vtk.vtkPolyDataMapper()
        self.ballMapper.SetInputConnection(self.ball.GetOutputPort())

        # actor
        self.ballActor = vtk.vtkLODActor()
        self.ballActor.SetMapper(self.ballMapper)

        # make it look nice
        self.ballProp = self.ballActor.GetProperty()
        self.ballProp.SetColor(255 / 255, 255 / 255, 0)
        self.ballProp.SetAmbient(0.2)
        self.ballProp.SetDiffuse(0.8)
        self.ballProp.SetSpecular(0.5)
        self.ballProp.SetSpecularPower(0.5)

        self.ren.AddActor(self.ballActor)

        # add background
        self.ren.GradientBackgroundOn()
        self.ren.SetBackground(228 / 255, 232 / 255, 213 / 255)
        self.ren.SetBackground2(38 / 255, 139 / 255, 210 / 255)

        # get everybody into the frame
        self.ren.ResetCamera()
        self.ren.GetActiveCamera().Zoom(1.7)
示例#5
0
    def initPlatform(self):
        qDebug('initPlatform()')

        #* Platform Model
        platformModelMapper = vtk.vtkPolyDataMapper()

        self.platformModel = vtk.vtkCubeSource()
        platformModelMapper.SetInputConnection(
            self.platformModel.GetOutputPort())

        self.platformModelActor = vtk.vtkActor()
        self.platformModelActor.SetMapper(platformModelMapper)
        self.platformModelActor.GetProperty().SetColor(1, 1, 1)
        self.platformModelActor.GetProperty().LightingOn()
        self.platformModelActor.GetProperty().SetOpacity(1)
        self.platformModelActor.GetProperty().SetAmbient(0.45)
        self.platformModelActor.GetProperty().SetDiffuse(0.4)

        self.platformModelActor.PickableOff()
        self.renderer.AddActor(self.platformModelActor)

        #* Platform Grid
        self.platformGrid = vtk.vtkPolyData()

        platformGridMapper = vtk.vtkPolyDataMapper()
        platformGridMapper.SetInputData(self.platformGrid)

        self.platformGridActor = vtk.vtkActor()
        self.platformGridActor.SetMapper(platformGridMapper)
        self.platformGridActor.GetProperty().LightingOff()
        self.platformGridActor.GetProperty().SetColor(0.45, 0.45, 0.45)
        self.platformGridActor.GetProperty().SetOpacity(1)
        self.platformGridActor.PickableOff()
        self.renderer.AddActor(self.platformGridActor)
        self.updatePlatform()
示例#6
0
    def __init__(self):

        # VTK Data
        self.vtk_poly_data = vtk.vtkPolyData()
        self.vtk_points = vtk.vtkPoints()
        self.vtk_cells = vtk.vtkCellArray()

        self.vtk_poly_data.SetPoints(self.vtk_points)
        self.vtk_poly_data.SetVerts(self.vtk_cells)
        self.vtk_poly_data.Modified()

        # Cube Source
        self.vtk_cube_source = vtk.vtkCubeSource()

        # Glyph 3D
        self.vtk_glyph_3d = vtk.vtkGlyph3D()
        self.vtk_glyph_3d.SetSourceConnection(
            self.vtk_cube_source.GetOutputPort())
        self.vtk_glyph_3d.SetInputData(self.vtk_poly_data)
        self.vtk_glyph_3d.ScalingOff()
        self.vtk_glyph_3d.Update()

        # Data Set Mapper
        self.vtk_data_set_mapper = vtk.vtkDataSetMapper()

        # Actor for Boxes
        self.vtk_actor = vtk.vtkActor()
        self.vtk_actor.SetMapper(self.vtk_data_set_mapper)
        self.vtk_actor.GetProperty().SetRepresentationToWireframe()
        self.vtk_actor.GetProperty().SetLineWidth(2)

        # Actor for Orientation Lines
        self.vtk_lines_actor = vtk.vtkActor()
        self.vtk_lines_actor.GetProperty().SetLineWidth(2)
示例#7
0
    def add_blocks(self):

        for key, block in self.blocks.items():

            cube = vtk.vtkCubeSource()
            cube.SetXLength(block.blocksDimensions[0])
            cube.SetYLength(block.blocksDimensions[1])
            cube.SetZLength(block.blocksDimensions[2])

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

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

            # random_color=random.randint(30,70)/100.0
            actor.GetProperty().SetColor(0.4, 0.4, 0.4)
            actor.SetPosition(block.blocksCentroid[0], block.blocksCentroid[1],
                              block.blocksCentroid[2])
            actor.key = key

            self.balloonWidget.AddBalloon(actor, "Block %s" % block.blockID)

            try:
                if actor.key in self.toRemove:
                    continue
                else:
                    self.renderer.AddActor(actor)
            except NameError:
                self.renderer.AddActor(actor)
                continue
示例#8
0
    def _add_box(self, region):
        # create cube
        cube = vtk.vtkCubeSource()
        dimensions = region.regionDimensions
        #cube.SetCenter(0.0, 0.0, 0.0)
        cube.SetBounds(dimensions.minimumX / 10.0, dimensions.maximumX / 10.0,
                       dimensions.minimumY / 10.0, dimensions.maximumY / 10.0,
                       dimensions.minimumZ / 10.0, dimensions.maximumZ / 10.0)
        self.maximum_size_nm = max(
            self.maximum_size_nm, dimensions.minimumX / 10.0,
            dimensions.maximumX / 10.0, dimensions.minimumY / 10.0,
            dimensions.maximumY / 10.0, dimensions.minimumZ / 10.0,
            dimensions.maximumZ / 10.0)

        # mapper
        cubeMapper = vtk.vtkPolyDataMapper()
        # cubeMapper.SetInputData(cube.GetOutput())
        cubeMapper.SetInputConnection(cube.GetOutputPort())

        # actor
        cubeActor = vtk.vtkActor()
        cubeActor.SetMapper(cubeMapper)
        cubeActor.GetProperty().SetColor(next(colors))
        cubeActor.GetProperty().SetOpacity(0.2)
        cubeActor.GetProperty().SetEdgeVisibility(True)

        self.renderer.AddActor(cubeActor)

        self._rescale_axes()
示例#9
0
    def create(self):
        source = vtk.vtkCubeSource()
        source.SetXLength(1.5 * FlowChannel.RADIUS)
        source.SetYLength(self._length)
        source.SetZLength(1.5 * FlowChannel.RADIUS)

        self._mapper = vtk.vtkPolyDataMapper()
        self._mapper.SetInputConnection(source.GetOutputPort())

        self._actor = vtk.vtkActor()
        self._actor.SetMapper(self._mapper)
        self._actor.SetPosition(self._position)
        self._actor.SetOrientation(self._vtk_orientation)

        self._silhouette = vtk.vtkPolyDataSilhouette()
        self._silhouette.SetInputData(self._mapper.GetInput())

        self._silhouette_mapper = vtk.vtkPolyDataMapper()
        self._silhouette_mapper.SetInputConnection(
            self._silhouette.GetOutputPort())

        self._silhouette_actor = vtk.vtkActor()
        self._silhouette_actor.SetMapper(self._silhouette_mapper)
        self._silhouette_actor.SetPosition(self._position)
        self._silhouette_actor.SetOrientation(self._vtk_orientation)

        self._caption_actor = self._createCaptionActor()
        self._caption_actor.SetAttachmentPoint(self._position)
示例#10
0
def main():
    colors = vtk.vtkNamedColors()

    diskSource = vtk.vtkCubeSource()

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

    actor = vtk.vtkActor()
    actor.GetProperty().SetColor(colors.GetColor3d("Cornsilk"))
    actor.SetMapper(mapper)

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Disk")
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actors to the scene
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("DarkGreen"))

    # Render and interact
    renderWindow.Render()
    renderWindowInteractor.Start()
示例#11
0
    def __init__(self,
                 node,
                 tag=-1,
                 u_def=[],
                 size=0.01,
                 enableTransformation=True):
        super().__init__()

        self.node = node
        self.size = size
        if u_def == []:
            self.x = node.x
            self.y = node.y
            self.z = node.z
        else:
            self.x = u_def[0]
            self.y = u_def[1]
            self.z = u_def[2]

        self.color = [0, 0, 1]
        self.special = False
        self.tag = tag
        if enableTransformation:
            self.enable_transformation()

        self.sphere = vtk.vtkSphereSource()
        self.cube = vtk.vtkCubeSource()

        self._object = vtk.vtkPolyData()

        self._colorFilter = vtk.vtkUnsignedCharArray()
        self._colorFilter.SetNumberOfComponents(3)

        self._mapper = vtk.vtkPolyDataMapper()
    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self, parent)

        self.frame = QtGui.QFrame()

        self.vl = QtGui.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget)

        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.interactor = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Generate polygon data for a cube
        self.cube = vtk.vtkCubeSource()

        # Create a mapper and an actor for the cube data
        self.cube_mapper = vtk.vtkPolyDataMapper()
        self.cube_mapper.SetInput(self.cube.GetOutput())
        self.cube_actor = vtk.vtkActor()
        self.cube_actor.SetMapper(self.cube_mapper)
        self.cube_actor.GetProperty().SetColor(0.0, 1.0, 0.0)  # make the cube red

        # Create a renderer and add the cube actor to it
        self.ren.SetBackground(0.0, 0.0, 0.0)  # make the background black
        self.ren.AddActor(self.cube_actor)

        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)
        self.show()
        self.interactor.Initialize()
示例#13
0
 def __init__(self, pos, radius, rgb=[0.62, 0, 0.77]):
     self.source = vtk.vtkCubeSource()
     self.mapper = vtk.vtkPolyDataMapper()
     
     # length of sides
     self.source.SetXLength(radius)
     self.source.SetYLength(radius)
     self.source.SetZLength(radius)
     
     # centre
     self.source.SetCenter(pos)
     
     # edges filter
     edges = vtk.vtkExtractEdges()
     edges.SetInputConnection(self.source.GetOutputPort())
     
     # tube filter
     tubes = vtk.vtkTubeFilter()
     tubes.SetInputConnection(edges.GetOutputPort())
     tubes.SetRadius(0.15)
     tubes.SetNumberOfSides(5)
     tubes.UseDefaultNormalOn()
     tubes.SetDefaultNormal(.577, .577, .577)
     
     # mapper
     self.mapper.SetInputConnection(tubes.GetOutputPort())
     
     # actor
     self.SetMapper(self.mapper)
     self.GetProperty().SetColor(rgb)
示例#14
0
    def __init__(self):

        pypes.pypeScript.__init__(self)

        self.CubeSource = vtk.vtkCubeSource()
        self.CubeActor = vtk.vtkActor()
        
        self.BoxActive = 0
        self.BoxBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

        self.CroppedImage = vtk.vtkImageData()

        self.vmtkRenderer = None
        self.OwnRenderer = 0

        self.PlaneWidgetX = None
        self.PlaneWidgetY = None
        self.PlaneWidgetZ = None
        self.BoxWidget = None

        self.Image = None

        self.Interactive = 1

        self.SetScriptName('vmtkimagevoiselector')
        self.SetScriptDoc('select a cubical volume of interest and get rid of the rest of the image')
        self.SetInputMembers([
            ['Image','i','vtkImageData',1,'','the input image','vmtkimagereader'],
            ['Interactive','interactive','bool',1,'','toggle interactivity'],
            ['BoxBounds','boxbounds','float',6,'','bounds of the cubical region of interest'],
            ['vmtkRenderer','renderer','vmtkRenderer',1,'','external renderer']
            ])
        self.SetOutputMembers([
            ['Image','o','vtkImageData',1,'','the output image','vmtkimagewriter']
            ])
示例#15
0
    def addCube(self,pos,tam,img=False):
        jpegfile = "struct.jpg"
        
        # Read the image data from a file
        reader = vtk.vtkJPEGReader()
        reader.SetFileName(jpegfile)
         
        (x,y,z) = pos
        (i,j,k) = tam

        cubito = vtk.vtkCubeSource()
        cubito.SetXLength(0.2*i)
        cubito.SetYLength(0.2*j)
        cubito.SetZLength(0.2*k)
        cubito.SetCenter((x,y,z)) 
        if img == True:
            
            # Create texture object
            texture = vtk.vtkTexture()
            if vtk.VTK_MAJOR_VERSION <= 5:
                texture.SetInput(reader.GetOutput())
            else:
                texture.SetInputConnection(reader.GetOutputPort())
            # Map texture coordinates
            map_to_sphere = vtk.vtkTextureMapToPlane()
            if vtk.VTK_MAJOR_VERSION <= 5:
                map_to_sphere.SetInput(cubito.GetOutput())
            else:
                map_to_sphere.SetInputConnection(cubito.GetOutputPort())
            #map_to_sphere.PreventSeamOn()
             
            # Create mapper and set the mapped texture as input
            mapper = vtk.vtkPolyDataMapper()
            if vtk.VTK_MAJOR_VERSION <= 5:
                mapper.SetInput(map_to_sphere.GetOutput())
            else:
                mapper.SetInputConnection(map_to_sphere.GetOutputPort())
            
        

        planeMapper = vtk.vtkPolyDataMapper()
        planeMapper.SetInputConnection(cubito.GetOutputPort())
        planeActor = (vtk.vtkActor())
        if (img == True):
            planeActor.SetMapper(mapper)
        else:
            planeActor.SetMapper(planeMapper)# mapper planeMapper
        planeActor.DragableOn()
        planeActor.SetDragable(1)
        if (img== True):
            planeActor.SetTexture(texture)
        else:
            planeActor.GetProperty().SetColor(.0,.3,.6)
            planeActor.GetProperty().SetOpacity(0.95)
        #planeActor.GetProperty().SetAmbient(0)
        #planeActor.GetProperty().SetDiffuse(0.9)
        #planeActor.GetProperty().SetSpecular(0.1)
        self.render.AddActor(planeActor)
        
        return planeActor
示例#16
0
def loadTestVTKWindow(parentUI):

    cube = vtk.vtkCubeSource()
    cube.SetXLength(200)
    cube.SetYLength(200)
    cube.SetZLength(200)
    cube.Update()
    cm = vtk.vtkPolyDataMapper()
    cm.SetInputConnection(cube.GetOutputPort())
    ca = vtk.vtkActor()
    ca.SetMapper(cm)
    parentUI.vtkInstances[-1].ren.AddActor(ca)

    axesActor = vtk.vtkAnnotatedCubeActor()
    axesActor.SetXPlusFaceText('R')
    axesActor.SetXMinusFaceText('L')
    axesActor.SetYMinusFaceText('H')
    axesActor.SetYPlusFaceText('F')
    axesActor.SetZMinusFaceText('P')
    axesActor.SetZPlusFaceText('A')
    axesActor.GetTextEdgesProperty().SetColor(1, 1, 0)
    axesActor.GetTextEdgesProperty().SetLineWidth(2)
    axesActor.GetCubeProperty().SetColor(0, 0, 1)
    axes = vtk.vtkOrientationMarkerWidget()
    axes.SetOrientationMarker(axesActor)
    axes.SetInteractor(parentUI.vtkInstances[-1].iren)

    parentUI.vtkInstances[-1].ren.ResetCamera()
    parentUI.vtkInstances[-1].iren.Start()
示例#17
0
def add_tube(prev, x, y):
    cylA = create_cylinder(r=3.155, h=8.6)

    cube = vtk.vtkCubeSource()
    cube.SetXLength(.75)
    cube.SetYLength(6.6)
    cube.SetZLength(13.6)
    cube.SetCenter(0, 1, 0)

    bA = vtkbool.vtkPolyDataBooleanFilter()
    bA.SetInputConnection(cylA.GetOutputPort())
    bA.SetInputConnection(1, cube.GetOutputPort())
    bA.SetOperModeToUnion()

    cylB = create_cylinder(r=2.405, h=8.6)

    bB = vtkbool.vtkPolyDataBooleanFilter()
    bB.SetInputConnection(bA.GetOutputPort())
    bB.SetInputConnection(1, cylB.GetOutputPort())
    bB.SetOperModeToDifference()

    tr = vtk.vtkTransform()
    tr.Translate(x, y, 4.3)
    tr.RotateX(90)

    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetTransform(tr)
    tf.SetInputConnection(bB.GetOutputPort())

    bC = vtkbool.vtkPolyDataBooleanFilter()
    bC.SetInputConnection(prev.GetOutputPort())
    bC.SetInputConnection(1, tf.GetOutputPort())
    bC.SetOperModeToUnion()

    return bC
示例#18
0
def cube_axes(size):
    render = vtk.vtkRenderer()

    cube = vtk.vtkCubeSource()
    cube.SetXLength(size)
    cube.SetYLength(size)
    cube.SetZLength(size)

    # Create a text property for both cube axes
    tprop = vtk.vtkTextProperty()
    tprop.SetColor(layer_color, layer_color, layer_color)
    tprop.ShadowOn()

    # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
    # draw the axes.  Add the actor to the renderer.
    axes = vtk.vtkCubeAxesActor2D()
    axes.SetInputConnection(cube.GetOutputPort())
    axes.SetCamera(render.GetActiveCamera())
    axes.SetLabelFormat("%6.4g")
    axes.SetFlyModeToOuterEdges()
    axes.SetFontFactor(0.8)
    axes.GetAxisLabelTextProperty().SetColor(cube_color, cube_color,
                                             cube_color)
    axes.SetAxisTitleTextProperty(tprop)
    axes.SetAxisLabelTextProperty(tprop)
    axes.GetProperty().SetColor(cube_color, cube_color, cube_color)

    return axes
示例#19
0
def Cube(center=(0., 0., 0.), x_length=1.0, y_length=1.0, z_length=1.0, bounds=None):
    """Create a cube by either specifying the center and side lengths or just
    the bounds of the cube. If ``bounds`` are given, all other arguments are
    ignored.

    Parameters
    ----------
    center : np.ndarray or list
        Center in [x, y, z].

    x_length : float
        length of the cube in the x-direction.

    y_length : float
        length of the cube in the y-direction.

    z_length : float
        length of the cube in the z-direction.

    bounds : np.ndarray or list
        Specify the bounding box of the cube. If given, all other arguments are
        ignored. ``(xMin,xMax, yMin,yMax, zMin,zMax)``
    """
    src = vtk.vtkCubeSource()
    if bounds is not None:
        if np.array(bounds).size != 6:
            raise TypeError('Bounds must be given as length 6 tuple: (xMin,xMax, yMin,yMax, zMin,zMax)')
        src.SetBounds(bounds)
    else:
        src.SetCenter(center)
        src.SetXLength(x_length)
        src.SetYLength(y_length)
        src.SetZLength(z_length)
    src.Update()
    return pyvista.wrap(src.GetOutput())
示例#20
0
def MkCube( cx, cy, cz, l ):
    CubeModel = vtk.vtkCubeSource()
    CubeModel.SetCenter(cx, cy ,cz)
    CubeModel.SetXLength(l)
    CubeModel.SetYLength(l)
    CubeModel.SetZLength(l)
    return CubeModel
示例#21
0
def drawVtkSymb(symbType, renderer, RGBcolor, vPos, vDir, scale):
    '''Adds to the renderer a symbol of type 'arrow', 'doubleArrow',
    'cone', 'doubleCone', 'sphere', 'doubleSphere','cube' , 'doubleCube',
    'cylinder', 'doubleCylinder'

    :param symbType: type of symbol (available types: 'arrow', 'doubleArrow',
           'cone', 'doubleCone', 'sphere', 'doubleSphere','cube' ,
           'doubleCube', 'cylinder', 'doubleCylinder')
    :param renderer: vtk renderer
    :param RGBcolor: list [R,G,B] with the 3 components of color
    :param vPos: list [x,y,z] with the 3 coordinates of the point where
           to place the symbol.
    :param vDir: director vector to orient the symbol
    :param scale: scale to be applied to the symbol representation
    '''
    symTpLow = symbType.lower()
    if 'arrow' in symTpLow:
        symbSource = vtk.vtkArrowSource()
    elif 'cone' in symTpLow:
        symbSource = vtk.vtkConeSource()
    elif 'sphere' in symTpLow:
        symbSource = vtk.vtkSphereSource()
    elif 'cube' in symTpLow:
        symbSource = vtk.vtkCubeSource()
    elif 'cylinder' in symTpLow:
        symbSource = vtk.vtkCylinderSource()
    vPosVx = [vPos[i] - scale / 2.0 * vDir[i]
              for i in range(3)]  #vertex position
    addSymb(symbSource, renderer, RGBcolor, vPosVx, vDir, scale)
    if 'double' in symTpLow:
        vPosVx = [vPosVx[i] - scale * vDir[i]
                  for i in range(3)]  #vertex position
        addSymb(symbSource, renderer, RGBcolor, vPosVx, vDir, scale)
示例#22
0
def cubeFactory(xLength, yLength, zLength):
    cube = vtk.vtkCubeSource()
    cube.SetXLength(xLength)
    cube.SetYLength(yLength)
    cube.SetZLength(zLength)

    return cube
示例#23
0
def getCell2vtp(vtkObj,ind):
    """
        Function gets a cell by ind and constructs a polydata from it.

    """

    # Get the cell
    cE = vtkObj.GetCell(ind)
    # Make the polygon
    if cE.GetCellType() == 11:
        # Use a cubeSource, much faster
        cube = vtk.vtkCubeSource()
        cube.SetBounds(cE.GetBounds())
        cube.Update()
        vtpObj = cube.GetOutput()
    else:
        polygons = vtk.vtkCellArray()
        for iF in range(cE.GetNumberOfFaces()):
            f = cE.GetFace(iF)
            poly = vtk.vtkPolygon()
            poly.GetPointIds().SetNumberOfIds(f.GetNumberOfPoints())
            for nr in range(f.GetNumberOfPoints()):
                poly.GetPointIds().SetId(nr,f.GetPointId(nr))
            polygons.InsertNextCell(poly)
        # Build the polydata
        vtpObj = vtk.vtkPolyData()
        vtpObj.SetPoints(obj.GetPoints())
        vtpObj.SetPolys(polygons)

    return polydata.normFilter(polydata.triangulatePolyData(vtpObj))
示例#24
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkCubeSource(), 'Processing.',
         (), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
示例#25
0
def create_actors(x, y, temperature, is_visible):
    if temperature is None:
        return None, None

    cube_source = vtk.vtkCubeSource()
    cube_source.SetXLength(30)
    cube_source.SetYLength(30)
    cube_source.SetZLength(1)
    cube_source.SetCenter(x, y - 19, 0)

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

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    temperature_label = temperature_labels[get_temperature_label_index(
        temperature)]
    actor.GetProperty().SetColor(
        temperature_colors.GetColor3d(temperature_label))
    actor.SetVisibility(is_visible)

    atext = vtk.vtkVectorText()
    atext.SetText("{:.1f}".format(temperature).center(5))
    textMapper = vtk.vtkPolyDataMapper()
    textMapper.SetInputConnection(atext.GetOutputPort())
    textActor = vtk.vtkFollower()
    textActor.SetMapper(textMapper)
    textActor.SetScale(8, 8, 8)
    textActor.AddPosition(x - 16, y - 23, 1)
    textActor.GetProperty().SetColor(0, 0, 0)
    textActor.SetVisibility(is_visible)

    return actor, textActor
    def __init__(self):
        self.context = zmq.Context()

        self.PUB = self.context.socket(zmq.PUB)
        self.PUB.bind("tcp://*:5555")

        self.SUB = self.context.socket(zmq.SUB)
        self.SUB.bind("tcp://*:5556")
        self.SUB.setsockopt_string(zmq.SUBSCRIBE, np.unicode(''))

        self.REP = self.context.socket(zmq.REP)
        self.REP.bind("tcp://*:5557")

        self.run()
        logging.info('Connection establihed')

        self.id.Identity()
        cube = vtk.vtkCubeSource()
        centerPointCoord = [0.0, 0.0, 0.0]
        cube.SetCenter(centerPointCoord)
        cube.SetXLength(20)
        cube.SetYLength(5)
        cube.SetZLength(10)
        cube.Update()
        modelsLogic = slicer.modules.models.logic()
        model = modelsLogic.AddModel(cube.GetOutput())
        model.GetDisplayNode().SetSliceIntersectionVisibility(True)
        model.GetDisplayNode().SetSliceIntersectionThickness(3)
        model.GetDisplayNode().SetColor(1, 0, 0)
示例#27
0
def getCell2vtp(vtkObj, ind):
    """
        Function gets a cell by ind and constructs a polydata from it.

    """

    # Get the cell
    cE = vtkObj.GetCell(ind)
    # Make the polygon
    if cE.GetCellType() == 11:
        # Use a cubeSource, much faster
        cube = vtk.vtkCubeSource()
        cube.SetBounds(cE.GetBounds())
        cube.Update()
        vtpObj = cube.GetOutput()
    else:
        polygons = vtk.vtkCellArray()
        for iF in range(cE.GetNumberOfFaces()):
            f = cE.GetFace(iF)
            poly = vtk.vtkPolygon()
            poly.GetPointIds().SetNumberOfIds(f.GetNumberOfPoints())
            for nr in range(f.GetNumberOfPoints()):
                poly.GetPointIds().SetId(nr, f.GetPointId(nr))
            polygons.InsertNextCell(poly)
        # Build the polydata
        vtpObj = vtk.vtkPolyData()
        vtpObj.SetPoints(obj.GetPoints())
        vtpObj.SetPolys(polygons)

    return normFilter(triangulatePolyData(vtpObj))
示例#28
0
    def __init__(self):

        pypes.pypeScript.__init__(self)

        self.CubeSource = vtk.vtkCubeSource()
        self.CubeActor = vtk.vtkActor()
        
        self.BoxActive = 0
        self.BoxBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

        self.CroppedImage = vtk.vtkImageData()

        self.vmtkRenderer = None
        self.OwnRenderer = 0

        self.PlaneWidgetX = None
        self.PlaneWidgetY = None
        self.PlaneWidgetZ = None
        self.BoxWidget = None

        self.Image = None

        self.Interactive = 1

        self.SetScriptName('vmtkimagevoiselector')
        self.SetScriptDoc('select a cubical volume of interest and get rid of the rest of the image')
        self.SetInputMembers([
            ['Image','i','vtkImageData',1,'','the input image','vmtkimagereader'],
            ['Interactive','interactive','bool',1,'','toggle interactivity'],
            ['BoxBounds','boxbounds','float',6,'','bounds of the cubical region of interest'],
            ['vmtkRenderer','renderer','vmtkRenderer',1,'','external renderer']
            ])
        self.SetOutputMembers([
            ['Image','o','vtkImageData',1,'','the output image','vmtkimagewriter']
            ])
示例#29
0
    def __init__(self, renderer):
        Visualizer.__init__(self)

        assert isinstance(renderer, vtk.vtkRenderer)
        self.ren = renderer
    
        # -------- add the beam ----
        # geometry
        self.beam = vtk.vtkCubeSource()
        self.beam.SetXLength(st.visBeamLength)
        self.beam.SetYLength(st.visBeamWidth)
        self.beam.SetZLength(st.visBeamDepth)

        # mapper
        self.beamMapper = vtk.vtkPolyDataMapper()
        self.beamMapper.SetInputConnection(self.beam.GetOutputPort())

        # actor
        self.beamActor = vtk.vtkLODActor()
        self.beamActor.SetMapper(self.beamMapper)

        # make it look nice
        self.beamProp = self.beamActor.GetProperty()
        self.beamProp.SetColor(101 / 255, 123 / 255, 131 / 255)

        self.ren.AddActor(self.beamActor)

        # -------- add the ball ----
        # geometry
        self.ball = vtk.vtkSphereSource()
        self.ball.SetRadius(st.visR)
        self.ball.SetThetaResolution(20)
        self.ball.SetPhiResolution(20)

        # mapper
        self.ballMapper = vtk.vtkPolyDataMapper()
        self.ballMapper.SetInputConnection(self.ball.GetOutputPort())

        # actor
        self.ballActor = vtk.vtkLODActor()
        self.ballActor.SetMapper(self.ballMapper)

        # make it look nice
        self.ballProp = self.ballActor.GetProperty()
        self.ballProp.SetColor(255 / 255, 255 / 255, 0)
        self.ballProp.SetAmbient(0.2)
        self.ballProp.SetDiffuse(0.8)
        self.ballProp.SetSpecular(0.5)
        self.ballProp.SetSpecularPower(0.5)

        self.ren.AddActor(self.ballActor)

        # add background
        self.ren.GradientBackgroundOn()
        self.ren.SetBackground(228 / 255, 232 / 255, 213 / 255)
        self.ren.SetBackground2(38 / 255, 139 / 255, 210 / 255)

        # get everybody into the frame
        self.ren.ResetCamera()
        self.ren.GetActiveCamera().Zoom(1.7)
示例#30
0
文件: brick.py 项目: tanxcosx/vtkbool
def add_tube(prev, x, y):
    cylA = create_cylinder(r=3.155, h=8.6)

    cube = vtk.vtkCubeSource()
    cube.SetXLength(.75)
    cube.SetYLength(6.6)
    cube.SetZLength(13.6)
    cube.SetCenter(0, 1, 0)

    bA = vtkboolPython.vtkPolyDataBooleanFilter()
    bA.SetInputConnection(cylA.GetOutputPort())
    bA.SetInputConnection(1, cube.GetOutputPort())
    bA.SetOperModeToUnion()

    cylB = create_cylinder(r=2.405, h=8.6)

    bB = vtkboolPython.vtkPolyDataBooleanFilter()
    bB.SetInputConnection(bA.GetOutputPort())
    bB.SetInputConnection(1, cylB.GetOutputPort())
    bB.SetOperModeToDifference()

    tr = vtk.vtkTransform()
    tr.Translate(x, y, 4.3)
    tr.RotateX(90)

    tf = vtk.vtkTransformPolyDataFilter()
    tf.SetTransform(tr)
    tf.SetInputConnection(bB.GetOutputPort())

    bC = vtkboolPython.vtkPolyDataBooleanFilter()
    bC.SetInputConnection(prev.GetOutputPort())
    bC.SetInputConnection(1, tf.GetOutputPort())
    bC.SetOperModeToUnion()

    return bC
示例#31
0
    def render(self, pointsData, scalarsArray, radiusArray, nspecies, colouringOptions, atomScaleFactor, lut):
        """
        Render the given antisites (wire frame).
        
        """
        self._logger.debug("Rendering antisites: colour by '%s'", colouringOptions.colourBy)

        # points
        points = vtk.vtkPoints()
        points.SetData(pointsData.getVTK())

        # poly data
        polydata = vtk.vtkPolyData()
        polydata.SetPoints(points)
        polydata.GetPointData().AddArray(scalarsArray.getVTK())
        polydata.GetPointData().SetScalars(radiusArray.getVTK())

        # source
        cubeSource = vtk.vtkCubeSource()
        edges = vtk.vtkExtractEdges()
        edges.SetInputConnection(cubeSource.GetOutputPort())
        glyphSource = vtk.vtkTubeFilter()
        glyphSource.SetInputConnection(edges.GetOutputPort())
        glyphSource.SetRadius(0.05)
        glyphSource.SetVaryRadius(0)
        glyphSource.SetNumberOfSides(5)
        glyphSource.UseDefaultNormalOn()
        glyphSource.SetDefaultNormal(0.577, 0.577, 0.577)

        # glyph
        glyph = vtk.vtkGlyph3D()
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            glyph.SetSource(glyphSource.GetOutput())
            glyph.SetInput(polydata)
        else:
            glyph.SetSourceConnection(glyphSource.GetOutputPort())
            glyph.SetInputData(polydata)
        glyph.SetScaleFactor(atomScaleFactor * 2.0)
        glyph.SetScaleModeToScaleByScalar()
        glyph.ClampingOff()

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph.GetOutputPort())
        mapper.SetLookupTable(lut)
        mapper.SetScalarModeToUsePointFieldData()
        mapper.SelectColorArray("colours")
        utils.setMapperScalarRange(mapper, colouringOptions, nspecies)

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

        # store attributes
        self._actor = utils.ActorObject(actor)
        self._data["Points"] = pointsData
        self._data["Scalars"] = scalarsArray
        self._data["Radius"] = radiusArray
        self._data["LUT"] = lut
        self._data["Scale factor"] = atomScaleFactor
 def __init__(self, parent = None):
     QtGui.QMainWindow.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ren = vtk.vtkRenderer()
     self.ui.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
     self.iren = self.ui.vtkWidget.GetRenderWindow().GetInteractor()
     cube = vtk.vtkCubeSource()
     cube.SetXLength(200)
     cube.SetYLength(200)
     cube.SetZLength(200)
     cube.Update()
     cm = vtk.vtkPolyDataMapper()
     cm.SetInputConnection(cube.GetOutputPort())
     ca = vtk.vtkActor()
     ca.SetMapper(cm)
     self.ren.AddActor(ca)
     self.axesActor = vtk.vtkAnnotatedCubeActor();
     self.axesActor.SetXPlusFaceText('R')
     self.axesActor.SetXMinusFaceText('L')
     self.axesActor.SetYMinusFaceText('H')
     self.axesActor.SetYPlusFaceText('F')
     self.axesActor.SetZMinusFaceText('P')
     self.axesActor.SetZPlusFaceText('A')
     self.axesActor.GetTextEdgesProperty().SetColor(1,1,0)
     self.axesActor.GetTextEdgesProperty().SetLineWidth(2)
     self.axesActor.GetCubeProperty().SetColor(0,0,1)
     self.axes = vtk.vtkOrientationMarkerWidget()
     self.axes.SetOrientationMarker(self.axesActor)
     self.axes.SetInteractor(self.iren)
     self.axes.EnabledOn()
     self.axes.InteractiveOn()
     self.ren.ResetCamera()
示例#33
0
def setEverything(a_dict):
    values = dict()
    for k, v in a_dict.items():
        values[k] = dict()

        if v["source"] == "cube":
            #source
            values[k]["vtkSource"] = vtk.vtkCubeSource()
            values[k]["vtkSource"].SetXLength(v["xlength"])
            values[k]["vtkSource"].SetYLength(v["ylength"])
            values[k]["vtkSource"].SetZLength(v["zlength"])
            values[k]["vtkSource"].Update()
        if v["source"] == "cone":
            values[k]["vtkSource"] = vtk.vtkConeSource()
            values[k]["vtkSource"].SetRadius(v["radius"])
            values[k]["vtkSource"].SetHeight(v["height"])
            values[k]["vtkSource"].SetResolution(v["resolution"])
            values[k]["vtkSource"].Update()
        if v["source"] == "sphere":
            values[k]["vtkSource"] = vtk.vtkSphereSource()
            values[k]["vtkSource"].SetRadius(v["radius"])
            values[k]["vtkSource"].SetThetaResolution(v["thetaResolution"])
            values[k]["vtkSource"].Update()

        #map
        values[k]["vtkMap"] = vtk.vtkPolyDataMapper()
        values[k]["vtkMap"].SetInputData(values[k]["vtkSource"].GetOutput())

        #actor
        values[k]["vtkActor"] = vtk.vtkActor()
        values[k]["vtkActor"].SetPosition(v["pos"])
        values[k]["vtkActor"].SetMapper(values[k]["vtkMap"])
        values[k]["vtkActor"].GetProperty().SetColor(v["color"])
        values[k]["vtkActor"].SetOrientation(v["orientation"])
    return values
示例#34
0
 def from_shape(cls,
                shape,
                colour,
                args,
                transform,
                resolution=20,
                *args_,
                **kwargs_):
     """Initialiase a VTKMesh object from a sfftkrw.SFFShape
     
     :param shapes: an iterable of shapes
     :type shapes: ``sfftkrw.SFFShapePrimitiveList
     :param colour: the segment colour
     :type colour: ``sfftkrw.SFFRGBA``
     :param args: parsed arguments
     :type args: ``argparse.Namespace``
     :param transform: transform bearing this shape's translation from the origin
     :type transform: ``sfftkrw.SFFTransformationMatrix``
     :param int resolution: mesh resolution
     :return vtkmesh: an VTKMesh object
     :rtype vtkmesh: ``VTKMesh``  
     """
     assert resolution > 0
     vtkmesh = cls(colour, args, *args_, **kwargs_)
     from sfftk.schema import SFFEllipsoid, SFFCuboid, SFFCylinder, SFFCone
     if isinstance(shape, SFFEllipsoid):
         vtk_shape = vtk.vtkSphereSource()
         vtk_shape.SetRadius(shape.x)
         """
         :TODO: make this variable
         """
         vtk_shape.SetPhiResolution(resolution)
         vtk_shape.SetThetaResolution(resolution)
     elif isinstance(shape, SFFCylinder):
         vtk_shape = vtk.vtkCylinderSource()
         vtk_shape.SetHeight(shape.height)
         vtk_shape.SetRadius(shape.diameter / 2)
         vtk_shape.SetResolution(resolution)
     elif isinstance(shape, SFFCone):
         vtk_shape = vtk.vtkConeSource()
         vtk_shape.SetHeight(shape.height)
         vtk_shape.SetRadius(shape.bottomRadius)
         vtk_shape.SetResolution(resolution)
     elif isinstance(shape, SFFCuboid):
         vtk_shape = vtk.vtkCubeSource()
         vtk_shape.SetXLength(shape.x)
         vtk_shape.SetYLength(shape.y)
         vtk_shape.SetZLength(shape.z)
     T = transform.data_array
     vtk_shape.SetCenter(float(T[0, 3]), float(T[1, 3]), float(T[2, 3]))
     vtk_shape.Update()
     _vtkmesh = vtk_shape.GetOutput()
     # triangle filter
     triangleMesh = vtk.vtkTriangleFilter()
     triangleMesh.SetInputData(_vtkmesh)
     triangleMesh.Update()
     triangleMeshOutput = triangleMesh.GetOutput()
     vtkmesh.vtk_obj.SetPoints(triangleMeshOutput.GetPoints())
     vtkmesh.vtk_obj.SetPolys(triangleMeshOutput.GetPolys())
     return vtkmesh
def temperature_actor(x, y, temp, col):
    cube_source = vtk.vtkCubeSource()
    cube_source.SetXLength(30)
    cube_source.SetYLength(30)
    cube_source.SetZLength(1)
    cube_source.SetCenter(x, y - 19, 0)

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

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(col)
    actor.SetVisibility(True)

    atext = vtk.vtkVectorText()
    atext.SetText("{:.0f}".format(temp).center(4))
    textMapper = vtk.vtkPolyDataMapper()
    textMapper.SetInputConnection(atext.GetOutputPort())
    textActor = vtk.vtkFollower()
    textActor.SetMapper(textMapper)
    textActor.SetScale(8, 8, 8)
    textActor.AddPosition(x - 15, y - 23, 1)
    textActor.GetProperty().SetColor(1, 1, 1)
    textActor.SetVisibility(True)

    return actor, textActor
    def __init__(self):

        # Creates a cube image of height 0, thus creating a plane.
        cube = vtk.vtkCubeSource()
        cube.SetXLength(120)
        cube.SetYLength(120)
        cube.SetZLength(0)

        #cubeTransform = vtk.vtkTransform()
        #cubeTransform.Translate(0, 0, 0)
        
        cubeMapper = vtk.vtkPolyDataMapper()
        cubeMapper.SetInputConnection(cube.GetOutputPort())
        
        cubeTransformFilter = vtk.vtkTransformPolyDataFilter()
        cubeTransformFilter.SetInputConnection(cube.GetOutputPort())
        #cubeTransformFilter.SetTransform(cubeTransform)
        
        appendFilter = vtk.vtkAppendPolyData()
        #appendFilter.AddInputConnection(line.GetOutputPort())
        appendFilter.AddInputConnection(cubeTransformFilter.GetOutputPort())
       
        # gets the location of the tablet
        self.x = GlobalVariables.imageXDist/2.0 # @UndefinedVariable
        self.y = GlobalVariables.imageYDist/2.0 # @UndefinedVariable
        self.z = GlobalVariables.imageZDist/2.0 # @UndefinedVariable
        
        # moves the cube actor which is what moves the cursor
        self.cubeActor = vtk.vtkActor()
        self.cubeActor.SetMapper(cubeMapper)
        self.cubeActor.GetProperty().SetColor(0.2, 0.6, 0.8)
        self.cubeActor.SetPosition(self.x,self.y,self.z)#(self.sampleSpacing[0]/2,self.sampleSpacing[1]/2,self.sampleSpacing[2]/2)#(-30, -30, -150) #(70,90,50)
def df_to_vtp(df, output_path):
    append = vtk.vtkAppendPolyData()

    for index, row in df.iterrows():

        cube = vtk.vtkCubeSource()
        xcom = 0.5 * (row.xmax + row.xmin)
        ycom = 0.5 * (row.ymax + row.ymin)
        zcom = 0.5 * (row.zmax + row.zmin)
        xsize = row.xmax - row.xmin
        ysize = row.ymax - row.ymin
        zsize = row.zmax - row.zmin
        cube.SetCenter(xcom, ycom, zcom)
        cube.SetXLength(xsize)
        cube.SetYLength(ysize)
        cube.SetZLength(zsize)
        cube.Update()

        append.AddInput(cube.GetOutput())

    append.Update()

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetInput(append.GetOutput())
    writer.SetFileName(output_path)
    writer.Write()
示例#38
0
def get_sources():
    sources = list()

    # Create a sphere
    sphere = vtk.vtkSphereSource()
    sphere.SetCenter(0.0, 0.0, 0.0)
    sphere.Update()
    sources.append(sphere)
    # Create a cone
    cone = vtk.vtkConeSource()
    cone.SetCenter(0.0, 0.0, 0.0)
    cone.SetDirection(0, 1, 0)
    cone.Update()
    sources.append(cone)
    # Create a cube
    cube = vtk.vtkCubeSource()
    cube.SetCenter(0.0, 0.0, 0.0)
    cube.Update()
    sources.append(cube)
    # Create a cylinder
    cylinder = vtk.vtkCylinderSource()
    cylinder.SetCenter(0.0, 0.0, 0.0)
    cylinder.Update()
    sources.append(cylinder)

    return sources
示例#39
0
def insert_plane():
    img = 'floor.jpg'
    cube_source = vtk.vtkCubeSource()

    cube_source.SetCenter(0.49, 10, 10)
    cube_source.SetXLength(0.0010)
    cube_source.SetYLength(20)
    cube_source.SetZLength(20)
    cube_source.Update()

    reader = vtk.vtkJPEGReader()
    reader.SetFileName(img)

    # Create texture object
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())

    # Map texture coordinates
    map_to_plane = vtk.vtkTextureMapToPlane()
    map_to_plane.SetInputConnection(cube_source.GetOutputPort())

    # Create mapper and set the mapped texture as input
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(map_to_plane.GetOutputPort())

    # Create actor and set the mapper and the texture . uncomment if no texture

    #  mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInputConnection(cube_source.GetOutputPort())
    mapper.Update()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)
    return actor
示例#40
0
文件: utilsVtk.py 项目: lcpt/xc_utils
def drawVtkSymb(symbType,renderer, RGBcolor, vPos, vDir, scale):
    '''Adds to the renderer a symbol of type 'arrow', 'doubleArrow',
    'cone', 'doubleCone', 'sphere', 'doubleSphere','cube' , 'doubleCube',
    'cylinder', 'doubleCylinder'

    :param symbType: type of symbol (available types: 'arrow', 'doubleArrow',
           'cone', 'doubleCone', 'sphere', 'doubleSphere','cube' ,
           'doubleCube', 'cylinder', 'doubleCylinder')
    :param renderer: vtk renderer
    :param RGBcolor: list [R,G,B] with the 3 components of color
    :param vPos: list [x,y,z] with the 3 coordinates of the point where
           to place the symbol.
    :param vDir: director vector to orient the symbol
    :param scale: scale to be applied to the symbol representation
    '''
    symTpLow=symbType.lower()
    if 'arrow' in symTpLow:
        symbSource=vtk.vtkArrowSource()
    elif 'cone' in symTpLow:
        symbSource=vtk.vtkConeSource()
    elif 'sphere' in symTpLow:
        symbSource=vtk.vtkSphereSource()
    elif 'cube' in symTpLow:
        symbSource=vtk.vtkCubeSource()
    elif 'cylinder' in symTpLow:
        symbSource=vtk.vtkCylinderSource()
    vPosVx=[vPos[i]-scale/2.0*vDir[i] for i in range(3)] #vertex position
    addSymb(symbSource,renderer, RGBcolor, vPosVx, vDir, scale)
    if 'double' in symTpLow:
        vPosVx=[vPosVx[i]-scale*vDir[i] for i in range(3)] #vertex position
        addSymb(symbSource,renderer, RGBcolor, vPosVx, vDir, scale)
示例#41
0
    def __init__(self):

        pypes.pypeScript.__init__(self)

        self.CubeSource = vtk.vtkCubeSource()
        self.CubeActor = vtk.vtkActor()
        
        self.BoxActive = 0
        self.BoxBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        self.PaintValue = 0.0

        self.vmtkRenderer = None
        self.OwnRenderer = 0

        self.PlaneWidgetX = None
        self.PlaneWidgetY = None
        self.PlaneWidgetZ = None
        self.BoxWidget = None

        self.Image = None

        self.Interactive = 1

        self.SetScriptName('vmtkimagevoipainter')
        self.SetScriptDoc('fill a cubical region of an image with a given gray level')
        self.SetInputMembers([
            ['Image','i','vtkImageData',1,'','the input image','vmtkimagereader'],
            ['Interactive','interactive','bool',1,'','toggle interactivity'],
            ['BoxBounds','boxbounds','float',6,'','bounds of the cubical region for non-interactive mode'],
            ['PaintValue','paintvalue','float',1,'','graylevel to fill the region with'],
            ['vmtkRenderer','renderer','vmtkRenderer',1,'','external renderer']
            ])
        self.SetOutputMembers([
            ['Image','o','vtkImageData',1,'','the output image','vmtkimagewriter']
            ])
示例#42
0
    def update_viewer(self, event, *args):
        MarkerWindowInteractor.update_viewer(self, event, *args)
        if event=='color marker':
            marker, color = args
            marker.set_color(color)
        elif event=='label marker':
            marker, label = args
            marker.set_label(label)
            
            if shared.debug: print "Create VTK-Text", marker.get_label()
            text = vtk.vtkVectorText()
            text.SetText(marker.get_label())
            textMapper = vtk.vtkPolyDataMapper()
            textMapper.SetInput(text.GetOutput())
            textActor = self.textActors[marker]
            textActor.SetMapper(textMapper)

        elif event=='move marker':
            marker, center = args
            marker.set_center(center)
            #update the select boxes and text actor
            textActor = self.textActors[marker]
            size = marker.get_size()
            textActor.SetScale(size, size, size)
            x,y,z = marker.get_center()
            textActor.SetPosition(x+size, y+size, z+size)

            if self.boxes.has_key(marker):
                selectActor = self.boxes[marker]
                boxSource = vtk.vtkCubeSource()
                boxSource.SetBounds(marker.GetBounds())
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInput(boxSource.GetOutput())
                selectActor.SetMapper(mapper)
                
        elif event=='labels on':
            actors = self.textActors.values()
            for actor in actors:
                actor.VisibilityOn()
        elif event=='labels off':
            actors = self.textActors.values()
            for actor in actors:
                actor.VisibilityOff()
        #elif event=='select marker':
        #    marker = args[0]
        #    actor = create_box_actor_around_marker(marker)
        #    if shared.debug: print "PlaneWidgetsXYZ.update_viewer(): self.renderer.AddActor(actor)"
        #    self.renderer.AddActor(actor)
        #    self.boxes[marker] = actor
        #elif event=='unselect marker':
        #    marker = args[0]
        #    actor = self.boxes[marker]
        #    print "pwxyz: u m", repr(marker), repr(actor)
        #    self.renderer.RemoveActor(actor)
        #    del self.boxes[marker]
        elif event=="set axes directions":
            self.add_axes_labels()
            EventHandler().notify('observers update plane')
        
        self.Render()
示例#43
0
def main():
    cubeSource = vtk.vtkCubeSource()
    cubeMapper = vtk.vtkPolyDataMapper()
    cubeMapper.SetInputConnection(cubeSource.GetOutputPort())

    cubeActor = vtk.vtkActor()
    cubeActor.GetProperty().SetOpacity(0.5)
    cubeActor.SetMapper(cubeMapper)

    sphereSource = vtk.vtkSphereSource()
    sphereMapper = vtk.vtkPolyDataMapper()
    sphereMapper.SetInputConnection(sphereSource.GetOutputPort())

    sphereActor = vtk.vtkActor()
    sphereActor.GetProperty().SetColor(0.5, 1, 0.5)
    #sphereActor.GetProperty().SetOpacity(0.5);
    sphereActor.SetMapper(sphereMapper)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(cubeActor)
    renderer.AddActor(sphereActor)

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

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)
    renderer.SetBackground(0, 0, 0)
    renderWindow.Render()

    interactor.Start()
示例#44
0
def vtk_example():
    # generate a polygon data for a cube
    cube = vtk.vtkCubeSource()

    # create a mapper for the cube data
    cube_mapper = vtk.vtkPolyDataMapper()
    cube_mapper.SetInputData(cube.GetOutput())

    # connect the mapper to an actor
    cube_actor = vtk.vtkActor()
    cube_actor.SetMapper(cube_mapper)
    cube_actor.GetProperty().SetColor(1.0, 0.0, 0.0)

    # render the cube actor
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(0.0, 0.0, 0.0)
    renderer.AddActor(cube_actor)

    # create a render window
    render_window = vtk.vtkRenderWindow()
    render_window.SetWindowName("Simple VTK Scene")
    render_window.SetSize(400, 400)
    render_window.AddRenderer(renderer)

    # create the interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(render_window)

    # initialize the interactor
    interactor.Initialize()
    render_window.Render()
    interactor.Start()
示例#45
0
    def GeneratePlantPots(self, plant_list):
        """Create randomised background"""
        for plant in plant_list:
            plant_bag = vtk.vtkCubeSource()
            plant_pos = plant.StemActorList[0].GetPosition()

            plant_bag.SetXLength(POT_SIZE)
            plant_bag.SetYLength(POT_SIZE)
            plant_bag.SetZLength(POT_SIZE)
            plant_bag.Update()
            plant_bag_mapper = vtk.vtkPolyDataMapper()
            plant_bag_mapper.SetInputData(plant_bag.GetOutput())

            center_offset = np.random.normal(loc=0,
                                             scale=POT_TRANS_VAR,
                                             size=3)
            center_rot = np.random.normal(loc=0, scale=POT_ROT_VAR, size=3)
            poly_actor = vtk.vtkActor()
            poly_actor.SetMapper(plant_bag_mapper)
            poly_actor.SetPosition(plant_pos[0] + center_offset[0],
                                   -POT_SIZE / 2 + plant_pos[1],
                                   plant_pos[2] + center_offset[2])
            poly_actor.SetOrientation(center_rot)
            self.BackgroundPolydataList.append(plant_bag)
            self.BackgroundMapperList.append(plant_bag_mapper)
            self.BackgroundActorList.append(poly_actor)
示例#46
0
    def __init__(self, type='default'):
        self.ren_widget = QWidget()
        self.vtk_ren_window =  QVTKRenderWindowInteractor(self.ren_widget)
        
        self.vtk_renderer = vtk.vtkRenderer()
        self.vtk_ren_window.GetRenderWindow().AddRenderer(self.vtk_renderer)
        self.vtk_interactor = self.vtk_ren_window.GetRenderWindow().GetInteractor()
        # Create source
        source_dict = {
            "cylinder": vtk.vtkCylinderSource(),
            "sphere": vtk.vtkSphereSource(),
            "arrow": vtk.vtkArrowSource(),
            "cube": vtk.vtkCubeSource(),
            "default": vtk.vtkConeSource()
        }
        source = source_dict.get(type)
        
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())
        
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.vtk_renderer.AddActor(actor)
        self.vtk_renderer.ResetCamera()
示例#47
0
    def __init__(self, length, position=(0, 0, 0), **kwargs):
        cube = vtk.vtkCubeSource()
        cube.SetXLength(length)
        cube.SetYLength(length)
        cube.SetZLength(length)
        cube.SetCenter(position)
        cube.Update()

        super(Cube, self).__init__(cube, position, **kwargs)
示例#48
0
	def __init__(self):
		Model.__init__(self)
		self.source = vtk.vtkCubeSource()
		self.source.SetCenter(0.0, 0.0, 0.0)
		self.source.SetXLength(1.0)
		self.source.SetYLength(1.0)
		self.source.SetZLength(1.0)
		self.source.Update()
		self.Update()
示例#49
0
 def render(self, pointsData, scalarsArray, radiusArray, nspecies, colouringOptions, atomScaleFactor, lut, settings):
     """
     Render the given antisites (wire frame).
     
     """
     self._logger.debug("Rendering vacancies: colour by '%s'", colouringOptions.colourBy)
     
     # points
     points = vtk.vtkPoints()
     points.SetData(pointsData.getVTK())
     
     # poly data
     polydata = vtk.vtkPolyData()
     polydata.SetPoints(points)
     polydata.GetPointData().AddArray(scalarsArray.getVTK())
     polydata.GetPointData().SetScalars(radiusArray.getVTK())
     
     # source
     glyphSource = vtk.vtkCubeSource()
     
     # glyph
     glyph = vtk.vtkGlyph3D()
     if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
         glyph.SetSource(glyphSource.GetOutput())
         glyph.SetInput(polydata)
     else:
         glyph.SetSourceConnection(glyphSource.GetOutputPort())
         glyph.SetInputData(polydata)
     scaleVacs = 2.0 * settings.getSetting("vacScaleSize")
     glyph.SetScaleFactor(atomScaleFactor * scaleVacs)
     glyph.SetScaleModeToScaleByScalar()
     glyph.ClampingOff()
       
     # mapper
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(glyph.GetOutputPort())
     mapper.SetLookupTable(lut)
     mapper.SetScalarModeToUsePointFieldData()
     mapper.SelectColorArray("colours")
     utils.setMapperScalarRange(mapper, colouringOptions, nspecies)
     
     # actor
     actor = vtk.vtkActor()
     actor.SetMapper(mapper)
     actor.GetProperty().SetSpecular(settings.getSetting("vacSpecular"))
     actor.GetProperty().SetSpecularPower(settings.getSetting("vacSpecularPower"))
     actor.GetProperty().SetOpacity(settings.getSetting("vacOpacity"))
     
     # store attributes
     self._actor = utils.ActorObject(actor)
     self._data["Points"] = pointsData
     self._data["Scalars"] = scalarsArray
     self._data["Radius"] = radiusArray
     self._data["LUT"] = lut
     self._data["Scale factor"] = atomScaleFactor
     self._data["Vacancy opacity"] = settings.getSetting("vacOpacity")
示例#50
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(1, 1, 1)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create points
        points = vtk.vtkPoints()
        points.InsertNextPoint(0, 0, 0)
        points.InsertNextPoint(5, 0, 0)
        points.InsertNextPoint(10, 0, 0)

        # Setup scales. This can also be an Int array
        # char is used since it takes the least memory
        colors = vtk.vtkUnsignedCharArray()
        colors.SetName("colors")
        colors.SetNumberOfComponents(3)
        colors.InsertNextTupleValue((255, 0, 0))
        colors.InsertNextTupleValue((0, 255, 0))
        colors.InsertNextTupleValue((0, 0, 255))

        # Combine into a polydata
        polyData = vtk.vtkPolyData()
        polyData.SetPoints(points)
        polyData.GetPointData().SetScalars(colors)

        # Create anything you want here, we will use a cube for the demo.
        cubeSource = vtk.vtkCubeSource()
        
        glyph3D = vtk.vtkGlyph3D()
        glyph3D.SetColorModeToColorByScalar()
        glyph3D.SetSourceConnection(cubeSource.GetOutputPort())
        glyph3D.SetInput(polyData)
        glyph3D.ScalingOff() #Needed, otherwise only the red cube is visible
        glyph3D.Update()

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

        self._initialized = False
示例#51
0
def load_octomap(octomap_h5_file, conf=0.9, wireframe=False):
    h5f = h5py.File(octomap_h5_file, 'r')
    octree_data = h5f['octree'][...]

    octree_data = octree_data[octree_data[:, 4] > conf]
    pts = vtk.vtkPoints()
    #vtk_pt_data = converter.numpy_to_vtk(np.ascontiguousarray(octree_data[:, 0:3]))
    #pts.SetData(vtk_pt_data)

    use_colors = octree_data.shape[1] > 5
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    #color_data = np.ascontiguousarray(octree_data[:, 5:8])
    #colors = converter.numpy_to_vtk(color_data)
    #colors.SetName('ColorArray')
    #polydata.GetPointData().SetActiveScalars('ColorArray')

    for k in range(octree_data.shape[0]):
        pts.InsertNextPoint(*octree_data[k, 0:3])
        if use_colors:
            r = int(octree_data[k, 5])
            g = int(octree_data[k, 6])
            b = int(octree_data[k, 7])
            colors.InsertNextTupleValue((r, g, b))

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(pts)
    if use_colors:
        polydata.GetPointData().SetScalars(colors)

    cube = vtk.vtkCubeSource()
    cube.SetXLength(octree_data[0, 3])
    cube.SetYLength(octree_data[0, 3])
    cube.SetZLength(octree_data[0, 3])

    glyph = vtk.vtkGlyph3D()
    if use_colors:
        glyph.SetColorModeToColorByScalar()
    glyph.SetSourceConnection(cube.GetOutputPort())
    glyph.SetInput(polydata)
    glyph.ScalingOff()
    glyph.Update()

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

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    if wireframe:
        actor.GetProperty().SetRepresentationToWireframe()
        actor.GetProperty().SetLineWidth(1)
        actor.GetProperty().SetOpacity(0.2)
    actor.GetProperty().LightingOff()

    return actor
    def __init__(self, canvas, position, numInputs, numOutputs,
                 labelList, module_instance):
        # parent constructor
        DeVIDECanvasObject.__init__(self, canvas, position)

        # we'll fill this out later
        self._size = (0,0)
        self._numInputs = numInputs
        self.inputLines = [None] * self._numInputs
        self._numOutputs = numOutputs
        # be careful with list concatenation!
        self.outputLines = [[] for i in range(self._numOutputs)]
        self._labelList = labelList
        self.module_instance = module_instance
        # usually 2-element list.  elem0 is 0 for input port and 1 for
        # output port.  elem1 is the index.
        self.draggedPort = None
        self.enteredPort = None
        self.selected = False
        self.blocked = False

        # we'll collect the glyph and its ports in this assembly
        self.prop1 = vtk.vtkAssembly()
        # the main body glyph
        self._beb = BeveledEdgeBlock()
        self._selection_block = FilledBlock()
        self._blocked_block = FilledBlock()

        self._rbsa = vtk.vtkActor()
        # and of course the label
        self._tsa = vtk.vtkTextActor3D()

        self._iportssa = \
            [(vtk.vtkCubeSource(),vtk.vtkActor()) for _ in
                range(self._numInputs)]

        self._oportssa = \
            [(vtk.vtkCubeSource(),vtk.vtkActor()) for _ in
                range(self._numOutputs)]

        self._create_geometry()
        self.update_geometry()
示例#53
0
def getCubeActor():
    cubeSource = vtk.vtkCubeSource()
    cubeSource.SetBounds(-1, 1, -1, 1, -1, 1)
    mapper =  vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(cubeSource.GetOutputPort())
    actor = vtk.vtkActor()
    actor.GetProperty().SetOpacity(0.5)
    actor.GetProperty().SetColor(1, 0, 0)
    actor.SetMapper(mapper)

    return actor
示例#54
0
 def __init__(self,center=(2,2,0) , length=1, color=(0,1,0) ):
     """ create cube"""
     self.src = vtk.vtkCubeSource()
     self.src.SetCenter(center)
     self.src.SetXLength(length)
     self.src.SetYLength(length)
     self.src.SetZLength(length)
     
     self.mapper = vtk.vtkPolyDataMapper()
     self.mapper.SetInput(self.src.GetOutput())
     self.SetMapper(self.mapper)
     self.SetColor(color)
    def _create_wireframe_cube(self):
        cube = vtk.vtkCubeSource()
        cube.SetBounds([0.0, self._scalings[0], 0.0, self._scalings[1], 0.0, self._scalings[2]])

        cube.SetCenter([self._scalings[0] / 2.0, self._scalings[1] / 2.0, self._scalings[2] / 2.0])

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

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetRepresentationToWireframe()
        return actor
示例#56
0
文件: epdp.py 项目: ecell/newio
    def __create_wireframe_cube(self):
        cube = vtk.vtkCubeSource()
        scaling = self.settings.scaling
        cube.SetBounds(numpy.array([0.0, 1.0, 0.0, 1.0, 0.0, 1.0]) * scaling)
        cube.SetCenter(numpy.array([0.5, 0.5, 0.5]) * scaling)

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

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetRepresentationToWireframe()
        return actor
    def __init__(self):
        """
        Initializes VTK objects for rendering.
        """
        # vtk objects for rendering
        self.vtkrenderer = vtk.vtkRenderer()
        
        self.vtkcamera = vtk.vtkCamera()
        self.vtkcamera.SetPosition(self.camera_pos)
        self.vtkcamera.SetFocalPoint(0, 0, 0)
        self.vtkcamera.SetViewUp(self.camera_up)
 
        # lighting
        self.light1 = vtk.vtkLight()
        self.light1.SetIntensity(.4)
        self.light1.SetPosition(10, -10, 10)
        self.light1.SetDiffuseColor(1, 1, 1)
        self.light2 = vtk.vtkLight()
        self.light2.SetIntensity(.4)
        self.light2.SetPosition(-10, -10, 10)
        self.light2.SetDiffuseColor(1, 1, 1)
        self.light3 = vtk.vtkLight()
        self.light3.SetIntensity(.4)
        self.light3.SetPosition(10, -10, -10)
        self.light3.SetDiffuseColor(1, 1, 1)
        self.light4 = vtk.vtkLight()
        self.light4.SetIntensity(.4)
        self.light4.SetPosition(-10, -10, -10)
        self.light4.SetDiffuseColor(1, 1, 1)
        self.vtkrenderer.AddLight(self.light1)
        self.vtkrenderer.AddLight(self.light2)
        self.vtkrenderer.AddLight(self.light3)
        self.vtkrenderer.AddLight(self.light4)
        self.vtkrenderer.SetBackground(0.1, 0.1, 0.1) # Background color

        self.vtkrender_window = vtk.vtkRenderWindow()
        self.vtkrender_window.AddRenderer(self.vtkrenderer)
        self.vtkrender_window.SetSize(self.render_size)
        self.vtkrender_window_interactor = vtk.vtkRenderWindowInteractor()
        self.vtkrender_window_interactor.SetRenderWindow(self.vtkrender_window)

        # vtk objects for reading, and rendering object parts
        self.part_source = vtk.vtkCubeSource()
        self.part_output = self.part_source.GetOutput()
        self.part_mapper = vtk.vtkPolyDataMapper()
        self.part_mapper.SetInput(self.part_output)

        # exporters
        self.vtkvrml_exporter = vtk.vtkVRMLExporter()
        self.vtkobj_exporter = vtk.vtkOBJExporter()
        self.stl_writer = vtk.vtkSTLWriter()
示例#58
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()

        #Create a cube
        cube=vtk.vtkCubeSource()
        cube.SetXLength(40)
        cube.SetYLength(30)
        cube.SetZLength(20)
        cubeMapper=vtk.vtkPolyDataMapper()
        cubeMapper.SetInputConnection(cube.GetOutputPort())
         
        #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)
        plane=vtk.vtkPlane()
        plane.SetOrigin(10,0,0)
        plane.SetNormal(1,0,0)
         
        #create cutter
        cutter=vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputConnection(cube.GetOutputPort())
        cutter.Update()
        cutterMapper=vtk.vtkPolyDataMapper()
        cutterMapper.SetInputConnection( cutter.GetOutputPort())
         
        #create plane actor
        planeActor=vtk.vtkActor()
        planeActor.GetProperty().SetColor(1.0,1,0)
        planeActor.GetProperty().SetLineWidth(2)
        planeActor.SetMapper(cutterMapper)
         
        #create cube actor
        cubeActor=vtk.vtkActor()
        cubeActor.GetProperty().SetColor(0.5,1,0.5)
        cubeActor.GetProperty().SetOpacity(0.5)
        cubeActor.SetMapper(cubeMapper)
         
        #create renderers and add actors of plane and cube
        self.ren.AddActor(planeActor)
        self.ren.AddActor(cubeActor) 

        self.ren.ResetCamera()
        self._initialized = False
示例#59
0
  def test_Segmentation(self):
    """ Test the GetRASBounds & GetBounds method on a segmentation.
    """
    #self.delayDisplay("Starting test_Segmentation")
    cubeSource = vtk.vtkCubeSource()
    cubeSource.SetXLength(500)
    cubeSource.SetYLength(200)
    cubeSource.SetZLength(300)
    cubeSource.SetCenter(10, -85, 0.7)

    rotation = vtk.vtkTransform()
    rotation.RotateX(15.0)
    rotation.RotateZ(78)

    applyTransform = vtk.vtkTransformPolyDataFilter()
    applyTransform.SetTransform(rotation)
    applyTransform.SetInputConnection(cubeSource.GetOutputPort())
    applyTransform.Update()

    modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
    modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

    segmentationNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLSegmentationNode())
    segmentationLogic = slicer.modules.segmentations.logic()
    segmentationLogic.ImportModelToSegmentationNode(modelNode, segmentationNode)

    # Testing
    bounds = range(6)
    segmentationNode.GetRASBounds(bounds)
    untransformedBounds = [-65.4164152220677, 237.23434621664234, -305.4495706784099, 289.7072339384947, -217.46321203583187, 213.68731403607347]
    self.assertListAlmostEquals(bounds, untransformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)

    transform = vtk.vtkTransform()
    transform.Translate([-5.0, +42.0, -0.1])
    transform.RotateWXYZ(41, 0.7, 0.6, 75)
    transform.Scale(2, 3, 10)
    transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
    transformNode.ApplyTransform(transform)

    segmentationNode.SetAndObserveTransformNodeID(transformNode.GetID())
    transformedBounds = [-690.2701685073098, 970.3186946284741, -744.3124542486084, 1018.260811721817, -2183.4639807718822, 2144.107746300856]
    segmentationNode.GetRASBounds(bounds)
    self.assertListAlmostEquals(bounds, transformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)
示例#60
0
  def test_Segmentation(self):
    """ Test the GetRASBounds & GetBounds method on a segmentation.
    """
    #self.delayDisplay("Starting test_Segmentation")
    cubeSource = vtk.vtkCubeSource()
    cubeSource.SetXLength(500)
    cubeSource.SetYLength(200)
    cubeSource.SetZLength(300)
    cubeSource.SetCenter(10, -85, 0.7)

    rotation = vtk.vtkTransform()
    rotation.RotateX(15.0)
    rotation.RotateZ(78)

    applyTransform = vtk.vtkTransformPolyDataFilter()
    applyTransform.SetTransform(rotation)
    applyTransform.SetInputConnection(cubeSource.GetOutputPort())
    applyTransform.Update()

    modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
    modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

    segmentationNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLSegmentationNode())
    segmentationLogic = slicer.modules.segmentations.logic()
    segmentationLogic.ImportModelToSegmentationNode(modelNode, segmentationNode)

    # Testing
    bounds = range(6)
    segmentationNode.GetRASBounds(bounds)
    untransformedBounds = [-65.0710220336914, 235.9289779663086, -304.413391113281, 288.586608886719, -216.427032470703, 213.572967529297]
    self.assertListAlmostEquals(bounds, untransformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)

    transform = vtk.vtkTransform()
    transform.Translate([-5.0, +42.0, -0.1])
    transform.RotateWXYZ(41, 0.7, 0.6, 75)
    transform.Scale(2, 3, 10)
    transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
    transformNode.ApplyTransform(transform)

    segmentationNode.SetAndObserveTransformNodeID(transformNode.GetID())
    transformedBounds = [-200.70776329131795, 479.54290966330126, -723.6172978253361, 996.0765602877555, -2171.2883672792996, 2141.1537548033725]
    segmentationNode.GetRASBounds(bounds)
    self.assertListAlmostEquals(bounds, transformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)