示例#1
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.reader = vtk.vtkDICOMImageReader()

        #self.viewerL = vtk.vtkImageViewer2()
        #self.viewerR = vtk.vtkImageViewer2()

        self.renL = vtk.vtkRenderer()
        self.ui.leftVtk.GetRenderWindow().AddRenderer(self.renL)
        self.renR = vtk.vtkRenderer()
        self.ui.rightVtk.GetRenderWindow().AddRenderer(self.renR)

        self.mapperL = vtk.vtkImageMapper()
        self.mapperL.SetInputConnection(self.reader.GetOutputPort())
        self.mapperR = vtk.vtkImageMapper()

        self.actorL = vtk.vtkActor2D()
        self.actorL.SetMapper(self.mapperL)
        self.actorR = vtk.vtkActor2D()
        self.actorR.SetMapper(self.mapperR)

        self.renL.AddActor2D(self.actorL)
        self.renR.AddActor2D(self.actorR)

        self.importer = vtk.vtkImageImport()
        self.mapperR.SetInputConnection(self.importer.GetOutputPort())

        self.loadImage(os.path.join(STARTINGPATH, FILENAME))
        self.setWindowingAlg()
示例#2
0
 def InitiateScreenText(self):
   '''
   self.tpropScren = vtk.vtkTextProperty()
   size = self.GetSize()
   self.text_screen = vtk.vtkTextActor()
   self.text_screen.SetPosition(10, 10)
   self.text_screen.SetInput(' ') 
   
   self.tpropScren.SetFontSize(10)
   self.tpropScren.SetFontFamilyToArial()
   self.tpropScren.SetJustificationToLeft()
   #self.tprop.BoldOn()
   #self.tprop.ItalicOn()
   #self.tpropScren.ShadowOn()
   self.tpropScren.SetColor(0.9, 0.8, 0.8)
   self.text_screen.SetTextProperty(self.tpropScren)
   '''
   #self.scree_text_offset = 10
   self.textMapper = vtk.vtkTextMapper()
   tprop = self.textMapper.GetTextProperty()
   tprop.SetFontFamilyToArial()
   tprop.SetFontSize(10)
   #tprop.BoldOn()
   #tprop.ShadowOn()
   tprop.SetColor(0.5, 0.9, 0.5)
   self.textActor = vtk.vtkActor2D()
   self.textActor.VisibilityOff()
   self.textActor.SetMapper(self.textMapper)
   self.AddActor2D(self.textActor)                                 
示例#3
0
def CreateViewportBox(colorfg,linewidth=3) :
	pts = vtk.vtkPoints()
	pts.SetNumberOfPoints(4)
	pts.SetPoint(0, 0.0, 0.0, 0.0)
	pts.SetPoint(1, 0.0, 1.0, 0.0)
	pts.SetPoint(2, 1.0, 1.0, 0.0)
	pts.SetPoint(3, 1.0, 0.0, 0.0)
	lines = vtk.vtkCellArray()
	lines.InsertNextCell(5)
	lines.InsertCellPoint(0)
	lines.InsertCellPoint(1)
	lines.InsertCellPoint(2)
	lines.InsertCellPoint(3)
	lines.InsertCellPoint(0)
	box = vtk.vtkPolyData()
	box.SetPoints(pts)
	box.SetLines(lines)

	coords = vtk.vtkCoordinate()
	coords.SetCoordinateSystemToNormalizedViewport()

	boxmapper = vtk.vtkPolyDataMapper2D()
	boxmapper.SetInputData(box)
	boxmapper.SetTransformCoordinate(coords)

	boxactor = vtk.vtkActor2D()
	boxactor.SetMapper(boxmapper)
	boxactor.GetProperty().SetLineWidth(linewidth)
	boxactor.GetProperty().SetColor(colorfg)

	return boxactor
  def __init__(self):
    self.lookupTable = vtk.vtkLookupTable()
    self.lookupTable.SetRampToLinear()
    self.lookupTable.SetNumberOfTableValues(2)
    self.lookupTable.SetTableRange(0, 1)
    self.lookupTable.SetTableValue(0,  0, 0, 0,  0)
    self.colorMapper = vtk.vtkImageMapToRGBA()
    self.colorMapper.SetOutputFormatToRGBA()
    self.colorMapper.SetLookupTable(self.lookupTable)
    self.thresholdFilter = vtk.vtkImageThreshold()
    self.thresholdFilter.SetInValue(1)
    self.thresholdFilter.SetOutValue(0)
    self.thresholdFilter.SetOutputScalarTypeToUnsignedChar()

    # Feedback actor
    self.mapper = vtk.vtkImageMapper()
    self.dummyImage = vtk.vtkImageData()
    self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
    self.mapper.SetInputData(self.dummyImage)
    self.actor = vtk.vtkActor2D()
    self.actor.VisibilityOff()
    self.actor.SetMapper(self.mapper)
    self.mapper.SetColorWindow(255)
    self.mapper.SetColorLevel(128)

    # Setup pipeline
    self.colorMapper.SetInputConnection(self.thresholdFilter.GetOutputPort())
    self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())
示例#5
0
    def addText(self, text, x=0.03, y=0.97, size=12, orientation="left"):
        property = vtk.vtkTextProperty()
        property.SetFontSize(size)
        property.SetFontFamilyToArial()
        property.BoldOff()
        property.ItalicOff()
        # property.ShadowOn()
        if orientation == "left":
            property.SetJustificationToLeft()
        elif orientation == "right":
            property.SetJustificationToRight()
        elif orientation == "center":
            property.SetJustificationToCenter()

        property.SetVerticalJustificationToTop()
        property.SetColor(1, 1, 1)

        mapper = vtk.vtkTextMapper()
        mapper.SetTextProperty(property)
        mapper.SetInput(str(text))

        textActor = vtk.vtkActor2D()
        self.textActors.append(textActor)
        textActor.SetMapper(mapper)
        textActor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
        textActor.GetPositionCoordinate().SetValue(x, y)
        textActor.VisibilityOn()

        self.render.AddActor(textActor)
        self.Render()
示例#6
0
文件: cad_mesh.py 项目: lcpt/xc
def VtkDibujaIdsCells(uGrid, setToDraw, entTypeName, renderer):
  ids= vtk.vtkIdFilter()
  ids.SetInput(uGrid)
  ids.CellIdsOff()
  ids.PointIdsOff()

  VtkCargaIdsCells(uGrid,setToDraw,entTypeName)
    
  # Dibuja las etiquetas de las líneas.
  cc= vtk.vtkCellCenters()
  cc.SetInputConnection(ids.GetOutputPort()) #  Centroides de las celdas. 
        
  visCells= vtk.vtkSelectVisiblePoints()
  visCells.SetInputConnection(cc.GetOutputPort())
  visCells.SetRenderer(renderer)
  visCells.SelectionWindowOff()

  #Create the mapper to display the cell ids.  Specify the format to
  # use for the labels.  Also create the associated actor.
  cellMapper= vtk.vtkLabeledDataMapper()
  cellMapper.SetInputConnection(visCells.GetOutputPort())
  cellMapper.GetLabelTextProperty().SetColor(0,0,0.9)

  cellLabels= vtk.vtkActor2D()
  cellLabels.SetMapper(cellMapper)
       
  renderer.AddActor2D(cellLabels)
示例#7
0
    def __init__(self):
        self.layer = 99
        self.children = []
        property = vtk.vtkTextProperty()
        property.SetFontSize(const.TEXT_SIZE)
        property.SetFontFamilyToArial()
        property.BoldOff()
        property.ItalicOff()
        property.ShadowOn()
        property.SetJustificationToLeft()
        property.SetVerticalJustificationToTop()
        property.SetColor(const.TEXT_COLOUR)
        self.property = property

        mapper = vtk.vtkTextMapper()
        mapper.SetTextProperty(property)
        self.mapper = mapper

        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
        actor.PickableOff()
        self.actor = actor

        self.SetPosition(const.TEXT_POS_LEFT_UP)
示例#8
0
文件: cad_mesh.py 项目: lcpt/xc
def VtkDibujaIdsKPts(uGrid, setToDraw, renderer):
  '''Draw the point labels.'''
  numKPtsDI= setToDraw.getPoints.size
  if(numKPtsDI>0):
    ids= vtk.vtkIdFilter()
    ids.SetInput(uGrid)
    ids.CellIdsOff()
    ids.PointIdsOff()

    VtkCargaIdsKPts(uGrid,setToDraw)
            
    visPts= vtk.vtkSelectVisiblePoints()
    visPts.SetInputConnection(ids.GetOutputPort())
    visPts.SetRenderer(renderer)
    visPts.SelectionWindowOff()

    #Create the mapper to display the point ids.  Specify the format to
    #  use for the labels.  Also create the associated actor.
    ldm= vtk.vtkLabeledDataMapper()
    ldm.SetInputConnection(visPts.GetOutputPort())
    ldm.GetLabelTextProperty().SetColor(0.1,0.1,0.1)

    pointLabels= vtk.vtkActor2D()
    pointLabels.SetMapper(ldm)

    renderer.AddActor2D(pointLabels)
  else:
    print "El conjunto: '",setToDraw,"' no tiene KPts."
示例#9
0
 def enable(self, parent):
     self.parent = parent
     
     self.pts = vtk.vtkPoints()
     self.pts.SetNumberOfPoints(4)
     
     self.lines = vtk.vtkCellArray()
     self.lines.InsertNextCell(5)
     for i in range(4):
         self.lines.InsertCellPoint(i)
     self.lines.InsertCellPoint(0)
     
     self.pd = vtk.vtkPolyData()
     self.pd.SetPoints(self.pts)
     self.pd.SetLines(self.lines)
     
     self.bboxMapper = vtk.vtkPolyDataMapper2D()
     self.bboxMapper.SetInput(self.pd)
     self.bboxActor = vtk.vtkActor2D()
     self.bboxActor.SetMapper(self.bboxMapper)
     self.bboxActor.GetProperty().SetColor(1, 0, 0)
     
     self.parent.renderer.AddViewProp(self.bboxActor)
     
     self.pts.SetPoint(0, self.X1, self.Y1, 0)
     self.pts.SetPoint(1, self.X2, self.Y1, 0)
     self.pts.SetPoint(2, self.X2, self.Y2, 0)
     self.pts.SetPoint(3, self.X1, self.Y2, 0)
     self.bboxEnabled = False
示例#10
0
  def __init__(self, sliceWidget):
    super(QuickTCGAEffectTool,self).__init__(sliceWidget)
    # create a logic instance to do the non-gui work
    #self.logic = QuickTCGAEffectLogic(self.sliceWidget.sliceLogic())

    self.sliceWidget = sliceWidget
    self.sliceLogic = sliceWidget.sliceLogic()
    self.sliceView = self.sliceWidget.sliceView()
    self.interactor = self.sliceView.interactorStyle().GetInteractor()
    self.renderWindow = self.sliceWidget.sliceView().renderWindow()

    self.actionState = None
    self.startXYPosition = None
    self.currentXYPosition = None

    self.createGlyph()

    self.mapper = vtk.vtkPolyDataMapper2D()
    self.actor = vtk.vtkActor2D()
    self.mapper.SetInputData(self.polyData)
    self.actor.SetMapper(self.mapper)
    property_ = self.actor.GetProperty()
    property_.SetColor(1,1,0)
    property_.SetLineWidth(1)
    self.renderer.AddActor2D( self.actor )
    self.actors.append( self.actor )
示例#11
0
    def _init_canvas(self):
        w, h = self._size
        self._array = np.zeros((h, w, 4), dtype=np.uint8)

        self._cv_image = converters.np_rgba_to_vtk(self._array)

        self.mapper = vtk.vtkImageMapper()
        self.mapper.SetInputData(self._cv_image)
        self.mapper.SetColorWindow(255)
        self.mapper.SetColorLevel(128)

        self.actor = vtk.vtkActor2D()
        self.actor.SetPosition(0, 0)
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetOpacity(0.99)

        self.canvas_renderer.AddActor2D(self.actor)

        self.rgb = np.zeros((h, w, 3), dtype=np.uint8)
        self.alpha = np.zeros((h, w, 1), dtype=np.uint8)

        self.bitmap = wx.EmptyBitmapRGBA(w, h)
        try:
            self.image = wx.Image(w, h, self.rgb, self.alpha)
        except TypeError:
            self.image = wx.ImageFromBuffer(w, h, self.rgb, self.alpha)
示例#12
0
    def __create_line_actor(self, line):
        line_mapper = vtk.vtkPolyDataMapper2D()
        line_mapper.SetInput(line.GetOutput())

        line_actor = vtk.vtkActor2D()
        line_actor.SetMapper(line_mapper)
        return line_actor
示例#13
0
  def __init__(self, sliceWidget):
    super(RectangleEffectTool,self).__init__(sliceWidget)

    # create a logic instance to do the non-gui work
    self.logic = RectangleEffectLogic(self.sliceWidget.sliceLogic())

    # interaction state variables
    self.actionState = None
    self.startXYPosition = None
    self.currentXYPosition = None

    # initialization
    self.createGlyph()

    self.mapper = vtk.vtkPolyDataMapper2D()
    self.actor = vtk.vtkActor2D()
    if vtk.VTK_MAJOR_VERSION <= 5:
      self.mapper.SetInput(self.polyData)
    else:
      self.mapper.SetInputData(self.polyData)
    self.actor.SetMapper(self.mapper)
    property_ = self.actor.GetProperty()
    property_.SetColor(1,1,0)
    property_.SetLineWidth(1)
    self.renderer.AddActor2D( self.actor )
    self.actors.append( self.actor )
示例#14
0
  def __init__(self, sliceWidget):

    # keep a flag since events such as sliceNode modified
    # may come during superclass construction, which will
    # invoke our processEvents method
    self.initialized = False

    super(DrawEffectTool,self).__init__(sliceWidget)

    # create a logic instance to do the non-gui work
    self.logic = DrawEffectLogic(self.sliceWidget.sliceLogic())

    # interaction state variables
    self.activeSlice = None
    self.lastInsertSLiceNodeMTime = None
    self.actionState = None

    # initialization
    self.xyPoints = vtk.vtkPoints()
    self.rasPoints = vtk.vtkPoints()
    self.polyData = self.createPolyData()

    self.mapper = vtk.vtkPolyDataMapper2D()
    self.actor = vtk.vtkActor2D()
    self.mapper.SetInputData(self.polyData)
    self.actor.SetMapper(self.mapper)
    property_ = self.actor.GetProperty()
    property_.SetColor(1,1,0)
    property_.SetLineWidth(1)
    self.renderer.AddActor2D( self.actor )
    self.actors.append( self.actor )

    self.initialized = True
示例#15
0
  def __init__(self, sliceWidget):
    super(LevelTracingEffectTool,self).__init__(sliceWidget)

    # create a logic instance to do the non-gui work
    self.logic = LevelTracingEffectLogic(self.sliceWidget.sliceLogic())

    # instance variables
    self.actionState = ''

    # initialization
    self.xyPoints = vtk.vtkPoints()
    self.rasPoints = vtk.vtkPoints()
    self.polyData = vtk.vtkPolyData()

    self.tracingFilter = vtkITK.vtkITKLevelTracingImageFilter()
    self.ijkToXY = vtk.vtkGeneralTransform()

    self.mapper = vtk.vtkPolyDataMapper2D()
    self.actor = vtk.vtkActor2D()
    property_ = self.actor.GetProperty()
    property_.SetColor( 107/255., 190/255., 99/255. )
    property_.SetLineWidth( 1 )
    if vtk.VTK_MAJOR_VERSION <= 5:
      self.mapper.SetInput(self.polyData)
    else:
      self.mapper.SetInputData(self.polyData)
    self.actor.SetMapper(self.mapper)
    property_ = self.actor.GetProperty()
    property_.SetColor(1,1,0)
    property_.SetLineWidth(1)
    self.renderer.AddActor2D( self.actor )
    self.actors.append( self.actor )
示例#16
0
  def __init__(self, sliceWidget):
    super(PaintEffectTool,self).__init__(sliceWidget)
    # create a logic instance to do the non-gui work
    self.logic = PaintEffectLogic(self.sliceWidget.sliceLogic())

    # configuration variables
    self.delayedPaint = True
    self.parameterNode = EditUtil.getParameterNode()
    self.sphere = not (0 == int(self.parameterNode.GetParameter("PaintEffect,sphere")))
    self.smudge = not (0 == int(self.parameterNode.GetParameter("PaintEffect,smudge")))
    self.pixelMode = not (0 == int(self.parameterNode.GetParameter("PaintEffect,pixelMode")))
    self.radius = float(self.parameterNode.GetParameter("PaintEffect,radius"))

    # interaction state variables
    self.position = [0, 0, 0]
    self.paintCoordinates = []
    self.feedbackActors = []
    self.lastRadius = 0

    # scratch variables
    self.rasToXY = vtk.vtkMatrix4x4()

    # initialization
    self.brush = vtk.vtkPolyData()
    self.createGlyph(self.brush)
    self.mapper = vtk.vtkPolyDataMapper2D()
    self.actor = vtk.vtkActor2D()
    self.mapper.SetInputData(self.brush)
    self.actor.SetMapper(self.mapper)
    self.actor.VisibilityOff()

    self.renderer.AddActor2D(self.actor)
    self.actors.append(self.actor)

    self.processEvent()
示例#17
0
  def __init__(self, sliceWidget):
    super(ThresholdEffectTool,self).__init__(sliceWidget)

    # create a logic instance to do the non-gui work
    self.logic = ThresholdEffectLogic(self.sliceWidget.sliceLogic())
    self.logic.undoRedo = self.undoRedo

    # interaction state variables
    self.min = 0
    self.max = 0

    # class instances
    self.lut = None
    self.thresh = None
    self.map = None

    # feedback actor
    self.cursorMapper = vtk.vtkImageMapper()
    self.cursorDummyImage = vtk.vtkImageData()
    self.cursorDummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
    self.cursorMapper.SetInputData( self.cursorDummyImage )
    self.cursorActor = vtk.vtkActor2D()
    self.cursorActor.VisibilityOff()
    self.cursorActor.SetMapper( self.cursorMapper )
    self.cursorMapper.SetColorWindow( 255 )
    self.cursorMapper.SetColorLevel( 128 )

    self.actors.append( self.cursorActor )

    self.renderer.AddActor2D( self.cursorActor )
示例#18
0
def VtkDibujaIdsElementos(nmbUGrid, setName, renderer):
  # ****** Creamos las etiquetas para las celdas *******
  ids= vtk.vtkIdFilter()
  ids.SetInput(nmbUGrid)
  ids.CellIdsOff()
  ids.PointIdsOff()
 
  VtkCargaIdsElem(nmbUGrid,setName)()
    
  # Dibuja las etiquetas de las líneas.
  cc= vtk.vtkCellCenters()
  cc.SetInput(ids) #  Centroides de las celdas. 
        
  visElems= vtk.vtkSelectVisiblePoints()
  visElems.SetInput(cc)
  visElems.SetRenderer(renderer)
  visElems.SelectionWindowOff()

  ''' Create the mapper to display the element ids.  Specify the format to
     use for the labels.  Also create the associated actor. '''
  elemMapper= vtk.vtkLabeledShStrMapper()
  elemMapper.SetInput(visElems)
  elemMapper.LabelTextProperty.SetColor(0,0,0.9)

  elemLabels= vtk.vtkActor2D()
  elemLabels.SetMapper(elemMapper)
  renderer.AddActor2D(elemLabels)
示例#19
0
    def _draw_line(self):
        line1 = vtk.vtkLineSource()
        line1.SetPoint1(self.points[0])
        line1.SetPoint2(self.points[1])

        line2 = vtk.vtkLineSource()
        line2.SetPoint1(self.points[1])
        line2.SetPoint2(self.points[2])

        arc = self.DrawArc()

        line = vtk.vtkAppendPolyData()
        line.AddInput(line1.GetOutput())
        line.AddInput(line2.GetOutput())
        line.AddInput(arc.GetOutput())

        c = vtk.vtkCoordinate()
        c.SetCoordinateSystemToWorld()

        m = vtk.vtkPolyDataMapper2D()
        m.SetInputConnection(line.GetOutputPort())
        m.SetTransformCoordinate(c)

        a = vtk.vtkActor2D()
        a.SetMapper(m)
        a.GetProperty().SetColor(self.colour)
        self.line_actor = a
示例#20
0
    def Execute(self):
 
        if not self.Centerlines:
            self.PrintError('Error: No input centerlines.')
            return
        
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self) 

        if self.CellDataArrayName:
            cellCenters = vtk.vtkCellCenters()
            cellCenters.SetInput(self.Centerlines)
            cellCenters.Update()
            cellCenters.GetOutput().GetPointData().SetActiveScalars(self.CellDataArrayName)
            labelsMapper = vtk.vtkLabeledDataMapper();
            labelsMapper.SetInput(cellCenters.GetOutput())
            labelsMapper.SetLabelModeToLabelScalars()
            labelsActor = vtk.vtkActor2D()
            labelsActor.SetMapper(labelsMapper)
            self.vmtkRenderer.Renderer.AddActor(labelsActor)

        centerlineMapper = vtk.vtkPolyDataMapper()
        centerlineMapper.SetInput(self.Centerlines)
        if self.CellDataArrayName and not self.PointDataArrayName:
            centerlineMapper.ScalarVisibilityOn()
            centerlineMapper.SetScalarModeToUseCellData()
            self.Centerlines.GetCellData().SetActiveScalars(self.CellDataArrayName)
            centerlineMapper.SetScalarRange(self.Centerlines.GetCellData().GetScalars().GetRange(0))
        elif self.PointDataArrayName:
            centerlineMapper.ScalarVisibilityOn()
            centerlineMapper.SetScalarModeToUsePointData()
            self.Centerlines.GetPointData().SetActiveScalars(self.PointDataArrayName)
            centerlineMapper.SetScalarRange(self.Centerlines.GetPointData().GetScalars().GetRange(0))
        else:
            centerlineMapper.ScalarVisibilityOff()
        centerlineActor = vtk.vtkActor()
        centerlineActor.SetMapper(centerlineMapper)
        self.vmtkRenderer.Renderer.AddActor(centerlineActor)

        scalarBarActor = None
        if self.Legend and centerlineActor and self.PointDataArrayName:
            scalarBarActor = vtk.vtkScalarBarActor()
            scalarBarActor.SetLookupTable(centerlineActor.GetMapper().GetLookupTable())
            scalarBarActor.GetLabelTextProperty().ItalicOff()
            scalarBarActor.GetLabelTextProperty().BoldOff()
            scalarBarActor.GetLabelTextProperty().ShadowOff()
            scalarBarActor.SetLabelFormat('%.2f')
            scalarBarActor.SetTitle(self.PointDataArrayName)
            self.vmtkRenderer.Renderer.AddActor(scalarBarActor)
	
	if self.Display:
            self.vmtkRenderer.Render()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
	def __init__(self):
		self.poly_list = []
		self.actor_list = []
		
		# Create shapes and actors
		boxUp = vtk.vtkRegularPolygonSource()
		boxUp.GeneratePolygonOn()
		boxUp.GeneratePolylineOff()
		boxUp.SetNumberOfSides(3)
		boxUp.SetCenter(0,14,0)
		boxUp.SetRadius(11)
		self.poly_list.append(boxUp)
		
		boxL = vtk.vtkRegularPolygonSource()
		boxL.GeneratePolygonOn()
		boxL.GeneratePolylineOff()
		boxL.SetNumberOfSides(4)
		boxL.SetCenter(-15,-2,0)
		boxL.SetRadius(9)
		self.poly_list.append(boxL)
		
		boxR = vtk.vtkRegularPolygonSource()
		boxR.GeneratePolygonOn()
		boxR.GeneratePolylineOff()
		boxR.SetNumberOfSides(4)
		boxR.SetCenter(15,-2,0)
		boxR.SetRadius(9)
		self.poly_list.append(boxR)
		
		boxLDown = vtk.vtkRegularPolygonSource()
		boxLDown.GeneratePolygonOn()
		boxLDown.GeneratePolylineOff()
		boxLDown.SetNumberOfSides(6)
		boxLDown.SetCenter(-12,-22,0)
		boxLDown.SetRadius(9)
		self.poly_list.append(boxLDown)
		
		boxRDown = vtk.vtkRegularPolygonSource()
		boxRDown.GeneratePolygonOn()
		boxRDown.GeneratePolylineOff()
		boxRDown.SetNumberOfSides(6)
		boxRDown.SetCenter(12,-22,0)
		boxRDown.SetRadius(9)
		self.poly_list.append(boxRDown)
		
		for ii, poly in enumerate(self.poly_list):
			map = vtk.vtkPolyDataMapper2D()
			map.SetInputConnection(poly.GetOutputPort(0))
			act = vtk.vtkActor2D()
			act.SetMapper(map)
			act.SetPickable(True)
			# act.GetProperty().SetColor(0.5, 0.45, 0.35)
			act.GetProperty().SetColor(0.4, 0.4, 0.4)
			act.GetProperty().SetLineWidth(0.0)
			act.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
			act.GetPositionCoordinate().SetValue(0.075 ,0.15)
			act.GetPosition2Coordinate().SetCoordinateSystemToNormalizedDisplay()
			act.GetPosition2Coordinate().SetValue(0.5, 0.5)
			self.actor_list.append(act)
示例#22
0
 def __init__(self, element_color_mapping=None, show_unit_cell=True,
              show_bonds=False, show_polyhedron=False,
              poly_radii_tol_factor=0.5, excluded_bonding_elements=None,
              animated_movie_options=DEFAULT_ANIMATED_MOVIE_OPTIONS):
     super().__init__(element_color_mapping=element_color_mapping,
                                              show_unit_cell=show_unit_cell,
                                              show_bonds=show_bonds, show_polyhedron=show_polyhedron,
                                              poly_radii_tol_factor=poly_radii_tol_factor,
                                              excluded_bonding_elements=excluded_bonding_elements)
     self.warningtxt_actor = vtk.vtkActor2D()
     self.infotxt_actor = vtk.vtkActor2D()
     self.structures = None
     style = MultiStructuresInteractorStyle(self)
     self.iren.SetInteractorStyle(style)
     self.istruct = 0
     self.current_structure = None
     self.set_animated_movie_options(animated_movie_options=animated_movie_options)
示例#23
0
 def add_actors(self, list_of_actors, label=False):
     for actor in list_of_actors:
         self.ren.AddActor(actor)
         if label:
             labelMapper = vtk.vtkLabeledDataMapper()
             labelMapper.SetInput(actor.polydata)
             labelActor = vtk.vtkActor2D()
             labelActor.SetMapper(labelMapper)
             self.ren.AddActor(labelActor)
def render_image(png_reader):
    square = 8
    color_map = vtk.vtkLookupTable()
    color_map.SetNumberOfColors(16)
    color_map.SetHueRange(0, 0.667)

    magnitude = vtk.vtkImageMagnitude()
    magnitude.SetInput(png_reader.GetOutput())

    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInput(magnitude.GetOutput())

    warp = vtk.vtkWarpScalar()
    warp.SetInput(geometry.GetOutput())
    warp.SetScaleFactor(0.25)

    merge = vtk.vtkMergeFilter()
    merge.SetGeometry(warp.GetOutput())
    merge.SetScalars(png_reader.GetOutput())

    elevation_mtHood = vtk.vtkElevationFilter()
    elevation_mtHood.SetInput(merge.GetOutput())
    elevation_mtHood.SetLowPoint(0, 0, 0)
    elevation_mtHood.SetHighPoint(0, 0, 50)

    mapper_3D_mtHood = vtk.vtkDataSetMapper()
    mapper_3D_mtHood.SetInput(elevation_mtHood.GetOutput())
    mapper_3D_mtHood.SetLookupTable(color_map)

    mapper_2D_mtHood = vtk.vtkPolyDataMapper2D()
    mapper_2D_mtHood.SetInput(elevation_mtHood.GetOutput())
    mapper_2D_mtHood.SetLookupTable(color_map)
    
    actor_2D_mtHood = vtk.vtkActor2D()
    actor_2D_mtHood.SetMapper(mapper_2D_mtHood)
    actor_2D_mtHood.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
    actor_2D_mtHood.GetPositionCoordinate().SetValue(0.25,0.25)
    
    actor_3D_mtHood = vtk.vtkActor()
    actor_3D_mtHood.SetMapper(mapper_3D_mtHood)


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

    renderer.AddActor(actor_3D_mtHood)
    renderer.SetBackground(.5, .5, .5)

    renderWindow.SetSize(600, 600)
    renderWindow.Render()
    renderWindowInteractor.Start()
示例#25
0
 def __init__(self, id):
     # Create text mapper and 2d actor to display finger position.
     self.textMapper = vtk.vtkTextMapper()
     self.textMapper.SetInput(id)  
     self.tprop = self.textMapper.GetTextProperty()
     self.tprop.SetFontFamilyToArial()
     self.tprop.SetFontSize(30)
     self.tprop.BoldOn()
     self.tprop.ShadowOn()
     self.tprop.SetColor(1, 0, 0)
     self.textActor = vtk.vtkActor2D()
     self.textActor.VisibilityOff()
     self.textActor.SetMapper(self.textMapper)
示例#26
0
    def GetRepresentation(self, x, y, z):
        pc = self.camera.GetPosition() # camera position
        pf = self.camera.GetFocalPoint() # focal position
        pp = (x, y, z) # point where the user clicked

        # Vector from camera position to user clicked point
        vcp = [j-i for i,j in zip(pc, pp)]
        # Vector from camera position to camera focal point
        vcf = [j-i for i,j in zip(pc, pf)]
        # the vector where the perpendicular vector will be given
        n = [0,0,0]
        # The cross, or vectorial product, give a vector perpendicular to vcp
        # and vcf, in this case this vector will be in horizontal, this vector
        # will be stored in the variable "n"
        vtk.vtkMath.Cross(vcp, vcf, n)
        # then normalize n to only indicate the direction of this vector
        vtk.vtkMath.Normalize(n)
        # then
        p1 = [i*self.size + j for i,j in zip(n, pp)]
        p2 = [i*-self.size + j for i,j in zip(n, pp)]

        sh = vtk.vtkLineSource()
        sh.SetPoint1(p1)
        sh.SetPoint2(p2)

        n = [0,0,0]
        vcn = [j-i for i,j in zip(p1, pc)]
        vtk.vtkMath.Cross(vcp, vcn, n)
        vtk.vtkMath.Normalize(n)
        p3 = [i*self.size + j for i,j in zip(n, pp)]
        p4 = [i*-self.size +j for i,j in zip(n, pp)]

        sv = vtk.vtkLineSource()
        sv.SetPoint1(p3)
        sv.SetPoint2(p4)

        cruz = vtk.vtkAppendPolyData()
        cruz.AddInput(sv.GetOutput())
        cruz.AddInput(sh.GetOutput())

        c = vtk.vtkCoordinate()
        c.SetCoordinateSystemToWorld()

        m = vtk.vtkPolyDataMapper2D()
        m.SetInputConnection(cruz.GetOutputPort())
        m.SetTransformCoordinate(c)

        a = vtk.vtkActor2D()
        a.SetMapper(m)
        a.GetProperty().SetColor(self.colour)
        return a
示例#27
0
def CreateAxisTickActor(xstart,ystart,xend,yend,colorfg) :
	line=vtk.vtkLineSource()
	line.SetPoint1(xstart,ystart,0.0)
	line.SetPoint2(xend,yend,0.0)
	coords = vtk.vtkCoordinate()
	coords.SetCoordinateSystemToNormalizedViewport()
	linemapper = vtk.vtkPolyDataMapper2D()
	linemapper.SetInputConnection(line.GetOutputPort())
	linemapper.SetTransformCoordinate(coords)
	tick = vtk.vtkActor2D()
	tick.SetMapper(linemapper)
	tick.GetProperty().SetLineWidth(1)
	tick.GetProperty().SetColor(colorfg)
	tick.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
	return tick 
def render_image(pointset):
    '''
    square = 10
    color_map = vtk.vtkLookupTable()
    color_map.SetNumberOfColors(square * square)
    color_map.SetTableRange(0, square * square - 1)
    for ii in range(0, square):
        for jj in range(0, square):
            color_map.SetTableValue(ii, jj / square, jj / square, ii /square)
    '''

    color_map = vtk.vtkLookupTable()
    color_map.SetNumberOfColors(16)
    color_map.SetHueRange(0, 0.667)

    delaunay = vtk.vtkDelaunay2D()
    delaunay.SetTolerance(0.001)
    delaunay.SetAlpha(18)
    delaunay.SetInput(pointset);
    delaunay.Update();

    elevation_thorax = vtk.vtkElevationFilter()
    elevation_thorax.SetInput(delaunay.GetOutput())
    elevation_thorax.SetLowPoint(0, 0, -25)
    elevation_thorax.SetHighPoint(0, 0, 25)

 
    meshMapper = vtk.vtkPolyDataMapper2D()
    meshMapper.SetInput(elevation_thorax.GetOutput())
    meshMapper.SetLookupTable(color_map)
    #meshMapper.SetScalarRange(0,255)
 
    meshActor = vtk.vtkActor2D()
    meshActor.SetMapper(meshMapper)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderer.AddActor(meshActor)
    #renderer.AddActor(boundaryActor)
    renderer.SetBackground(.5, .5, .5)

    renderWindow.SetSize(600, 600) 
    renderWindow.Render()
    renderWindowInteractor.Start()
示例#29
0
 def display_warning(self, warning):
     self.warningtxt_mapper = vtk.vtkTextMapper()
     tprops = self.warningtxt_mapper.GetTextProperty()
     tprops.SetFontSize(14)
     tprops.SetFontFamilyToTimes()
     tprops.SetColor(1, 0, 0)
     tprops.BoldOn()
     tprops.SetJustificationToRight()
     self.warningtxt = "WARNING : {}".format(warning)
     self.warningtxt_actor = vtk.vtkActor2D()
     self.warningtxt_actor.VisibilityOn()
     self.warningtxt_actor.SetMapper(self.warningtxt_mapper)
     self.ren.AddActor(self.warningtxt_actor)
     self.warningtxt_mapper.SetInput(self.warningtxt)
     winsize = self.ren_win.GetSize()
     self.warningtxt_actor.SetPosition(winsize[0]-10, 10)
     self.warningtxt_actor.VisibilityOn()
示例#30
0
 def display_info(self, info):
     self.infotxt_mapper = vtk.vtkTextMapper()
     tprops = self.infotxt_mapper.GetTextProperty()
     tprops.SetFontSize(14)
     tprops.SetFontFamilyToTimes()
     tprops.SetColor(0, 0, 1)
     tprops.BoldOn()
     tprops.SetVerticalJustificationToTop()
     self.infotxt = "INFO : {}".format(info)
     self.infotxt_actor = vtk.vtkActor2D()
     self.infotxt_actor.VisibilityOn()
     self.infotxt_actor.SetMapper(self.infotxt_mapper)
     self.ren.AddActor(self.infotxt_actor)
     self.infotxt_mapper.SetInput(self.infotxt)
     winsize = self.ren_win.GetSize()
     self.infotxt_actor.SetPosition(10, winsize[1]-10)
     self.infotxt_actor.VisibilityOn()
def MakeLabel(textLabel, renWinSize):
    """
    Create a label.

    :param textLabel: The label.
    :param renWinSize: The size of the render window. Used to set the font size.

    :return: The actor for the text label.
    """
    # Create one text property for all
    textProperty = vtk.vtkTextProperty()
    textProperty.SetJustificationToCentered()
    textProperty.SetFontSize(int(renWinSize / 20))

    mapper = vtk.vtkTextMapper()
    mapper.SetInput(textLabel)
    mapper.SetTextProperty(textProperty)

    actor = vtk.vtkActor2D()
    actor.SetMapper(mapper)
    actor.SetPosition(renWinSize / 2.0, 16)
    actor.GetProperty().SetColor(nc.GetColor3d("Gold"))
    return actor
    def __init__(self, sliceWidget):
        super(RectangleEffectTool, self).__init__(sliceWidget)

        # create a logic instance to do the non-gui work
        self.logic = RectangleEffectLogic(self.sliceWidget.sliceLogic())

        # interaction state variables
        self.actionState = None
        self.startXYPosition = None
        self.currentXYPosition = None

        # initialization
        self.createGlyph()

        self.mapper = vtk.vtkPolyDataMapper2D()
        self.actor = vtk.vtkActor2D()
        self.mapper.SetInputData(self.polyData)
        self.actor.SetMapper(self.mapper)
        property_ = self.actor.GetProperty()
        property_.SetColor(1, 1, 0)
        property_.SetLineWidth(1)
        self.renderer.AddActor2D(self.actor)
        self.actors.append(self.actor)
示例#33
0
def text(text,
         font_size=10,
         position=(0, 0),
         color=(0, 0, 0),
         is_visible=True):
    """ Generate a 2d text actor.
    """
    mapper = vtk.vtkTextMapper()
    mapper.SetInput(text)
    properties = mapper.GetTextProperty()
    properties.SetFontFamilyToArial()
    properties.SetFontSize(font_size)
    properties.BoldOn()
    properties.ShadowOn()
    properties.SetColor(color)

    actor = vtk.vtkActor2D()
    actor.SetPosition(position)
    if not is_visible:
        actor.VisibilityOff()
    actor.SetMapper(mapper)

    return actor
示例#34
0
    def add_border(self, color=[1, 1, 1], width=2.0):
        points = np.array([[1., 1., 0.], [0., 1., 0.], [0., 0., 0.],
                           [1., 0., 0.]])

        lines = np.array([[2, 0, 1], [2, 1, 2], [2, 2, 3], [2, 3, 0]]).ravel()

        poly = pyvista.PolyData()
        poly.points = points
        poly.lines = lines

        coordinate = vtk.vtkCoordinate()
        coordinate.SetCoordinateSystemToNormalizedViewport()

        mapper = vtk.vtkPolyDataMapper2D()
        mapper.SetInputData(poly)
        mapper.SetTransformCoordinate(coordinate)

        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(parse_color(color))
        actor.GetProperty().SetLineWidth(width)

        self.add_actor(actor)
示例#35
0
def addFrame(c=None, alpha=0.5, bg=None, lw=0.5):

    if c is None:  # automatic black or white
        c = (0.9, 0.9, 0.9)
        if numpy.sum(settings.plotter_instance.renderer.GetBackground()) > 1.5:
            c = (0.1, 0.1, 0.1)
    c = colors.getColor(c)

    ppoints = vtk.vtkPoints()  # Generate the polyline
    psqr = [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]
    for i, pt in enumerate(psqr):
        ppoints.InsertPoint(i, pt[0], pt[1], 0)
    lines = vtk.vtkCellArray()
    lines.InsertNextCell(len(psqr))
    for i in range(len(psqr)):
        lines.InsertCellPoint(i)
    pd = vtk.vtkPolyData()
    pd.SetPoints(ppoints)
    pd.SetLines(lines)

    mapper = vtk.vtkPolyDataMapper2D()
    mapper.SetInputData(pd)
    cs = vtk.vtkCoordinate()
    cs.SetCoordinateSystemToNormalizedViewport()
    mapper.SetTransformCoordinate(cs)

    fractor = vtk.vtkActor2D()
    fractor.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
    fractor.GetPosition2Coordinate().SetCoordinateSystemToNormalizedViewport()
    fractor.GetPositionCoordinate().SetValue(0, 0)
    fractor.GetPosition2Coordinate().SetValue(1, 1)
    fractor.SetMapper(mapper)
    fractor.GetProperty().SetColor(c)
    fractor.GetProperty().SetOpacity(alpha)
    fractor.GetProperty().SetLineWidth(lw)

    settings.plotter_instance.renderer.AddActor(fractor)
    def __init__(self, curveNode, sliceNode):
        VTKObservationMixin.__init__(self)

        self.glyphScale = 0.5

        self.intersectionPoints_XY = vtk.vtkPolyData()

        self.glyphSource = slicer.vtkMarkupsGlyphSource2D()
        self.glyphSource.SetGlyphType(
            slicer.vtkMarkupsGlyphSource2D.GlyphCrossDot)

        self.glypher = vtk.vtkGlyph2D()
        self.glypher.SetInputData(self.intersectionPoints_XY)
        self.glypher.SetScaleFactor(1.0)
        self.glypher.SetSourceConnection(self.glyphSource.GetOutputPort())

        self.mapper = vtk.vtkPolyDataMapper2D()
        self.mapper.SetInputConnection(self.glypher.GetOutputPort())
        self.mapper.ScalarVisibilityOff()
        mapperCoordinate = vtk.vtkCoordinate()
        mapperCoordinate.SetCoordinateSystemToDisplay()
        self.mapper.SetTransformCoordinate(mapperCoordinate)

        self.property = vtk.vtkProperty2D()
        self.property.SetColor(0.4, 1.0, 1.0)
        self.property.SetPointSize(3.)
        self.property.SetLineWidth(3.)
        self.property.SetOpacity(1.)

        self.actor = vtk.vtkActor2D()
        self.actor.SetMapper(self.mapper)
        self.actor.SetProperty(self.property)

        self.curveNode = curveNode
        self.sliceNode = sliceNode

        self.visibility = True
示例#37
0
    def __init__(self, sliceWidget):

        # keep a flag since events such as sliceNode modified
        # may come during superclass construction, which will
        # invoke our processEvents method
        self.initialized = False

        super(DrawEffectTool, self).__init__(sliceWidget)

        # create a logic instance to do the non-gui work
        self.logic = DrawEffectLogic(self.sliceWidget.sliceLogic())

        # interaction state variables
        self.activeSlice = None
        self.lastInsertSLiceNodeMTime = None
        self.actionState = None

        # initialization
        self.xyPoints = vtk.vtkPoints()
        self.rasPoints = vtk.vtkPoints()
        self.polyData = self.createPolyData()

        self.mapper = vtk.vtkPolyDataMapper2D()
        self.actor = vtk.vtkActor2D()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.mapper.SetInput(self.polyData)
        else:
            self.mapper.SetInputData(self.polyData)
        self.actor.SetMapper(self.mapper)
        property_ = self.actor.GetProperty()
        property_.SetColor(1, 1, 0)
        property_.SetLineWidth(1)
        self.renderer.AddActor2D(self.actor)
        self.actors.append(self.actor)

        self.initialized = True
示例#38
0
    def __init__(self):

        property = vtk.vtkTextProperty()
        property.SetFontSize(const.TEXT_SIZE)
        property.SetFontFamilyToArial()
        property.BoldOff()
        property.ItalicOff()
        property.ShadowOn()
        property.SetJustificationToLeft()
        property.SetVerticalJustificationToTop()
        property.SetColor(const.TEXT_COLOUR)
        self.property = property

        mapper = vtk.vtkTextMapper()
        mapper.SetTextProperty(property)
        self.mapper = mapper

        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
        actor.PickableOff()
        self.actor = actor

        self.SetPosition(const.TEXT_POS_LEFT_UP)
示例#39
0
    def Execute(self):
 
        if not self.Network:
            self.Network = vtk.vtkPolyData()
            networkPoints = vtk.vtkPoints()
            networkLines = vtk.vtkCellArray()
            radiusArray = vtk.vtkDoubleArray()
            radiusArray.SetName(self.RadiusArrayName)
            self.Network.SetPoints(networkPoints)
            self.Network.SetLines(networkLines)
            self.Network.GetPointData().AddArray(radiusArray)
        
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.ExitAfterTextInputMode = False
        self.vmtkRenderer.RegisterScript(self) 

        if self.Image and (not self.PlaneWidgetX or not self.PlaneWidgetY or not self.PlaneWidgetZ):
            imageViewer = vmtkimageviewer.vmtkImageViewer()
            imageViewer.Image = self.Image
            imageViewer.vmtkRenderer = self.vmtkRenderer
            imageViewer.Display = 0
            imageViewer.Execute()
            self.PlaneWidgetX = imageViewer.PlaneWidgetX
            self.PlaneWidgetY = imageViewer.PlaneWidgetY
            self.PlaneWidgetZ = imageViewer.PlaneWidgetZ

        if self.Image:
            spacing = self.Image.GetSpacing()
            self.CurrentRadius = min(spacing)

        if self.UseActiveTubes and not self.FeatureImage:
            imageFeatures = vmtkimagefeatures.vmtkImageFeatures()
            imageFeatures.Image = self.Image
            imageFeatures.FeatureImageType = 'vtkgradient'
            imageFeatures.Execute()
            self.FeatureImage = imageFeatures.FeatureImage
 
        self.NetworkRadiusArray = self.Network.GetPointData().GetArray(self.RadiusArrayName)

        self.Network.GetPointData().SetActiveScalars(self.RadiusArrayName)

        networkMapper = vtk.vtkPolyDataMapper()
        networkMapper.SetInputData(self.Network)
        networkMapper.SetScalarModeToUseCellData()

        self.NetworkActor = vtk.vtkActor()
        self.NetworkActor.SetMapper(networkMapper)
        self.vmtkRenderer.Renderer.AddActor(self.NetworkActor)

        self.NetworkTube = vtk.vtkTubeFilter()
        self.NetworkTube.SetInputData(self.Network)
        self.NetworkTube.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
        self.NetworkTube.SetNumberOfSides(20)
        networkTubeMapper = vtk.vtkPolyDataMapper()
        networkTubeMapper.SetInputConnection(self.NetworkTube.GetOutputPort())
        networkTubeMapper.ScalarVisibilityOff()
        networkTubeActor = vtk.vtkActor()
        networkTubeActor.SetMapper(networkTubeMapper)
        networkTubeActor.PickableOff()
        networkTubeActor.GetProperty().SetOpacity(0.2)
        self.vmtkRenderer.Renderer.AddActor(networkTubeActor)

        self.Selection = vtk.vtkPolyData()
        self.SelectionPoints = vtk.vtkPoints()
        self.SelectionRadiusArray = vtk.vtkDoubleArray()
        self.SelectionRadiusArray.SetName(self.RadiusArrayName)
        self.Selection.SetPoints(self.SelectionPoints)
        self.Selection.GetPointData().AddArray(self.SelectionRadiusArray)
        self.Selection.GetPointData().SetActiveScalars(self.RadiusArrayName)

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphSource.SetRadius(1.0)
        glyphSource.SetThetaResolution(20)
        glyphSource.SetPhiResolution(20)
        glyphs.SetInputData(self.Selection)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToScaleByScalar()
        glyphs.SetScaleFactor(1.0)

        selectionMapper = vtk.vtkPolyDataMapper()
        selectionMapper.SetInputConnection(glyphs.GetOutputPort())

        self.SelectionActor = vtk.vtkActor()
        self.SelectionActor.SetMapper(selectionMapper)
        self.SelectionActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SelectionActor.GetProperty().SetOpacity(0.5)
        self.SelectionActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SelectionActor)

        self.ActiveSegmentSeeds = vtk.vtkPolyData()
        self.ActiveSegmentSeedsPoints = vtk.vtkPoints()
        self.ActiveSegmentSeedsRadiusArray = vtk.vtkDoubleArray()
        self.ActiveSegmentSeedsRadiusArray.SetName(self.RadiusArrayName)
        self.ActiveSegmentSeeds.SetPoints(self.ActiveSegmentSeedsPoints)
        self.ActiveSegmentSeeds.GetPointData().AddArray(self.ActiveSegmentSeedsRadiusArray)
        self.ActiveSegmentSeeds.GetPointData().SetActiveScalars(self.RadiusArrayName)

        activeSegmentSeedsGlyphs = vtk.vtkGlyph3D()
        activeSegmentSeedsGlyphSource = vtk.vtkSphereSource()
        activeSegmentSeedsGlyphSource.SetRadius(1.0)
        activeSegmentSeedsGlyphSource.SetThetaResolution(20)
        activeSegmentSeedsGlyphSource.SetPhiResolution(20)
        activeSegmentSeedsGlyphs.SetInputData(self.ActiveSegmentSeeds)
        activeSegmentSeedsGlyphs.SetSourceConnection(activeSegmentSeedsGlyphSource.GetOutputPort())
        activeSegmentSeedsGlyphs.SetScaleModeToScaleByScalar()
        activeSegmentSeedsGlyphs.SetScaleFactor(1.0)

        activeSegmentSeedsMapper = vtk.vtkPolyDataMapper()
        activeSegmentSeedsMapper.SetInputConnection(activeSegmentSeedsGlyphs.GetOutputPort())
        activeSegmentSeedsMapper.ScalarVisibilityOff()

        self.ActiveSegmentSeedsActor = vtk.vtkActor()
        self.ActiveSegmentSeedsActor.SetMapper(activeSegmentSeedsMapper)
        self.ActiveSegmentSeedsActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.ActiveSegmentSeedsActor.GetProperty().SetOpacity(0.5)
        self.ActiveSegmentSeedsActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.ActiveSegmentSeedsActor)

        self.ActiveSegment = vtk.vtkPolyData()
        self.ActiveSegmentPoints = vtk.vtkPoints()
        self.ActiveSegmentCellArray = vtk.vtkCellArray()
        self.ActiveSegmentRadiusArray = vtk.vtkDoubleArray()
        self.ActiveSegmentRadiusArray.SetName(self.RadiusArrayName)
        self.ActiveSegment.SetPoints(self.ActiveSegmentPoints)
        self.ActiveSegment.SetLines(self.ActiveSegmentCellArray)
        self.ActiveSegment.GetPointData().AddArray(self.ActiveSegmentRadiusArray)
        self.ActiveSegment.GetPointData().SetActiveScalars(self.RadiusArrayName)

        activeSegmentMapper = vtk.vtkPolyDataMapper()
        activeSegmentMapper.ScalarVisibilityOff()
        if self.SplineInterpolation and self.Image != None:
            splineFilter = vtk.vtkSplineFilter()
            splineFilter.SetInputData(self.ActiveSegment)
            splineFilter.SetSubdivideToLength()
            splineFilter.SetLength(2.0*min(self.Image.GetSpacing()))
            activeSegmentMapper.SetInputConnection(splineFilter.GetOutputPort())
        else:
            activeSegmentMapper.SetInputData(self.ActiveSegment)

        self.ActiveSegmentActor = vtk.vtkActor()
        self.ActiveSegmentActor.SetMapper(activeSegmentMapper)
        self.ActiveSegmentActor.GetProperty().SetColor(1.0,1.0,1.0)
        self.ActiveSegmentActor.GetProperty().SetLineWidth(3.0)
        self.ActiveSegmentActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.ActiveSegmentActor)

        activeTube = vtk.vtkTubeFilter()
        activeTube.SetInputConnection(activeSegmentMapper.GetInputPort())
        activeTube.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
        activeTube.SetNumberOfSides(20)
        activeTubeMapper = vtk.vtkPolyDataMapper()
        activeTubeMapper.SetInputConnection(activeTube.GetOutputPort())
        activeTubeMapper.ScalarVisibilityOff()
        activeTubeActor = vtk.vtkActor()
        activeTubeActor.SetMapper(activeTubeMapper)
        activeTubeActor.PickableOff()
        activeTubeActor.GetProperty().SetOpacity(0.6)
        self.vmtkRenderer.Renderer.AddActor(activeTubeActor)

        self.NetworkLabelsArray = vtk.vtkStringArray.SafeDownCast(self.Network.GetCellData().GetAbstractArray(self.LabelsArrayName))
        if not self.NetworkLabelsArray:
            self.NetworkLabelsArray = vtk.vtkStringArray()
            self.NetworkLabelsArray.SetName(self.LabelsArrayName)
            self.NetworkLabelsArray.SetNumberOfValues(self.Network.GetNumberOfCells())
            for i in range(self.Network.GetNumberOfCells()):
                self.NetworkLabelsArray.SetValue(i,'')
            self.Network.GetCellData().AddArray(self.NetworkLabelsArray)
        self.CellCenters = vtk.vtkCellCenters()
        self.CellCenters.SetInputData(self.Network)
        self.CellCenters.VertexCellsOff()
        self.CellCenters.Update()

        labeledMapper = vtk.vtkLabeledDataMapper()
        labeledMapper.SetInputConnection(self.CellCenters.GetOutputPort())
        labeledMapper.SetLabelModeToLabelFieldData()
        labeledMapper.SetFieldDataName(self.LabelsArrayName)
        labeledMapper.GetLabelTextProperty().SetFontFamilyToArial()
        labeledMapper.GetLabelTextProperty().BoldOff()
        labeledMapper.GetLabelTextProperty().ItalicOff()
        labeledMapper.GetLabelTextProperty().ShadowOff()
        
        self.LabelsActor = vtk.vtkActor2D()
        self.LabelsActor.SetMapper(labeledMapper)
        self.LabelsActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.LabelsActor)

        self.CellPicker = vtk.vtkCellPicker()
        self.CellPicker.SetTolerance(1E-2)
        self.CellPicker.InitializePickList()
        self.CellPicker.AddPickList(self.NetworkActor)
        self.CellPicker.PickFromListOn()

        self.vmtkRenderer.AddKeyBinding('a','Add mode.',self.AddCallback)
        self.vmtkRenderer.AddKeyBinding('d','Delete mode.',self.DeleteCallback)
        self.vmtkRenderer.AddKeyBinding('m','Merge mode.',self.MergeCallback)
        self.vmtkRenderer.AddKeyBinding('s','Split mode.',self.SplitCallback)
        self.vmtkRenderer.AddKeyBinding('l','Label mode.',self.LabelCallback)
        self.vmtkRenderer.AddKeyBinding('Tab','Show labels.',self.ShowLabelCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyReleaseEvent", self.KeyReleaseCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("MouseMoveEvent", self.MouseMoveCallback)

        if self.PlaneWidgetX:
            self.PlaneWidgetX.UseContinuousCursorOn()
            self.PlaneWidgetX.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)
        if self.PlaneWidgetY:
            self.PlaneWidgetY.UseContinuousCursorOn()
            self.PlaneWidgetY.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)
        if self.PlaneWidgetZ:
            self.PlaneWidgetZ.UseContinuousCursorOn()
            self.PlaneWidgetZ.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)

        self.FirstRender()

        self.Surface = self.NetworkTube.GetOutput()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
示例#40
0
 def _setup(self):
     self.actor = vtk.vtkActor2D()
示例#41
0
    def testWipe(self):

        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        image1 = vtk.vtkImageCanvasSource2D()
        image1.SetNumberOfScalarComponents(3)
        image1.SetScalarTypeToUnsignedChar()
        image1.SetExtent(0, 79, 0, 79, 0, 0)
        image1.SetDrawColor(255, 255, 0)
        image1.FillBox(0, 79, 0, 79)
        image1.Update()

        image2 = vtk.vtkImageCanvasSource2D()
        image2.SetNumberOfScalarComponents(3)
        image2.SetScalarTypeToUnsignedChar()
        image2.SetExtent(0, 79, 0, 79, 0, 0)
        image2.SetDrawColor(0, 255, 255)
        image2.FillBox(0, 79, 0, 79)
        image2.Update()

        mapper = vtk.vtkImageMapper()
        mapper.SetInputConnection(image1.GetOutputPort())
        mapper.SetColorWindow(255)
        mapper.SetColorLevel(127.5)
        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        imager = vtk.vtkRenderer()
        imager.AddActor2D(actor)

        renWin.AddRenderer(imager)

        wipes = ["Quad", "Horizontal", "Vertical", "LowerLeft", "LowerRight", "UpperLeft", "UpperRight"]

        wiper = dict()
        mapper = dict()
        actor = dict()
        imagers = dict()

        for wipe in wipes:
            wiper.update({wipe:vtk.vtkImageRectilinearWipe()})
            wiper[wipe].SetInput1Data(image1.GetOutput())
            wiper[wipe].SetInput2Data(image2.GetOutput())
            wiper[wipe].SetPosition(20, 20)
            eval('wiper[wipe].SetWipeTo' + wipe + '()')

            mapper.update({wipe:vtk.vtkImageMapper()})
            mapper[wipe].SetInputConnection(wiper[wipe].GetOutputPort())
            mapper[wipe].SetColorWindow(255)
            mapper[wipe].SetColorLevel(127.5)

            actor.update({wipe:vtk.vtkActor2D()})
            actor[wipe].SetMapper(mapper[wipe])

            imagers.update({wipe:vtk.vtkRenderer()})
            imagers[wipe].AddActor2D(actor[wipe])

            renWin.AddRenderer(imagers[wipe])

        imagers["Quad"].SetViewport(0, .5, .25, 1)
        imagers["Horizontal"].SetViewport(.25, .5, .5, 1)
        imagers["Vertical"].SetViewport(.5, .5, .75, 1)
        imagers["LowerLeft"].SetViewport(.75, .5, 1, 1)
        imagers["LowerRight"].SetViewport(0, 0, .25, .5)
        imagers["UpperLeft"].SetViewport(.25, 0, .5, .5)
        imagers["UpperRight"].SetViewport(.5, 0, .75, .5)
        imager.SetViewport(.75, 0, 1, .5)

        renWin.SetSize(400, 200)

        # render and interact with data

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

        img_file = "TestWipe.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
    def testFreetypeTextMapperBigger(self):

        currentFontSize = 55
        defaultText = "MmNnKk @"
        textColor = [246, 255, 11]
        bgColor = [56, 56, 154]
        for i in range(0, len(textColor)):
            textColor[i] /= 255.0
            bgColor[i] /= 255.0

        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(790, 450)

        ren = vtk.vtkRenderer()
        ren.SetBackground(bgColor)
        renWin.AddRenderer(ren)

        families = ["Arial", "Courier", "Times"]
        attributes = [[0, 0], [1, 1]]  # bold, italic

        def SetAttributesText(attrib):
            """ Expects a list of attributes of size 2, returns a string  """
            s = ""
            if attrib[0] != 0:
                s += "b"
            if attrib[1] != 0:
                s += "i"
            return ','.join(list(s))

        mapper = dict()
        actor = dict()

        pos = 0
        for i, family in enumerate(families):
            for j, attrib in enumerate(attributes):
                pos += 1
                txt = ""
                txtAttrib = SetAttributesText(attrib)
                if len(txtAttrib) != 0:
                    txt = family + " (" + SetAttributesText(
                        attrib) + "): " + defaultText
                else:
                    txt = family + ": " + defaultText

                idx = ''.join(map(str, [i, j]))
                mapper.update({idx: vtk.vtkTextMapper()})
                mapper[idx].SetInput(txt)

                tprop = mapper[idx].GetTextProperty()
                eval('tprop.SetFontFamilyTo' + family + '()')
                tprop.SetColor(textColor)
                tprop.SetBold(attrib[0])
                tprop.SetItalic(attrib[1])
                tprop.SetFontSize(currentFontSize)

                actor.update({idx: vtk.vtkActor2D()})
                actor[idx].SetMapper(mapper[idx])
                actor[idx].SetDisplayPosition(10, pos * (currentFontSize + 5))

                ren.AddActor(actor[idx])

        # render and interact with data

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

        renWin.Render()
示例#43
0
def viewportBorder(renderer, last, color=None):
    '''
    renderer:vtkRenderer
    last:boool
    color:array [0] * 3
    '''
    # points start at upper right and proceed anti-clockwise
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(4)
    points.InsertPoint(0, 1, 1, 0)
    points.InsertPoint(1, 0, 1, 0)
    points.InsertPoint(2, 0, 0, 0)
    points.InsertPoint(3, 1, 0, 0)

    # create cells, and lines
    cells = vtk.vtkCellArray()
    cells.Initialize()

    lines = vtk.vtkPolyLine()

    # only draw last line if this is the last viewport
    # this prevents double vertical lines at right border
    # if different colors are used for each border, then do
    # not specify last
    if last:
        lines.GetPointIds().SetNumberOfIds(5)
    else:
        lines.GetPointIds().SetNumberOfIds(4)
    for i in range(4):
        lines.GetPointIds().SetId(i, i)
    if last:
        lines.GetPointIds().SetId(4, 0)

    cells.InsertNextCell(lines)

    # now make tge polydata and display it
    poly = vtk.vtkPolyData()
    poly.Initialize()
    poly.SetPoints(points)
    poly.SetLines(cells)

    # use normalized viewport coordinates since
    # they are independent of window size
    coordinate = vtk.vtkCoordinate()
    coordinate.SetCoordinateSystemToNormalizedViewport()

    mapper = vtk.vtkPolyDataMapper2D()
    mapper.SetInputData(poly)
    mapper.SetTransformCoordinate(coordinate)

    actor = vtk.vtkActor2D()
    actor.SetMapper(mapper)
    if color != None:
        actor.GetProperty().SetColor(color)
    else:
        actor.GetProperty().SetColor(
            vtk.vtkNamedColors().GetColor3d("SlateGray"))

    # line width should be at least 2 to be visible at extremes
    actor.GetProperty().SetLineWidth(4.0)  # Line Width

    renderer.AddViewProp(actor)
示例#44
0
def main():
    colors = vtk.vtkNamedColors()

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

    sourceObjects = list()
    sourceObjects.append(vtk.vtkSphereSource())
    sourceObjects[-1].SetPhiResolution(21)
    sourceObjects[-1].SetThetaResolution(21)

    sourceObjects.append(vtk.vtkConeSource())
    sourceObjects[-1].SetResolution(51)

    sourceObjects.append(vtk.vtkCylinderSource())
    sourceObjects[-1].SetResolution(51)

    sourceObjects.append(vtk.vtkCubeSource())
    sourceObjects.append(vtk.vtkPlaneSource())
    sourceObjects.append(vtk.vtkTextSource())
    sourceObjects[-1].SetText("Hello")
    sourceObjects[-1].BackingOff()

    sourceObjects.append(vtk.vtkPointSource())
    sourceObjects[-1].SetNumberOfPoints(500)

    sourceObjects.append(vtk.vtkDiskSource())
    sourceObjects[-1].SetCircumferentialResolution(51)

    sourceObjects.append(vtk.vtkLineSource())

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

    # Create one text property for all.
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(16)
    textProperty.SetJustificationToCentered()

    backProperty = vtk.vtkProperty()
    backProperty.SetColor(colors.GetColor3d("Red"))

    # Create a source, renderer, mapper, and actor
    # for each object.
    for i in range(0, len(sourceObjects)):
        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(sourceObjects[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d("Seashell"))
        actors[i].SetBackfaceProperty(backProperty)

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(sourceObjects[i].GetClassName())
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(120, 16)
        renderers.append(vtk.vtkRenderer())

    gridDimensions = 3

    # We need a renderer even if there is no actor.
    for i in range(len(sourceObjects), gridDimensions ** 2):
        renderers.append(vtk.vtkRenderer())

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Source Objects Demo")
    rendererSize = 300
    renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)

    for row in range(0, gridDimensions):
        for col in range(0, gridDimensions):
            index = row * gridDimensions + col
            x0 = float(col) / gridDimensions
            y0 = float(gridDimensions - row - 1) / gridDimensions
            x1 = float(col + 1) / gridDimensions
            y1 = float(gridDimensions - row) / gridDimensions
            renderWindow.AddRenderer(renderers[index])
            renderers[index].SetViewport(x0, y0, x1, y1)

            if index > (len(sourceObjects) - 1):
                continue

            renderers[index].AddActor(actors[index])
            renderers[index].AddActor(textactors[index])
            renderers[index].SetBackground(colors.GetColor3d("BkgColor"))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(30)
            renderers[index].GetActiveCamera().Zoom(0.8)
            renderers[index].ResetCameraClippingRange()

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

    renderWindow.Render()
    interactor.Start()
示例#45
0
def main():
    colors = vtk.vtkNamedColors()

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

    # Create container to hold the 3D object generators (sources)
    geometricObjectSources = list()

    # Populate the container with the various object sources to be demonstrated
    geometricObjectSources.append(vtk.vtkArrowSource())
    geometricObjectSources.append(vtk.vtkConeSource())
    geometricObjectSources.append(vtk.vtkCubeSource())
    geometricObjectSources.append(vtk.vtkCylinderSource())
    geometricObjectSources.append(vtk.vtkDiskSource())
    geometricObjectSources.append(vtk.vtkLineSource())
    geometricObjectSources.append(vtk.vtkRegularPolygonSource())
    geometricObjectSources.append(vtk.vtkSphereSource())

    # Create containers for the remaining nodes of each pipeline
    mappers = list()
    actors = list()
    textmappers = list()
    textactors = list()

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

    # Create a mapper and actor for each object and the corresponding text label
    for i in range(0, len(geometricObjectSources)):
        geometricObjectSources[i].Update()

        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(geometricObjectSources[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(
            colors.GetColor3d("Seashell"))

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(
            geometricObjectSources[i].GetClassName())  # set text label to the name of the object source
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(120, 16)  # Note: the position of an Actor2D is specified in display coordinates

    # Define size of the grid that will hold the objects
    gridCols = 3
    gridRows = 3
    # Define side length (in pixels) of each renderer square
    rendererSize = 300

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Geometric Objects Demo")
    renderWindow.SetSize(rendererSize * gridCols, rendererSize * gridRows)

    # Set up a grid of viewports for each renderer
    for row in range(0, gridRows):
        for col in range(0, gridCols):
            index = row * gridCols + col

            # Create a renderer for this grid cell
            renderer = vtk.vtkRenderer()
            renderer.SetBackground(colors.GetColor3d("BkgColor"))

            # Set the renderer's viewport dimensions (xmin, ymin, xmax, ymax) within the render window.
            # Note that for the Y values, we need to subtract the row index from gridRows
            # because the viewport Y axis points upwards, but we want to draw the grid from top to down
            viewport = [
                float(col) / gridCols,
                float(gridRows - row - 1) / gridRows,
                float(col + 1) / gridCols,
                float(gridRows - row) / gridRows
            ]
            renderer.SetViewport(viewport)

            # Add the corresponding actor and label for this grid cell, if they exist
            if index < len(geometricObjectSources):
                renderer.AddActor(actors[index])
                renderer.AddActor(textactors[index])
                renderer.ResetCameraClippingRange()

            renderWindow.AddRenderer(renderer)

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

    renderWindow.Render()
    interactor.Start()
w2i.SetInputBufferTypeToRGBA()

# grab window
w2i.Update()

# copy the output
outputData = w2i.GetOutput().NewInstance()
outputData.DeepCopy(w2i.GetOutput())

# set up mappers and actors to display the image
im = vtk.vtkImageMapper()
im.SetColorWindow(255)
im.SetColorLevel(127.5)
im.SetInputData(outputData)

ia2 = vtk.vtkActor2D()
ia2.SetMapper(im)

# now, change the image (background is now green)
sphactor.SetScale(2, 2, 2)

ren1.SetBackground(0, 1, 0)
# add the image of the sphere (keeping the original sphere too)
ren1.AddActor(ia2)
ren1.SetViewport(0, 0, 1, 1)

# render result (the polygonal sphere appears behind a smaller image
# of itself).  Background of original image is transparent, so you
# can see through it back to the larger sphere and new background.
renWin.Render()
示例#47
0
mapper2 = vtk.vtkImageMapper()
mapper2.SetInputConnection(reslice2.GetOutputPort())
mapper2.SetColorWindow(2000)
mapper2.SetColorLevel(1000)
mapper2.SetZSlice(0)
mapper3 = vtk.vtkImageMapper()
mapper3.SetInputConnection(reslice3.GetOutputPort())
mapper3.SetColorWindow(2000)
mapper3.SetColorLevel(1000)
mapper3.SetZSlice(0)
mapper4 = vtk.vtkImageMapper()
mapper4.SetInputConnection(reslice4.GetOutputPort())
mapper4.SetColorWindow(2000)
mapper4.SetColorLevel(1000)
mapper4.SetZSlice(0)
actor1 = vtk.vtkActor2D()
actor1.SetMapper(mapper1)
actor2 = vtk.vtkActor2D()
actor2.SetMapper(mapper2)
actor3 = vtk.vtkActor2D()
actor3.SetMapper(mapper3)
actor4 = vtk.vtkActor2D()
actor4.SetMapper(mapper4)
imager1 = vtk.vtkRenderer()
imager1.AddActor2D(actor1)
imager1.SetViewport(0.5, 0.0, 1.0, 0.5)
imager2 = vtk.vtkRenderer()
imager2.AddActor2D(actor2)
imager2.SetViewport(0.0, 0.0, 0.5, 0.5)
imager3 = vtk.vtkRenderer()
imager3.AddActor2D(actor3)
示例#48
0
    def on_show(self):
        """show the highlight"""
        passed = self.on_validate()
        self.parent().mouse_actions.get_grid_selected(self.model_name)

        if passed and self.win_parent is not None:
            nodes, unused_flag1 = check_patran_syntax(self.nodes_edit,
                                                      pound=self._nodes_pound)
            elements, unused_flag2 = check_patran_syntax(
                self.elements_edit, pound=self._elements_pound)
            if len(nodes) == 0 and len(elements) == 0:
                return False
            nodes_filtered = np.intersect1d(self.nodes, nodes)
            elements_filtered = np.intersect1d(self.elements, elements)
            nnodes = len(nodes_filtered)
            nelements = len(elements_filtered)
            if nnodes == 0 and nelements == 0:
                return False
            self.on_remove_actors()

            gui = self.parent()
            mouse_actions = gui.mouse_actions
            grid = mouse_actions.get_grid_selected(self.model_name)

            actors = create_highlighted_actors(gui,
                                               grid,
                                               all_nodes=self.nodes,
                                               nodes=nodes_filtered,
                                               set_node_scalars=True,
                                               all_elements=self.elements,
                                               elements=elements_filtered,
                                               set_element_scalars=True)

            iactor = 0
            make_element_labels = True
            make_node_labels = True
            if make_node_labels and nnodes:
                mapper = actors[iactor].GetMapper()
                mygrid = mapper.GetInput()

                point_id_filter = get_ids_filter(mygrid,
                                                 idsname='Ids_points',
                                                 is_nids=True,
                                                 is_eids=False)
                point_id_filter.SetFieldData(1)
                point_id_filter.SetPointIds(0)
                point_id_filter.FieldDataOn()

                label_actor = create_node_labels(point_id_filter,
                                                 mygrid,
                                                 gui.rend,
                                                 label_size=self._label_size)
                actors.append(label_actor)
                iactor += 1

            if make_element_labels and nelements:
                mapper = actors[iactor].GetMapper()
                mygrid = mapper.GetInput()

                element_id_filter = get_ids_filter(mygrid,
                                                   idsname='Ids_cells',
                                                   is_nids=False,
                                                   is_eids=True)
                element_id_filter.SetFieldData(1)
                element_id_filter.SetCellIds(0)
                element_id_filter.FieldDataOn()

                # Create labels for cells
                cell_centers = vtk.vtkCellCenters()
                cell_centers.SetInputConnection(
                    element_id_filter.GetOutputPort())

                cell_mapper = vtk.vtkLabeledDataMapper()
                cell_mapper.SetInputConnection(cell_centers.GetOutputPort())
                cell_mapper.SetLabelModeToLabelScalars()

                label_actor = vtk.vtkActor2D()
                label_actor.SetMapper(cell_mapper)

                actors.append(label_actor)
                iactor += 1

            if actors:
                add_actors_to_gui(gui, actors, render=True)
                self.actors = actors
        return passed
示例#49
0
reader.SetFileName("" + str(fname) + "")
textProp = vtk.vtkTextProperty()
textProp.SetFontSize(12)
textProp.SetColor(1.0, 1.0, 0.5)
labelHier = vtk.vtkPointSetToLabelHierarchy()
labelHier.SetInputConnection(reader.GetOutputPort())
labelHier.SetTextProperty(textProp)
labelHier.SetLabelArrayName("LabelText")
labelHier.SetMaximumDepth(15)
labelHier.SetTargetLabelCount(12)
labelMapper = vtk.vtkLabelPlacementMapper()
labelMapper.SetInputConnection(labelHier.GetOutputPort())
labelMapper.UseDepthBufferOff()
labelMapper.SetShapeToRect()
labelMapper.SetStyleToOutline()
labelActor = vtk.vtkActor2D()
labelActor.SetMapper(labelMapper)
glyphSource = vtk.vtkSphereSource()
glyphSource.SetRadius(0.01)
glyph = vtk.vtkGlyph3D()
glyph.SetSourceConnection(glyphSource.GetOutputPort())
glyph.SetInputConnection(reader.GetOutputPort())
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(glyph.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
# Create rendering stuff
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
    def testFreetypeTextMapper(self):

        currentFontSize = 16
        defaultText = "ABCDEFGHIJKLMnopqrstuvwxyz 0123456789 !@#$%()-=_+{};:,./<>?"
        textColor = [246, 255, 11]
        bgColor = [56, 56, 154]
        for i in range(0, len(textColor)):
            textColor[i] /= 255.0
            bgColor[i] /= 255.0

        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(790, 350)

        ren = vtk.vtkRenderer()
        ren.SetBackground(bgColor)
        renWin.AddRenderer(ren)

        families = ["Arial", "Courier", "Times"]
        attributes = [[0, 0, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0],
                      [1, 1, 0]]  # bold, italic, shadow

        def SetAttributesText(attrib):
            """ Expects a list of attributes of size 3, returns a string  """
            s = ""
            if attrib[0] != 0:
                s += "b"
            if attrib[1] != 0:
                s += "i"
            if attrib[2] != 0:
                s += "s"
            return ','.join(list(s))

        mapper = dict()
        actor = dict()

        pos = 0
        for i, family in enumerate(families):
            for j, attrib in enumerate(attributes):
                pos += 1
                txt = ""
                txtAttrib = SetAttributesText(attrib)
                if len(txtAttrib) != 0:
                    txt = family + " (" + SetAttributesText(
                        attrib) + "): " + defaultText
                else:
                    txt = family + ": " + defaultText

                idx = ''.join(map(str, [i, j]))
                mapper.update({idx: vtk.vtkTextMapper()})
                mapper[idx].SetInput(txt)

                tprop = mapper[idx].GetTextProperty()
                eval('tprop.SetFontFamilyTo' + family + '()')
                tprop.SetColor(textColor)
                tprop.SetBold(attrib[0])
                tprop.SetItalic(attrib[1])
                tprop.SetShadow(attrib[2])
                tprop.SetFontSize(currentFontSize)

                actor.update({idx: vtk.vtkActor2D()})
                actor[idx].SetMapper(mapper[idx])
                actor[idx].SetDisplayPosition(10, pos * (currentFontSize + 5))

                ren.AddActor(actor[idx])

        # render and interact with data

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

        renWin.Render()

        img_file = "TestFreetypeTextMapper.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
示例#51
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()
示例#52
0
    def testParametricFunctions(self):
        # ------------------------------------------------------------
        # Get a texture
        # ------------------------------------------------------------
        textureReader = vtk.vtkJPEGReader()
        textureReader.SetFileName(VTK_DATA_ROOT + "/Data/beach.jpg")
        texture = vtk.vtkTexture()
        texture.SetInputConnection(textureReader.GetOutputPort())

        # ------------------------------------------------------------
        # For each parametric surface:
        # 1) Create it
        # 2) Assign mappers and actors
        # 3) Position the object
        # 5) Add a label
        # ------------------------------------------------------------

        # ------------------------------------------------------------
        # Create a torus
        # ------------------------------------------------------------
        torus = vtk.vtkParametricTorus()
        torusSource = vtk.vtkParametricFunctionSource()
        torusSource.SetParametricFunction(torus)
        torusSource.SetScalarModeToPhase()

        torusMapper = vtk.vtkPolyDataMapper()
        torusMapper.SetInputConnection(torusSource.GetOutputPort())
        torusMapper.SetScalarRange(0, 360)

        torusActor = vtk.vtkActor()
        torusActor.SetMapper(torusMapper)
        torusActor.SetPosition(0, 12, 0)

        torusTextMapper = vtk.vtkTextMapper()
        torusTextMapper.SetInput("Torus")
        torusTextMapper.GetTextProperty().SetJustificationToCentered()
        torusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        torusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        torusTextMapper.GetTextProperty().SetFontSize(14)
        torusTextActor = vtk.vtkActor2D()
        torusTextActor.SetMapper(torusTextMapper)
        torusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        torusTextActor.GetPositionCoordinate().SetValue(0, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Klein bottle
        # ------------------------------------------------------------
        klein = vtk.vtkParametricKlein()
        kleinSource = vtk.vtkParametricFunctionSource()
        kleinSource.SetParametricFunction(klein)
        kleinSource.SetScalarModeToU0V0()

        kleinMapper = vtk.vtkPolyDataMapper()
        kleinMapper.SetInputConnection(kleinSource.GetOutputPort())
        kleinMapper.SetScalarRange(0, 3)

        kleinActor = vtk.vtkActor()
        kleinActor.SetMapper(kleinMapper)
        kleinActor.SetPosition(8, 10.5, 0)

        kleinTextMapper = vtk.vtkTextMapper()
        kleinTextMapper.SetInput("Klein")
        kleinTextMapper.GetTextProperty().SetJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        kleinTextMapper.GetTextProperty().SetFontSize(14)
        kleinTextActor = vtk.vtkActor2D()
        kleinTextActor.SetMapper(kleinTextMapper)
        kleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        kleinTextActor.GetPositionCoordinate().SetValue(8, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Figure-8 Klein
        # ------------------------------------------------------------
        klein2 = vtk.vtkParametricFigure8Klein()
        klein2Source = vtk.vtkParametricFunctionSource()
        klein2Source.SetParametricFunction(klein2)
        klein2Source.GenerateTextureCoordinatesOn()

        klein2Mapper = vtk.vtkPolyDataMapper()
        klein2Mapper.SetInputConnection(klein2Source.GetOutputPort())
        klein2Mapper.SetScalarRange(0, 3)

        klein2Actor = vtk.vtkActor()
        klein2Actor.SetMapper(klein2Mapper)
        klein2Actor.SetPosition(16, 12, 0)
        klein2Actor.SetTexture(texture)


        fig8KleinTextMapper = vtk.vtkTextMapper()
        fig8KleinTextMapper.SetInput("Fig-8.Klein")
        fig8KleinTextMapper.GetTextProperty().SetJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        fig8KleinTextMapper.GetTextProperty().SetFontSize(14)
        fig8KleinTextActor = vtk.vtkActor2D()
        fig8KleinTextActor.SetMapper(fig8KleinTextMapper)
        fig8KleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        fig8KleinTextActor.GetPositionCoordinate().SetValue(16, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Mobius strip
        # ------------------------------------------------------------
        mobius = vtk.vtkParametricMobius()
        mobiusSource = vtk.vtkParametricFunctionSource()
        mobiusSource.SetParametricFunction(mobius)
        mobiusSource.GenerateTextureCoordinatesOn()

        mobiusMapper = vtk.vtkPolyDataMapper()
        mobiusMapper.SetInputConnection(mobiusSource.GetOutputPort())

        mobiusActor = vtk.vtkActor()
        mobiusActor.SetMapper(mobiusMapper)
        mobiusActor.RotateX(45)
        mobiusActor.SetPosition(24, 12, 0)
        mobiusActor.SetTexture(texture)

        mobiusTextMapper = vtk.vtkTextMapper()
        mobiusTextMapper.SetInput("Mobius")
        mobiusTextMapper.GetTextProperty().SetJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        mobiusTextMapper.GetTextProperty().SetFontSize(14)
        mobiusTextActor = vtk.vtkActor2D()
        mobiusTextActor.SetMapper(mobiusTextMapper)
        mobiusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        mobiusTextActor.GetPositionCoordinate().SetValue(24, 9.5, 0)

        # ------------------------------------------------------------
        # Create a super toroid
        # ------------------------------------------------------------
        toroid = vtk.vtkParametricSuperToroid()
        toroid.SetN1(2)
        toroid.SetN2(3)
        toroidSource = vtk.vtkParametricFunctionSource()
        toroidSource.SetParametricFunction(toroid)
        toroidSource.SetScalarModeToU()

        toroidMapper = vtk.vtkPolyDataMapper()
        toroidMapper.SetInputConnection(toroidSource.GetOutputPort())
        toroidMapper.SetScalarRange(0, 6.28)

        toroidActor = vtk.vtkActor()
        toroidActor.SetMapper(toroidMapper)
        toroidActor.SetPosition(0, 4, 0)

        superToroidTextMapper = vtk.vtkTextMapper()
        superToroidTextMapper.SetInput("Super.Toroid")
        superToroidTextMapper.GetTextProperty().SetJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superToroidTextMapper.GetTextProperty().SetFontSize(14)
        superToroidTextActor = vtk.vtkActor2D()
        superToroidTextActor.SetMapper(superToroidTextMapper)
        superToroidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superToroidTextActor.GetPositionCoordinate().SetValue(0, 1.5, 0)

        # ------------------------------------------------------------
        # Create a super ellipsoid
        # ------------------------------------------------------------
        superEllipsoid = vtk.vtkParametricSuperEllipsoid()
        superEllipsoid.SetXRadius(1.25)
        superEllipsoid.SetYRadius(1.5)
        superEllipsoid.SetZRadius(1.0)
        superEllipsoid.SetN1(1.1)
        superEllipsoid.SetN2(1.75)
        superEllipsoidSource = vtk.vtkParametricFunctionSource()
        superEllipsoidSource.SetParametricFunction(superEllipsoid)
        superEllipsoidSource.SetScalarModeToV()

        superEllipsoidMapper = vtk.vtkPolyDataMapper()
        superEllipsoidMapper.SetInputConnection(superEllipsoidSource.GetOutputPort())
        superEllipsoidMapper.SetScalarRange(0, 3.14)

        superEllipsoidActor = vtk.vtkActor()
        superEllipsoidActor.SetMapper(superEllipsoidMapper)
        superEllipsoidActor.SetPosition(8, 4, 0)

        superEllipsoidTextMapper = vtk.vtkTextMapper()
        superEllipsoidTextMapper.SetInput("Super.Ellipsoid")
        superEllipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superEllipsoidTextMapper.GetTextProperty().SetFontSize(14)
        superEllipsoidTextActor = vtk.vtkActor2D()
        superEllipsoidTextActor.SetMapper(superEllipsoidTextMapper)
        superEllipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superEllipsoidTextActor.GetPositionCoordinate().SetValue(8, 1.5, 0)

        # ------------------------------------------------------------
        # Create an open 1D spline
        # ------------------------------------------------------------
        splinePoints = [
          [0.50380158308139134, -0.60679315105396936, -0.37248976406291578],
          [-0.4354646054261665, -0.85362339758017258, -0.84844312996065385],
          [0.2163147512899315, -0.39797507012168643, -0.76700353518454523],
          [0.97158415334838644, -0.58513467367046257, -0.35846037946569753],
          [-0.64359767997804918, -0.94620739107309249, -0.90762176546623086],
          [-0.39901219094126117, -0.1978931497772658, 0.0098316934936828471],
          [-0.75872745167404765, 0.067719714281950116, 0.165237936733867],
          [-0.84599731389712418, -0.67685466896596114, 0.10357868909071133],
          [0.84702754758625654, -0.0080077177882230677, -0.58571286666473044],
          [-0.076150034124101484, 0.14637647622561856, 0.1494359239700418] ]
        inputPoints = vtk.vtkPoints()
        for i in range(0, 10):
            inputPoints.InsertPoint(i, splinePoints[i])

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(inputPoints)
        spline.ClosedOff()
        splineSource = vtk.vtkParametricFunctionSource()
        splineSource.SetParametricFunction(spline)

        splineMapper = vtk.vtkPolyDataMapper()
        splineMapper.SetInputConnection(splineSource.GetOutputPort())

        splineActor = vtk.vtkActor()
        splineActor.SetMapper(splineMapper)
        splineActor.SetPosition(16, 4, 0)
        splineActor.GetProperty().SetColor(0, 0, 0)

        splineTextMapper = vtk.vtkTextMapper()
        splineTextMapper.SetInput("Open.Spline")
        splineTextMapper.GetTextProperty().SetJustificationToCentered()
        splineTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        splineTextMapper.GetTextProperty().SetColor(1, 0, 0)
        splineTextMapper.GetTextProperty().SetFontSize(14)
        splineTextActor = vtk.vtkActor2D()
        splineTextActor.SetMapper(splineTextMapper)
        splineTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        splineTextActor.GetPositionCoordinate().SetValue(16, 1.5, 0)

        # ------------------------------------------------------------
        # Create a closed 1D spline
        # ------------------------------------------------------------
        spline2 = vtk.vtkParametricSpline()
        spline2.SetPoints(inputPoints)
        spline2.ClosedOn()
        spline2Source = vtk.vtkParametricFunctionSource()
        spline2Source.SetParametricFunction(spline2)

        spline2Mapper = vtk.vtkPolyDataMapper()
        spline2Mapper.SetInputConnection(spline2Source.GetOutputPort())

        spline2Actor = vtk.vtkActor()
        spline2Actor.SetMapper(spline2Mapper)
        spline2Actor.SetPosition(24, 4, 0)
        spline2Actor.GetProperty().SetColor(0, 0, 0)

        spline2TextMapper = vtk.vtkTextMapper()
        spline2TextMapper.SetInput("Closed.Spline")
        spline2TextMapper.GetTextProperty().SetJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetColor(1, 0, 0)
        spline2TextMapper.GetTextProperty().SetFontSize(14)
        spline2TextActor = vtk.vtkActor2D()
        spline2TextActor.SetMapper(spline2TextMapper)
        spline2TextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        spline2TextActor.GetPositionCoordinate().SetValue(24, 1.5, 0)

        # ------------------------------------------------------------
        # Create a spiral conic
        # ------------------------------------------------------------
        sconic = vtk.vtkParametricConicSpiral()
        sconic.SetA(0.8)
        sconic.SetB(2.5)
        sconic.SetC(0.4)
        sconicSource = vtk.vtkParametricFunctionSource()
        sconicSource.SetParametricFunction(sconic)
        sconicSource.SetScalarModeToDistance()

        sconicMapper = vtk.vtkPolyDataMapper()
        sconicMapper.SetInputConnection(sconicSource.GetOutputPort())
        sconicActor = vtk.vtkActor()
        sconicActor.SetMapper(sconicMapper)
        sconicMapper.SetScalarRange(0, 9)
        sconicActor.SetPosition(0, -4, 0)
        sconicActor.SetScale(1.2, 1.2, 1.2)

        sconicTextMapper = vtk.vtkTextMapper()
        sconicTextMapper.SetInput("Spiral.Conic")
        sconicTextMapper.GetTextProperty().SetJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetColor(1, 0, 0)
        sconicTextMapper.GetTextProperty().SetFontSize(14)
        sconicTextActor = vtk.vtkActor2D()
        sconicTextActor.SetMapper(sconicTextMapper)
        sconicTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        sconicTextActor.GetPositionCoordinate().SetValue(0, -6.5, 0)

        # ------------------------------------------------------------
        # Create Boy's surface
        # ------------------------------------------------------------
        boy = vtk.vtkParametricBoy()
        boySource = vtk.vtkParametricFunctionSource()
        boySource.SetParametricFunction(boy)
        boySource.SetScalarModeToModulus()

        boyMapper = vtk.vtkPolyDataMapper()
        boyMapper.SetInputConnection(boySource.GetOutputPort())
        boyMapper.SetScalarRange(0, 2)
        boyActor = vtk.vtkActor()
        boyActor.SetMapper(boyMapper)
        boyActor.SetPosition(8, -4, 0)
        boyActor.SetScale(1.5, 1.5, 1.5)

        boyTextMapper = vtk.vtkTextMapper()
        boyTextMapper.SetInput("Boy")
        boyTextMapper.GetTextProperty().SetJustificationToCentered()
        boyTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        boyTextMapper.GetTextProperty().SetColor(1, 0, 0)
        boyTextMapper.GetTextProperty().SetFontSize(14)
        boyTextActor = vtk.vtkActor2D()
        boyTextActor.SetMapper(boyTextMapper)
        boyTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        boyTextActor.GetPositionCoordinate().SetValue(8, -6.5, 0)

        # ------------------------------------------------------------
        # Create a cross cap
        # ------------------------------------------------------------
        crossCap = vtk.vtkParametricCrossCap()
        crossCapSource = vtk.vtkParametricFunctionSource()
        crossCapSource.SetParametricFunction(crossCap)
        crossCapSource.SetScalarModeToY()

        crossCapMapper = vtk.vtkPolyDataMapper()
        crossCapMapper.SetInputConnection(crossCapSource.GetOutputPort())
        crossCapActor = vtk.vtkActor()
        crossCapActor.SetMapper(crossCapMapper)
        crossCapActor.RotateX(65)
        crossCapActor.SetPosition(16, -4, 0)
        crossCapActor.SetScale(1.5, 1.5, 1.5)

        crossCapTextMapper = vtk.vtkTextMapper()
        crossCapTextMapper.SetInput("Cross.Cap")
        crossCapTextMapper.GetTextProperty().SetJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetColor(1, 0, 0)
        crossCapTextMapper.GetTextProperty().SetFontSize(14)
        crossCapTextActor = vtk.vtkActor2D()
        crossCapTextActor.SetMapper(crossCapTextMapper)
        crossCapTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        crossCapTextActor.GetPositionCoordinate().SetValue(16, -6.5, 0)

        # ------------------------------------------------------------
        # Create Dini's surface
        # ------------------------------------------------------------
        dini = vtk.vtkParametricDini()
        diniSource = vtk.vtkParametricFunctionSource()
        diniSource.SetScalarModeToDistance()
        diniSource.SetParametricFunction(dini)

        diniMapper = vtk.vtkPolyDataMapper()
        diniMapper.SetInputConnection(diniSource.GetOutputPort())

        diniActor = vtk.vtkActor()
        diniActor.SetMapper(diniMapper)
        diniActor.RotateX(-90)
        diniActor.SetPosition(24, -3, 0)
        diniActor.SetScale(1.5, 1.5, 0.5)

        diniTextMapper = vtk.vtkTextMapper()
        diniTextMapper.SetInput("Dini")
        diniTextMapper.GetTextProperty().SetJustificationToCentered()
        diniTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        diniTextMapper.GetTextProperty().SetColor(1, 0, 0)
        diniTextMapper.GetTextProperty().SetFontSize(14)
        diniTextActor = vtk.vtkActor2D()
        diniTextActor.SetMapper(diniTextMapper)
        diniTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        diniTextActor.GetPositionCoordinate().SetValue(24, -6.5, 0)

        # ------------------------------------------------------------
        # Create Enneper's surface
        # ------------------------------------------------------------
        enneper = vtk.vtkParametricEnneper()
        enneperSource = vtk.vtkParametricFunctionSource()
        enneperSource.SetParametricFunction(enneper)
        enneperSource.SetScalarModeToQuadrant()

        enneperMapper = vtk.vtkPolyDataMapper()
        enneperMapper.SetInputConnection(enneperSource.GetOutputPort())
        enneperMapper.SetScalarRange(1, 4)

        enneperActor = vtk.vtkActor()
        enneperActor.SetMapper(enneperMapper)
        enneperActor.SetPosition(0, -12, 0)
        enneperActor.SetScale(0.25, 0.25, 0.25)

        enneperTextMapper = vtk.vtkTextMapper()
        enneperTextMapper.SetInput("Enneper")
        enneperTextMapper.GetTextProperty().SetJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetColor(1, 0, 0)
        enneperTextMapper.GetTextProperty().SetFontSize(14)
        enneperTextActor = vtk.vtkActor2D()
        enneperTextActor.SetMapper(enneperTextMapper)
        enneperTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        enneperTextActor.GetPositionCoordinate().SetValue(0, -14.5, 0)

        # ------------------------------------------------------------
        # Create an ellipsoidal surface
        # ------------------------------------------------------------
        ellipsoid = vtk.vtkParametricEllipsoid()
        ellipsoid.SetXRadius(1)
        ellipsoid.SetYRadius(0.75)
        ellipsoid.SetZRadius(0.5)
        ellipsoidSource = vtk.vtkParametricFunctionSource()
        ellipsoidSource.SetParametricFunction(ellipsoid)
        ellipsoidSource.SetScalarModeToZ()

        ellipsoidMapper = vtk.vtkPolyDataMapper()
        ellipsoidMapper.SetInputConnection(ellipsoidSource.GetOutputPort())
        ellipsoidMapper.SetScalarRange(-0.5, 0.5)

        ellipsoidActor = vtk.vtkActor()
        ellipsoidActor.SetMapper(ellipsoidMapper)
        ellipsoidActor.SetPosition(8, -12, 0)
        ellipsoidActor.SetScale(1.5, 1.5, 1.5)

        ellipsoidTextMapper = vtk.vtkTextMapper()
        ellipsoidTextMapper.SetInput("Ellipsoid")
        ellipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        ellipsoidTextMapper.GetTextProperty().SetFontSize(14)
        ellipsoidTextActor = vtk.vtkActor2D()
        ellipsoidTextActor.SetMapper(ellipsoidTextMapper)
        ellipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        ellipsoidTextActor.GetPositionCoordinate().SetValue(8, -14.5, 0)

        # ------------------------------------------------------------
        # Create a surface with random hills on it.
        # ------------------------------------------------------------
        randomHills = vtk.vtkParametricRandomHills()
        randomHills.AllowRandomGenerationOn()
        randomHillsSource = vtk.vtkParametricFunctionSource()
        randomHillsSource.SetParametricFunction(randomHills)
        randomHillsSource.GenerateTextureCoordinatesOn()

        randomHillsMapper = vtk.vtkPolyDataMapper()
        randomHillsMapper.SetInputConnection(randomHillsSource.GetOutputPort())

        randomHillsActor = vtk.vtkActor()
        randomHillsActor.SetMapper(randomHillsMapper)
        randomHillsActor.SetPosition(16, -14, 0)
        randomHillsActor.SetScale(0.2, 0.2, 0.2)
        randomHillsActor.SetTexture(texture)

        randomHillsTextMapper = vtk.vtkTextMapper()
        randomHillsTextMapper.SetInput("Random.Hills")
        randomHillsTextMapper.GetTextProperty().SetJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetColor(1, 0, 0)
        randomHillsTextMapper.GetTextProperty().SetFontSize(14)
        randomHillsTextActor = vtk.vtkActor2D()
        randomHillsTextActor.SetMapper(randomHillsTextMapper)
        randomHillsTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        randomHillsTextActor.GetPositionCoordinate().SetValue(16, -14.5, 0)

        # ------------------------------------------------------------
        # Create Steiner's Roman Surface.
        # ------------------------------------------------------------
        roman = vtk.vtkParametricRoman()
        roman.SetRadius(1.5)
        romanSource = vtk.vtkParametricFunctionSource()
        romanSource.SetParametricFunction(roman)
        romanSource.SetScalarModeToX()

        romanMapper = vtk.vtkPolyDataMapper()
        romanMapper.SetInputConnection(romanSource.GetOutputPort())

        romanActor = vtk.vtkActor()
        romanActor.SetMapper(romanMapper)
        romanActor.SetPosition(24, -12, 0)

        romanTextMapper = vtk.vtkTextMapper()
        romanTextMapper.SetInput("Roman")
        romanTextMapper.GetTextProperty().SetJustificationToCentered()
        romanTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        romanTextMapper.GetTextProperty().SetColor(1, 0, 0)
        romanTextMapper.GetTextProperty().SetFontSize(14)
        romanTextActor = vtk.vtkActor2D()
        romanTextActor.SetMapper(romanTextMapper)
        romanTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        romanTextActor.GetPositionCoordinate().SetValue(24, -14.5, 0)

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

        # add actors
        ren.AddViewProp(torusActor)
        ren.AddViewProp(kleinActor)
        ren.AddViewProp(klein2Actor)
        ren.AddViewProp(toroidActor)
        ren.AddViewProp(superEllipsoidActor)
        ren.AddViewProp(mobiusActor)
        ren.AddViewProp(splineActor)
        ren.AddViewProp(spline2Actor)
        ren.AddViewProp(sconicActor)
        ren.AddViewProp(boyActor)
        ren.AddViewProp(crossCapActor)
        ren.AddViewProp(diniActor)
        ren.AddViewProp(enneperActor)
        ren.AddViewProp(ellipsoidActor)
        ren.AddViewProp(randomHillsActor)
        ren.AddViewProp(romanActor)
        #add text actors
        ren.AddViewProp(torusTextActor)
        ren.AddViewProp(kleinTextActor)
        ren.AddViewProp(fig8KleinTextActor)
        ren.AddViewProp(mobiusTextActor)
        ren.AddViewProp(superToroidTextActor)
        ren.AddViewProp(superEllipsoidTextActor)
        ren.AddViewProp(splineTextActor)
        ren.AddViewProp(spline2TextActor)
        ren.AddViewProp(sconicTextActor)
        ren.AddViewProp(boyTextActor)
        ren.AddViewProp(crossCapTextActor)
        ren.AddViewProp(diniTextActor)
        ren.AddViewProp(enneperTextActor)
        ren.AddViewProp(ellipsoidTextActor)
        ren.AddViewProp(randomHillsTextActor)
        ren.AddViewProp(romanTextActor)

        ren.SetBackground(0.7, 0.8, 1)
        renWin.SetSize(500, 500)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.3)

        iren.Initialize()
        renWin.Render()

        img_file = "TestParametricFunctions.png"
        # NOTE: this test has a companion .tcl test. The threshold set
        #  here should be the same as the threshold in the .tcl
        #  test. Both tests should produce exactly the same results.
        vtk.test.Testing.compareImage(iren.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=10)
        vtk.test.Testing.interact()
示例#53
0
    def set_structure(self, structure, reset_camera=True):
        """
        Add a structure to the visualizer.

        Args:
            structure:
                structure to visualize
            reset_camera:
                Set to True to reset the camera to a default determined based
                on the structure.
        """
        self.ren.RemoveAllViewProps()

        has_lattice = hasattr(structure, "lattice")

        if has_lattice:
            s = Structure.from_sites(structure, to_unit_cell=True)
            s.make_supercell(self.supercell)
        else:
            s = structure

        inc_coords = []
        for site in s:
            self.add_site(site)
            inc_coords.append(site.coords)

        count = 0
        labels = ["a", "b", "c"]
        colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]

        if has_lattice:
            matrix = s.lattice.matrix

        if self.show_unit_cell and has_lattice:
            #matrix = s.lattice.matrix
            self.add_text([0, 0, 0], "o")
            for vec in matrix:
                self.add_line((0, 0, 0), vec, colors[count])
                self.add_text(vec, labels[count], colors[count])
                count += 1
            for (vec1, vec2) in itertools.permutations(matrix, 2):
                self.add_line(vec1, vec1 + vec2)
            for (vec1, vec2, vec3) in itertools.permutations(matrix, 3):
                self.add_line(vec1 + vec2, vec1 + vec2 + vec3)

        if self.show_bonds or self.show_polyhedron:
            elements = sorted(s.composition.elements, key=lambda a: a.X)
            anion = elements[-1]

            def contains_anion(site):
                for sp in site.species_and_occu.keys():
                    if sp.symbol == anion.symbol:
                        return True
                return False

            anion_radius = anion.average_ionic_radius
            for site in s:
                exclude = False
                max_radius = 0
                color = np.array([0, 0, 0])
                for sp, occu in site.species_and_occu.items():
                    if sp.symbol in self.excluded_bonding_elements \
                            or sp == anion:
                        exclude = True
                        break
                    max_radius = max(max_radius, sp.average_ionic_radius)
                    color = color + \
                        occu * np.array(self.el_color_mapping.get(sp.symbol,
                                                                  [0, 0, 0]))

                if not exclude:
                    max_radius = (1 + self.poly_radii_tol_factor) * \
                        (max_radius + anion_radius)
                    nn = structure.get_neighbors(site, max_radius)
                    nn_sites = []
                    for nnsite, dist in nn:
                        if contains_anion(nnsite):
                            nn_sites.append(nnsite)
                            if not in_coord_list(inc_coords, nnsite.coords):
                                self.add_site(nnsite)
                    if self.show_bonds:
                        self.add_bonds(nn_sites, site)
                    if self.show_polyhedron:
                        color = [i / 255 for i in color]
                        self.add_polyhedron(nn_sites, site, color)

        if self.show_help:
            self.helptxt_actor = vtk.vtkActor2D()
            self.helptxt_actor.VisibilityOn()
            self.helptxt_actor.SetMapper(self.helptxt_mapper)
            self.ren.AddActor(self.helptxt_actor)
            self.display_help()

        camera = self.ren.GetActiveCamera()
        if reset_camera:
            if has_lattice:
                #Adjust the camera for best viewing
                lengths = s.lattice.abc
                pos = (matrix[1] + matrix[2]) * 0.5 + \
                    matrix[0] * max(lengths) / lengths[0] * 3.5
                camera.SetPosition(pos)
                camera.SetViewUp(matrix[2])
                camera.SetFocalPoint((matrix[0] + matrix[1] + matrix[2]) * 0.5)
            else:
                origin = s.center_of_mass
                max_site = max(
                    s, key=lambda site: site.distance_from_point(origin))
                camera.SetPosition(origin + 5 * (max_site.coords - origin))
                camera.SetFocalPoint(s.center_of_mass)

        self.structure = structure
        self.title = s.composition.formula
示例#54
0
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

i = 0

# another actor to test occlusion
plane = vtk.vtkPlaneSource()
plane.SetOrigin(120, 10, 0)
plane.SetPoint1(220, 10, 0)
plane.SetPoint2(120, 110, 0)

mapper = vtk.vtkPolyDataMapper2D()
mapper.SetInputConnection(plane.GetOutputPort())

actor = vtk.vtkActor2D()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(0.5, 0.5, 0.5)

ren.AddActor(actor)

for (bold, italic, shadow) in ((0, 0, 0), (0, 0, 1), (1, 0, 0), (0, 1, 0),
                               (1, 1, 0)):
    i = i + 1
    attribs = []
    if bold:
        attribs.append("b")

    if italic:
        attribs.append("i")
示例#55
0
# Create a table of glyphs
glypher = vtk.vtkGlyph2D()
glypher.SetInputData(pd)
glypher.SetSourceData(0, gs.GetOutput())
glypher.SetSourceData(1, gs1.GetOutput())
glypher.SetSourceData(2, gs2.GetOutput())
glypher.SetSourceData(3, gs3.GetOutput())
glypher.SetSourceData(4, gs4.GetOutput())
glypher.SetSourceData(5, gs5.GetOutput())
glypher.SetIndexModeToScalar()
glypher.SetRange(0, 5)
glypher.SetScaleModeToDataScalingOff()
mapper = vtk.vtkPolyDataMapper2D()
mapper.SetInputConnection(glypher.GetOutputPort())
mapper.SetScalarRange(0, 5)
glyphActor = vtk.vtkActor2D()
glyphActor.SetMapper(mapper)
# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Add the actors to the renderer, set the background and size
#
ren1.AddActor(glyphActor)
ren1.SetBackground(1, 1, 1)
renWin.SetSize(size, size)
renWin.Render()
示例#56
0
    def AddPointLabels(self, points, labels, bold=True, fontsize=16,
                       textcolor='k', font_family='courier', shadow=False,
                       showpoints=True, pointcolor='k', pointsize=5):
        """
        Creates a point actor with one label from list labels assigned to
        each point.
        
        Parameters
        ----------
        points : np.ndarray
            3 x n numpy array of points.
            
        labels : list
            List of labels.  Must be the same length as points.
            
        italic : bool, optional
            Italicises title and bar labels.  Default False.
            
        bold : bool, optional
            Bolds title and bar labels.  Default True
            
        fontsize : float, optional
            Sets the size of the title font.  Defaults to 16.
            
        textcolor : string or 3 item list, optional, defaults to black
            Color of text.
            Either a string, rgb list, or hex color string.  For example:
                textcolor='white'
                textcolor='w'
                textcolor=[1, 1, 1]
                textcolor='#FFFFFF'
                
        font_family : string, optional
            Font family.  Must be either courier, times, or arial.
            
        shadow : bool, optional
            Adds a black shadow to the text.  Defaults to False
            
        showpoints : bool, optional
            Controls if points are visible.  Default True
            
        pointcolor : string or 3 item list, optional, defaults to black
            Color of points (if visible).
            Either a string, rgb list, or hex color string.  For example:
                textcolor='white'
                textcolor='w'
                textcolor=[1, 1, 1]
                textcolor='#FFFFFF'
                
        pointsize : float, optional
            Size of points (if visible)
        
        Returns
        -------
        labelMapper : vtk.vtkvtkLabeledDataMapper
            VTK label mapper.  Can be used to change properties of the labels.
        
        """
        
        if len(points) != len(labels):
            raise Exception('There must be one label for each point')
        
        vtkpoints = vtkInterface.MakePointMesh(points)

        vtklabels = vtk.vtkStringArray()
        vtklabels.SetName('labels')
        for item in labels:
            vtklabels.InsertNextValue(str(item))
        
        vtkpoints.GetPointData().AddArray(vtklabels)
        
        # create label mapper
        labelMapper = vtk.vtkLabeledDataMapper()
        labelMapper.SetInputData(vtkpoints)
        textprop = labelMapper.GetLabelTextProperty()
        textprop.SetBold(bold)
        textprop.SetFontSize(fontsize)
        textprop.SetFontFamily(ParseFontFamily(font_family))
        textprop.SetColor(ParseColor(textcolor))
        textprop.SetShadow(shadow)
        labelMapper.SetLabelModeToLabelFieldData()
        labelMapper.SetFieldDataName('labels')

        labelActor = vtk.vtkActor2D()
        labelActor.SetMapper(labelMapper)
        
        # add points
        if showpoints:
            self.AddMesh(vtkpoints, style='points', color=pointcolor,
                         psize=pointsize)
        else:
            self.AddMesh(vtkpoints)
            
        self.AddActor(labelActor)
        return labelMapper
示例#57
0
def DisplayBodies():
 
    titles = list()
    textMappers = list()
    textActors = list()
 
    uGrids = list()
    mappers = list()
    actors = list()
    renderers = list()
 
    uGrids.append(MakeHexagonalPrism())
    titles.append('Hexagonal Prism')
    uGrids.append(MakeHexahedron())
    titles.append('Hexahedron')
    uGrids.append(MakePentagonalPrism())
    titles.append('Pentagonal Prism')
 
    uGrids.append(MakePolyhedron())
    titles.append('Polyhedron')
    uGrids.append(MakePyramid())
    titles.append('Pyramid')
    uGrids.append(MakeTetrahedron())
    titles.append('Tetrahedron')
 
    uGrids.append(MakeVoxel())
    titles.append('Voxel')
    uGrids.append(MakeWedge())
    titles.append('Wedge')
 
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    renWin.SetWindowName('Cell3D Demonstration')
 
    iRen = vtk.vtkRenderWindowInteractor()
    iRen.SetRenderWindow(renWin)
 
    # Create one text property for all
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(10)
    textProperty.SetJustificationToCentered()
 
    # Create and link the mappers actors and renderers together.
    for i in range(0, len(uGrids)):
        textMappers.append(vtk.vtkTextMapper())
        textActors.append(vtk.vtkActor2D())
 
        mappers.append(vtk.vtkDataSetMapper())
        actors.append(vtk.vtkActor())
        renderers.append(vtk.vtkRenderer())
 
        mappers[i].SetInputData(uGrids[i])
        actors[i].SetMapper(mappers[i])
        renderers[i].AddViewProp(actors[i])
 
        textMappers[i].SetInput(titles[i])
        textActors[i].SetMapper(textMappers[i])
        textActors[i].SetPosition(50, 10)
        renderers[i].AddViewProp(textActors[i])
 
        renWin.AddRenderer(renderers[i])
 
    gridDimensions = 3
    rendererSize = 200
 
    renWin.SetSize(rendererSize * gridDimensions,
                   rendererSize * gridDimensions)
 
    for row in range(0, gridDimensions):
        for col in range(0, gridDimensions):
            index = row * gridDimensions + col
 
            # (xmin, ymin, xmax, ymax)
            viewport = [
                float(col) * rendererSize /
                                     (gridDimensions * rendererSize),
                float(gridDimensions - (row + 1)) * rendererSize /
                                     (gridDimensions * rendererSize),
                float(col + 1) * rendererSize /
                                     (gridDimensions * rendererSize),
                float(gridDimensions - row) * rendererSize /
                                     (gridDimensions * rendererSize)]
 
            if index > len(actors) - 1:
                # Add a renderer even if there is no actor.
                # This makes the render window background all the same color.
                ren = vtk.vtkRenderer()
                ren.SetBackground(.2, .3, .4)
                ren.SetViewport(viewport)
                renWin.AddRenderer(ren)
                continue
 
            renderers[index].SetViewport(viewport)
            renderers[index].SetBackground(.2, .3, .4)
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(-30)
            renderers[index].GetActiveCamera().Zoom(0.85)
            renderers[index].ResetCameraClippingRange()
 
    iRen.Initialize()
    renWin.Render()
    return iRen
示例#58
0
def main():
    titles = list()
    textMappers = list()
    textActors = list()

    uGrids = list()
    mappers = list()
    actors = list()
    renderers = list()

    uGrids.append(MakeVertex())
    titles.append('VTK_VERTEX (=1)')
    uGrids.append(MakePolyVertex())
    titles.append('VTK_POLY_VERTEX (=2)')
    uGrids.append(MakeLine())
    titles.append('VTK_LINE (=3)')
    uGrids.append(MakePolyLine())
    titles.append('VTK_POLY_LINE (=4)')
    uGrids.append(MakeTriangle())
    titles.append('VTK_TRIANGLE (=5)')
    uGrids.append(MakeTriangleStrip())
    titles.append('VTK_TRIANGLE_STRIP (=6)')
    uGrids.append(MakePolygon())
    titles.append('VTK_POLYGON (=7)')
    uGrids.append(MakePixel())
    titles.append('VTK_PIXEL (=8)')
    uGrids.append(MakeQuad())
    titles.append('VTK_QUAD (=9)')
    uGrids.append(MakeTetra())
    titles.append('VTK_TETRA (=10)')
    uGrids.append(MakeVoxel())
    titles.append('VTK_VOXEL (=11)')
    uGrids.append(MakeHexahedron())
    titles.append('VTK_HEXAHEDRON (=12)')
    uGrids.append(MakeWedge())
    titles.append('VTK_WEDGE (=13)')
    uGrids.append(MakePyramid())
    titles.append('VTK_PYRAMID (=14)')
    uGrids.append(MakePentagonalPrism())
    titles.append('VTK_PENTAGONAL_PRISM (=15)')
    uGrids.append(MakeHexagonalPrism())
    titles.append('VTK_HEXAGONAL_PRISM (=16)')

    colors = vtk.vtkNamedColors()

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    renWin.SetWindowName('LinearCellDemo')

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

    # Create one sphere for all
    sphere = vtk.vtkSphereSource()
    sphere.SetPhiResolution(21)
    sphere.SetThetaResolution(21)
    sphere.SetRadius(.08)

    # Create one text property for all
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(10)
    textProperty.SetJustificationToCentered()


    # Create and link the mappers actors and renderers together.
    for i in range(0, len(uGrids)):
        print('Creating:', titles[i])
        textMappers.append(vtk.vtkTextMapper())
        textActors.append(vtk.vtkActor2D())

        mappers.append(vtk.vtkDataSetMapper())
        actors.append(vtk.vtkActor())
        renderers.append(vtk.vtkRenderer())
        mappers[i].SetInputData(uGrids[i])
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d('Tomato'))
        actors[i].GetProperty().EdgeVisibilityOn()
        actors[i].GetProperty().SetLineWidth(3)
        actors[i].GetProperty().SetOpacity(.5)
        renderers[i].AddViewProp(actors[i])

        textMappers[i].SetInput(titles[i])
        textActors[i].SetMapper(textMappers[i])
        textActors[i].SetPosition(50, 10)
        renderers[i].AddViewProp(textActors[i])

        # Label the points
        labelMapper = vtk.vtkLabeledDataMapper()
        labelMapper.SetInputData(uGrids[i])
        labelActor = vtk.vtkActor2D()
        labelActor.SetMapper(labelMapper)
        renderers[i].AddViewProp(labelActor)

        # Glyph the points
        pointMapper = vtk.vtkGlyph3DMapper()
        pointMapper.SetInputData(uGrids[i])
        pointMapper.SetSourceConnection(sphere.GetOutputPort())
        pointMapper.ScalingOff()
        pointMapper.ScalarVisibilityOff()

        pointActor = vtk.vtkActor()
        pointActor.SetMapper(pointMapper)
        pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana'))
        pointActor.GetProperty().SetSpecular(.6)
        pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
        pointActor.GetProperty().SetSpecularPower(100)
        renderers[i].AddViewProp(pointActor)

        renWin.AddRenderer(renderers[i])

    # Setup the viewports
    xGridDimensions = 4
    yGridDimensions = 4
    rendererSize = 240
    renWin.SetSize(rendererSize * xGridDimensions, rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(0, xGridDimensions):
            index = row * xGridDimensions + col

            # (xmin, ymin, xmax, ymax)
            viewport = [float(col) / xGridDimensions,
                        float(yGridDimensions - (row + 1)) / yGridDimensions,
                        float(col + 1) / xGridDimensions,
                        float(yGridDimensions - row) / yGridDimensions]

            if index > (len(actors) - 1):
                # Add a renderer even if there is no actor.
                # This makes the render window background all the same color.
                ren = vtk.vtkRenderer()
                ren.SetBackground(colors.GetColor3d('SlateGray'))
                ren.SetViewport(viewport)
                renWin.AddRenderer(ren)
                continue

            renderers[index].SetViewport(viewport)
            renderers[index].SetBackground(colors.GetColor3d('SlateGray'))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(-30)
            if index == 0:
                renderers[index].GetActiveCamera().Dolly(0.1)
                renderers[index].ResetCameraClippingRange()
            if index == 4:
                renderers[index].GetActiveCamera().Dolly(0.8)
                renderers[index].ResetCameraClippingRange()
            renderers[index].ResetCameraClippingRange()

    renWin.Render()
    iRen.Initialize()
    iRen.Start()
def main():
    colors = vtk.vtkNamedColors()

    colors.SetColor("BkgColor", [26, 51, 102, 255])

    parametricObjects = list()
    parametricObjects.append(vtk.vtkParametricBohemianDome())
    parametricObjects[-1].SetA(5.0)
    parametricObjects[-1].SetB(1.0)
    parametricObjects[-1].SetC(2.0)
    parametricObjects.append(vtk.vtkParametricBour())
    parametricObjects.append(vtk.vtkParametricCatalanMinimal())
    parametricObjects.append(vtk.vtkParametricHenneberg())
    parametricObjects.append(vtk.vtkParametricKuen())
    parametricObjects.append(vtk.vtkParametricPluckerConoid())
    parametricObjects.append(vtk.vtkParametricPseudosphere())

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

    # Create one text property for all
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(12)
    textProperty.SetJustificationToCentered()

    backProperty = vtk.vtkProperty()
    backProperty.SetColor(colors.GetColor3d("Tomato"))

    # Create a parametric function source, renderer, mapper, and actor
    # for each object
    for i in range(0, len(parametricObjects)):
        parametricFunctionSources.append(
            vtk.vtkParametricFunctionSource())
        parametricFunctionSources[i].SetParametricFunction(parametricObjects[i])
        parametricFunctionSources[i].Update()

        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(
            parametricFunctionSources[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d("Banana"))
        actors[i].GetProperty().SetSpecular(.5)
        actors[i].GetProperty().SetSpecularPower(20)
        actors[i].SetBackfaceProperty(backProperty)

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(parametricObjects[i].GetClassName())
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(100, 16)

        renderers.append(vtk.vtkRenderer())
        renderers[i].AddActor(actors[i])
        renderers[i].AddActor(textactors[i])
        renderers[i].SetBackground(colors.GetColor3d("BkgColor"))

    # Setup the viewports
    xGridDimensions = 4
    yGridDimensions = 2
    rendererSize = 200
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Parametric Objects Demonstration2")
    renderWindow.SetSize(rendererSize * xGridDimensions,
                         rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(0, xGridDimensions):
            index = row * xGridDimensions + col

            # (xmin, ymin, xmax, ymax)
            viewport = [float(col) / xGridDimensions,
                        float(yGridDimensions - (row + 1)) / yGridDimensions,
                        float(col + 1) / xGridDimensions,
                        float(yGridDimensions - row) / yGridDimensions]

            if index > (len(actors) - 1):
                # Add a renderer even if there is no actor.
                # This makes the render window background all the same color.
                ren = vtk.vtkRenderer()
                ren.SetBackground(colors.GetColor3d("BkgColor"))
                ren.SetViewport(viewport)
                renderWindow.AddRenderer(ren)
                continue

            renderers[index].SetViewport(viewport)
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(-30)
            renderers[index].GetActiveCamera().Zoom(0.9)
            renderers[index].ResetCameraClippingRange()
            renderWindow.AddRenderer(renderers[index])

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

    renderWindow.Render()
    interactor.Start()
示例#60
0
    def __init__(self,
                 dimx=600,
                 dimy=600,
                 renWin=None,
                 iren=None,
                 ren=None,
                 debug=False):
        '''creates the rendering pipeline'''

        # Handle arguments
        if renWin is not None:
            self.renWin = renWin
        else:
            self.renWin = vtk.vtkRenderWindow()

        if iren is not None:
            self.iren = iren
        else:
            self.iren = vtk.vtkRenderWindowInteractor()

        # create a rendering window and renderer
        if ren is not None:
            self.ren = ren
        else:
            self.ren = vtk.vtkRenderer()
        self.renWin.SetSize(dimx, dimy)
        self.renWin.AddRenderer(self.ren)

        # img 3D as slice
        self.img3D = None
        self.slicenos = [0, 0, 0]
        self.sliceOrientation = SLICE_ORIENTATION_XY
        self.sliceActor = vtk.vtkImageActor()
        self.voi = vtk.vtkExtractVOI()
        self.wl = vtk.vtkImageMapToWindowLevelColors()
        self.ia = vtk.vtkImageHistogramStatistics()
        self.sliceActorNo = 0

        # Viewer Event manager
        self.event = ViewerEventManager()

        # create a renderwindowinteractor
        self.style = CILInteractorStyle(self)
        self.iren.SetInteractorStyle(self.style)
        self.iren.SetRenderWindow(self.renWin)

        # Render decimation
        self.decimate = vtk.vtkDecimatePro()

        self.ren.SetBackground(.1, .2, .4)

        self.actors = {}

        # Help text
        self.helpActor = vtk.vtkActor2D()
        self.helpActor.GetPositionCoordinate(
        ).SetCoordinateSystemToNormalizedDisplay()
        self.helpActor.GetPositionCoordinate().SetValue(0.1, 0.5)
        self.helpActor.VisibilityOff()
        self.ren.AddActor(self.helpActor)

        # volume render
        volumeMapper = vtk.vtkSmartVolumeMapper()
        #volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
        self.volume_mapper = volumeMapper

        volumeProperty = vtk.vtkVolumeProperty()
        self.volume_property = volumeProperty

        # The volume holds the mapper and the property and
        # can be used to position/orient the volume.
        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
        self.volume = volume
        self.volume_render_initialised = False

        # axis orientation widget
        om = vtk.vtkAxesActor()
        ori = vtk.vtkOrientationMarkerWidget()
        ori.SetOutlineColor(0.9300, 0.5700, 0.1300)
        ori.SetInteractor(self.iren)
        ori.SetOrientationMarker(om)
        ori.SetViewport(0.0, 0.0, 0.4, 0.4)
        ori.SetEnabled(1)
        ori.InteractiveOff()
        self.orientation_marker = ori

        self.iren.Initialize()