def Paint(self, vtkSelf, context2D):
        context2D.DrawPolyData(0.0,
                               0.0,
                               self.polydata,
                               self.polydata.GetCellData().GetScalars(),
                               vtk.VTK_SCALAR_MODE_USE_CELL_DATA)

        pen = context2D.GetPen()

        penColor = [0, 0, 0]
        pen.GetColor(penColor)
        penWidth = pen.GetWidth()

        brush = context2D.GetBrush()
        brushColor = [0, 0, 0, 0]
        brush.GetColor(brushColor)

        pen.SetColor([0, 0, 255])
        brush.SetColor([0, 0, 255])
        context2D.DrawWedge(0.75, 0.25, 0.125, 0.005, 30.0, 60.0)

        pen.SetWidth(20.0)
        pen.SetColor([0, 0, 0])
        brush.SetColor([0, 0, 0])
        context2D.DrawMarkers(vtk.vtkMarkerUtilities.CIRCLE, False, [0.1, 0.1, 0.5, 0.5, 0.9, 0.9], 3)
        pen.SetWidth(1.0)

        textProp = vtk.vtkTextProperty()
        textProp.BoldOn()
        textProp.ItalicOn()
        textProp.SetFontSize(22)
        textProp.SetColor(0.5, 0.0, 1.0)
        textProp.SetOrientation(45)
        context2D.ApplyTextProp(textProp)
        context2D.DrawString(0.35, 0.4, "Context2D!")

        pen.SetColor([200, 200, 30])
        brush.SetColor([200, 200, 30])
        brush.SetOpacity(128)
        context2D.DrawPolygon([0.5, 0.5, 0.75, 0.0, 1.0, 0.5], 3)

        pen.SetColor([133, 70, 70])
        brush.SetColor([133, 70, 70])
        brush.SetOpacity(255)
        context2D.DrawArc(0.25, 0.75, 0.125, 0.0, 360.0)

        pen.SetWidth(penWidth)
        pen.SetColor(penColor)
        brush.SetColor(brushColor[:3])
        brush.SetOpacity(brushColor[3])

        return True
    def createActor( self, **args ):
        if self.colorBarActor == None:
            pos = args.get( 'pos', [ 0.9, 0.2 ] )
            title = args.get( 'title', '' )
            self.colorBarActor = vtk.vtkScalarBarActor()
#            self.colorBarActor.SetMaximumWidthInPixels( 50 )
            self.colorBarActor.SetNumberOfLabels(9)
            labelFormat = vtk.vtkTextProperty()
            labelFormat.SetFontSize( 160 )
            labelFormat.SetColor(  VTK_FOREGROUND_COLOR[0], VTK_FOREGROUND_COLOR[1], VTK_FOREGROUND_COLOR[2] ) 
            titleFormat = vtk.vtkTextProperty()
            titleFormat.SetFontSize( 160 )
            titleFormat.SetColor(  VTK_FOREGROUND_COLOR[0], VTK_FOREGROUND_COLOR[1], VTK_FOREGROUND_COLOR[2]  ) 
#            titleFormat.SetVerticalJustificationToTop ()
#            titleFormat.BoldOn()
            self.colorBarActor.SetPosition( pos[0], pos[1] )    
            self.colorBarActor.SetLabelTextProperty( labelFormat )
            self.colorBarActor.SetTitleTextProperty( titleFormat )
            self.colorBarActor.SetTitle( title )
            self.colorBarActor.SetLookupTable( self.getDisplayLookupTable() )
            self.colorBarActor.SetVisibility(0)
            self.colorBarActor.SetMaximumWidthInPixels(75)
        else:
            self.colorBarActor.SetLookupTable( self.getDisplayLookupTable() )
            self.colorBarActor.Modified() 
        return self.colorBarActor
Ejemplo n.º 3
0
    def __init__(self):

        # Skip the parent constructor
        # super(Axes, self).__init__(renderer)

        text_property_x = vtk.vtkTextProperty()
        text_property_x.ItalicOn()
        text_property_x.ShadowOn()
        text_property_x.BoldOn()
        text_property_x.SetFontFamilyToTimes()
        text_property_x.SetColor(1, 0, 0)

        text_property_y = vtk.vtkTextProperty()
        text_property_y.ShallowCopy(text_property_x)
        text_property_y.SetColor(0, 1, 0)

        text_property_z = vtk.vtkTextProperty()
        text_property_z.ShallowCopy(text_property_x)
        text_property_z.SetColor(0, 0, 1)

        self.axes = vtk.vtkAxesActor()
        self.axes.SetShaftTypeToCylinder()
        self.axes.SetCylinderRadius(0.05)
        self.axes.SetTotalLength(3 * [1.5])

        self.axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(
            text_property_x)
        self.axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(
            text_property_y)
        self.axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(
            text_property_z)
Ejemplo n.º 4
0
    def build_axes(self, noZaxis = False):
        if self.axes is None:
            self.axes = vtk.vtkAxesActor()
#             self.axes.SetShaftTypeToCylinder()
            if not noZaxis:
                self.axes.SetTotalLength( self.data.shape[0] - 1, self.data.shape[1] - 1, self.data.shape[2] - 1)
            else:
                self.axes.SetTotalLength( self.data.shape[0] - 1, self.data.shape[1] - 1, 0 )
            self.axes.SetNormalizedShaftLength( 1, 1, 1 )
            self.axes.SetNormalizedTipLength( 0, 0, 0 )
#             self.axes.SetNormalizedShaftLength( 0.85, 0.85, 0.85 )
#             self.axes.SetNormalizedTipLength( 0.15, 0.15, 0.15 )
            self.axes.AxisLabelsOn()
            self.axes.GetXAxisTipProperty().SetColor( 0, 0, 1)
            self.axes.GetXAxisShaftProperty().SetColor( 0, 0, 1)
            self.axes.GetXAxisShaftProperty().SetLineWidth (2)
            self.axes.SetXAxisLabelText('x')
            txtprop = vtk.vtkTextProperty()
            txtprop.SetColor(0, 0, 0)
            txtprop.SetFontFamilyToArial()
            txtprop.SetFontSize(12)
            txtprop.SetOpacity(0.5)
            self.axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(txtprop)
            
            self.axes.GetYAxisTipProperty().SetColor( 0, 1, 0)
            self.axes.GetYAxisShaftProperty().SetColor( 0, 1, 0)
            self.axes.GetYAxisShaftProperty().SetLineWidth (2)
            self.axes.SetYAxisLabelText('y')
            txtprop = vtk.vtkTextProperty()
            txtprop.SetColor(0, 0, 0)
            txtprop.SetFontFamilyToArial()
            txtprop.SetFontSize(12)
            txtprop.SetOpacity(0.5)
            self.axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(txtprop)
            
            self.axes.GetZAxisTipProperty().SetColor( 1, 0, 0 )
            self.axes.GetZAxisShaftProperty().SetColor( 1, 0, 0)
            self.axes.GetZAxisShaftProperty().SetLineWidth (2)
            self.axes.SetZAxisLabelText('z')
            txtprop = vtk.vtkTextProperty()
            txtprop.SetColor(0, 0, 0)
            txtprop.SetFontFamilyToArial()
            txtprop.SetFontSize(12)
            txtprop.SetOpacity(0.5)
            self.axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(txtprop)
            
            self.renderer.AddActor(self.axes)   
            self.iren.Render()
        else :
            if self.axes.GetVisibility():
                self.axes.VisibilityOff()
            else:
                self.axes.VisibilityOn()
            self.iren.Render()    
Ejemplo n.º 5
0
    def buildLookupTable(self):
        self.colorFunction = vtk.vtkColorTransferFunction()
        self.colorFunction.SetColorSpaceToHSV()
        self.colorFunction.HSVWrapOff()

        drange = [10., 20.]
        self.colorFunction.AddRGBPoint(drange[0], 0.0, 0.0, 1.0)
        self.colorFunction.AddRGBPoint(drange[1], 1.0, 0.0, 0.0)

        self.scalarBar.SetTitle("Title1")
        self.scalarBar.SetLookupTable(self.colorFunction)
        self.scalarBar.SetOrientationToVertical()
        #self.scalarBar.GetLabelTextProperty().SetFontSize(8)

        self.scalarBar.SetHeight(0.9)
        self.scalarBar.SetWidth(0.20)  # the width is set first
        # after the width is set, this is adjusted
        self.scalarBar.SetPosition(0.77, 0.1)
        #self.scalarBar.SetPosition2(0.1, 0.3)
        #print self.scalarBar.GetPosition()

        propTitle = vtk.vtkTextProperty()
        propTitle.SetFontFamilyToArial()
        #propTitle.ItalicOff()
        propTitle.BoldOn()
        propTitle.ShadowOn()

        propLabel = vtk.vtkTextProperty()
        propLabel.BoldOff()
        propLabel.ShadowOn()
        #propLabel.SetFontSize(8)

        scalar_range = self.grid.GetScalarRange()
        self.aQuadMapper.SetScalarRange(scalar_range)
        self.aQuadMapper.SetLookupTable(self.colorFunction)

        #self.scalarBar.SetTitleTextProperty(propTitle);
        #self.scalarBar.SetLabelTextProperty(propLabel);
        self.scalarBar.SetLabelFormat("%i")

        # allows 0-1 to be nice number when ranging values (gotta pick something)
        self.scalarBar.SetNumberOfLabels(11)
        self.scalarBar.SetMaximumNumberOfColors(11)

        #self.scalarBar.VisibilityOff()  # first load -> scalar bar off
        #self.scalarBar.ShadowOn()
        #self.scalarBar.RepositionableOn()
        self.rend.AddActor(self.scalarBar)
 def __init__(self):
     self.IsProcessed = False
     self.Interaction = True
     self.ShowAnnotations = True
     self.ShowDirections = True
     self.AboutDataVisibility = True
     self.LinkRender = True
     self.LinkCameraFocalAndPosition = False
     
     
     self.Renderer = None
     self.RenderWindow = None
     self.RenderWindowInteractor = None
     self.Children = []
     self.InteractorStyle = None
     # Initilize Annotations
     self.CornerAnnotation = vtk.vtkCornerAnnotation()
     self.CornerAnnotation.SetNonlinearFontScaleFactor(0.3)
     
     self.TextProperty = vtk.vtkTextProperty()
     self.CornerAnnotation.SetTextProperty(self.TextProperty)
     
     #self.OrientationAnnotation = vtkOrientationAnnotation()
     #self.OrientationAnnotation.SetNonlinearFontScaleFactor(0.25)
     
     #self.InteractorStyle = vtk.vtkInteractorStyleSwitch()
     
     self.Parent = None
     
     self.downRightAnnotation = ""
     self.upLeftAnnotation = ""
     self.upRightAnnotation = ""
     self.downLeftAnnotation = ""
     self.AboutData = ""
     self.InternalMTime = 0
Ejemplo n.º 7
0
Archivo: epdp.py Proyecto: ecell/newio
    def __create_time_legend(self):
        time_legend = vtk.vtkLegendBoxActor()

        # Create legend actor
        time_legend.SetNumberOfEntries(1)
        time_legend.SetPosition(
            self.__get_legend_position(
                self.settings.time_legend_location,
                self.settings.time_legend_height,
                self.settings.time_legend_width,
                self.settings.time_legend_offset,
            )
        )

        time_legend.SetWidth(self.settings.time_legend_width)
        time_legend.SetHeight(self.settings.time_legend_height)

        tprop = vtk.vtkTextProperty()
        tprop.SetColor(rgb_colors.RGB_WHITE)
        tprop.SetVerticalJustificationToCentered()
        time_legend.SetEntryTextProperty(tprop)

        if self.settings.time_legend_border_display:
            time_legend.BorderOn()
        else:
            time_legend.BorderOff()
        return time_legend
Ejemplo n.º 8
0
Archivo: cell.py Proyecto: jboes/ase
    def __init__(self, cell):

        assert isinstance(cell, vtkUnitCellModule)
        self.cell = cell

        l0 = self.cell.get_characteristic_length()

        # Create VTK axes actor (not really a VTK actor though)
        self.vtk_ax = vtkAxesActor()
        self.vtk_ax.SetTipTypeToCone()
        self.vtk_ax.SetConeRadius(5e-2*l0)
        self.vtk_ax.SetShaftTypeToCylinder()
        self.vtk_ax.SetCylinderRadius(5e-3*l0)

        # Create VTK two-dimensional property
        p2d = vtkProperty2D()
        p2d.SetDisplayLocationToBackground()

        vtkModule.__init__(self, self.vtk_ax, p2d)

        # Create VTK text property and apply to axes
        vtk_textproperty = vtkTextProperty()
        vtk_textproperty.SetFontSize(14)
        vtk_textproperty.SetBold(True)
        vtk_textproperty.SetItalic(True)
        vtk_textproperty.SetShadow(True)
        vtk_textproperty.SetJustificationToRight()
        vtk_textproperty.SetVerticalJustificationToCentered()

        self.set_text_property(vtk_textproperty)
Ejemplo n.º 9
0
    def do_test(self):
        prop = vtk.vtkTextProperty()

        set_font("Arial", prop)
        if prop.GetFontFamily() != vtk.VTK_ARIAL:
            print "Font was not set to Arial"
            return

        set_font("Courier", prop)
        if prop.GetFontFamily() != vtk.VTK_COURIER:
            print "Font was not set to Courier"
            return

        set_font("Times", prop)
        if prop.GetFontFamily() != vtk.VTK_TIMES:
            print "Font was not set to Times"
            return

        path = os.path.abspath("blex.ttf")
        set_font(path, prop)
        if prop.GetFontFamily() == vtk.VTK_FONT_FILE:
            if path != prop.GetFontFile():
                print "Set path incorrectly"
                return
        else:
            print "Did not set Font File correctly"
            return

        self.passed = 0
Ejemplo n.º 10
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()
Ejemplo n.º 11
0
    def addT2transvisualize(self, T2images, image_pos_pat, image_ori_pat, T2dims, T2spacing, sideBreast, interact):
        '''Added to build second reference frame and display T2 overlayed into T1 reference frame'''
        # Proceed to build reference frame for display objects based on DICOM coords   
        [transformed_T2image, transform_cube] = self.dicomTransform(T2images, image_pos_pat, image_ori_pat)
        
        #alignR = int(raw_input('\nAlign right? Yes:1 No:0 : '))
        #if alignR:
        if(sideBreast=="Right"):
            zf1 = self.T1spacing[2]*self.T1extent[5] + self.T1origin[2]
            self.T2origin[2] = zf1 - T2spacing[2]*self.T2extent[5] # this is z-span
        else:
            self.T2origin[2] = self.T1origin[2]
        
        # Change info origin
        translated_T2image = vtk.vtkImageChangeInformation()
        translated_T2image.SetInput( transformed_T2image )
        translated_T2image.SetOutputOrigin(self.T2origin)
        translated_T2image.Update()
        
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0.5, 0.5, 0)
        tprop.ShadowOff()
        
        # Update the reneder window to receive new image !Important*****
        self.renderer1.Modified()
        self.renWin1.Modified()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInput(translated_T2image.GetOutput())
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)
        
        ### Update T2Images
        t_T2images = vtk.vtkImageChangeInformation()
        t_T2images.SetInput( T2images )
        t_T2images.SetOutputOrigin(self.T2origin)
        t_T2images.Update()        

        ############                
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()
            
        return 
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
    def do_test(self):
        text_property = vtk.vtkTextProperty()
        text_property.SetFontFamilyToArial()
        text_property.SetFontSize(24)
        dpi = self.win.GetDPI()

        w, h = vcs.vtk_ui.text.text_dimensions("no descenders", text_property,
                                               dpi)
        if w != 174 or h != 23:
            print "no descenders width/height changed (%d,%d)"%(w,h)
            return

        w, h = vcs.vtk_ui.text.text_dimensions("couple good descenders",
                                               text_property, dpi)
        if w != 298 or h != 23:
            print "couple good descenders width/height changed (%d, %d)"%(w,h)
            return

        w, h = vcs.vtk_ui.text.text_dimensions(
              "This one\nis on\nmultiple lines", text_property, dpi)
        if w != 150 or h != 73:
            print "Multi-line width/height changed (%d,%d)"%(w,h)
            return

        self.passed = 0
Ejemplo n.º 14
0
Archivo: text.py Proyecto: NESII/uvcdat
    def __init__(self, interactor, text, index, dp, configurator):

        self.interactor = interactor
        self.text = text

        self.display = dp
        self.actors = dp.backend["vtk_backend_text_actors"]

        self.index = index
        self.configurator = configurator

        for actor in self.actors:
            actor.SetVisibility(0)

        self.textboxes = None

        self.toolbar = Toolbar(self.interactor, "Text Options")
        self.toolbar.add_slider_button(
            text.height,
            1,
            100,
            "Height",
            update=self.update_height)

        halign = self.toolbar.add_button(
            ["Left Align", "Center Align", "Right Align"], action=self.halign)
        valign = self.toolbar.add_button(
            ["Top Align", "Half Align", "Bottom Align"], action=self.valign)
        halign.set_state(self.text.halign)
        valign.set_state(__valign_map__[self.text.valign])

        self.toolbar.add_slider_button(
            text.angle,
            0,
            360,
            "Angle",
            update=self.update_angle)

        self.picker = None
        self.toolbar.add_button(["Change Color"], action=self.change_color)
        self.toolbar.show()

        prop = vtkTextProperty()
        prop.SetBackgroundColor(.87, .79, .55)
        prop.SetBackgroundOpacity(1)
        prop.SetColor(0, 0, 0)
        prop.SetVerticalJustificationToTop()
        self.tooltip = Label(
            self.interactor,
            "%s + Click to place new text." %
            ("Cmd" if sys.platform == "darwin" else "Ctrl"),
            textproperty=prop)
        self.tooltip.left = 0
        self.tooltip.top = self.interactor.GetRenderWindow(
        ).GetSize()[1] - self.tooltip.get_dimensions()[1]
        self.tooltip.show()
        super(TextEditor, self).__init__()
        self.register()
        self.update()
Ejemplo n.º 15
0
 def __init__(self):
     '''
     Constructor
     '''
     
     self.__OrientationMatrix = vtk.vtkMatrix4x4()
     self.__CornerAnnotation = vtk.vtkCornerAnnotation()
     self.__TextProperty = vtk.vtkTextProperty()
     self.__LookupTable = vtk.vtkLookupTable()
     self.__ScalarBarActor = vtk.vtkScalarBarActor()
     self.__Prop3DCollection = vtk.vtkProp3DCollection()
     self.__DataSetCollection = vtk.vtkDataSetCollection()
     self.__OrientationTransform = vtk.vtkMatrixToLinearTransform()
     
     self.__OrientationMatrix.Identity()
     self.__CornerAnnotation.SetNonlinearFontScaleFactor(0.30)
     self.__CornerAnnotation.SetText(0, "Jolly - (c) summit 2009 ref vtkINRIA3D")
     self.__CornerAnnotation.SetMaximumFontSize(46)
     
     self.__ScalarBarActor.SetLabelTextProperty(self.__TextProperty)
     
     self.__ScalarBarActor.GetLabelTextProperty().BoldOff()
     self.__ScalarBarActor.GetLabelTextProperty().ItalicOff()
     self.__ScalarBarActor.SetNumberOfLabels(3)
     self.__ScalarBarActor.SetWidth(0.1)
     self.__ScalarBarActor.SetHeight(0.5)
     self.__ScalarBarActor.SetPosition(0.9, 0.3)
     self.__LookupTable.SetTableRange(0, 1)
     self.__LookupTable.SetSaturationRange(0, 0)
     self.__LookupTable.SetHueRange(0, 0)
     self.__LookupTable.SetValueRange(0, 1)
     self.__LookupTable.Build()
     
     self.__ShowAnnotations = True
     self.__ShowScalarBar = True
     
     self.__OrientationTransform.SetInput(self.__OrientationMatrix)
     
     self.__WindowLevel = self.GetWindowLevel()
     self.__WindowLevel.SetLookupTable( self.__LookupTable )
     self.__ScalarBarActor.SetLookupTable(self.__LookupTable)
     
     self.__Renderer = self.GetRenderer()
     self.__Renderer.AddViewProp(self.__CornerAnnotation)
     self.__Renderer.AddViewProp(self.__ScalarBarActor)
     
     self.__ImageActor = self.GetImageActor()
     self.__RenderWindow = self.GetRenderWindow ()
     self.__InteractorStyle = self.GetInteractorStyle()
     self.__Interactor = None
     
     self.__CornerAnnotation.SetWindowLevel(self.__WindowLevel)
     self.__CornerAnnotation.SetImageActor(self.__ImageActor)
     self.__CornerAnnotation.ShowSliceAndImageOn()
     
     # Sometime we would want to set the default window/level value instead
     # of the ImageData's ScalarRange
     self.__RefWindow = None
     self.__RefLevel = None
Ejemplo n.º 16
0
    def update(self):
        if self.textboxes:

            for box in self.textboxes:
                box.stop_editing()
                box.detach()
            del self.textboxes

        self.textboxes = []
        renWin = self.interactor.GetRenderWindow()
        w, h = renWin.GetSize()
        dpi = renWin.GetDPI()
        cmap = vcs.getcolormap()

        prop = vtkTextProperty()
        vcs.vcs2vtk.prepTextProperty(prop, (w, h), to=self.text, tt=self.text, cmap=cmap)
        prop.SetOrientation(-1 * self.text.angle)

        for ind, x in enumerate(self.text.x):
            self.actors[ind].SetTextProperty(prop)

            y = self.text.y[ind]
            string = self.text.string[ind]

            text_width, text_height = text_dimensions(self.text, ind, (w, h),
                                                      dpi)

            x = x * w
            y = y * h

            box_prop = vtkTextProperty()
            vcs.vcs2vtk.prepTextProperty(box_prop, (w, h), to=self.text, tt=self.text, cmap=cmap)
            box_prop.SetOrientation(-1 * self.text.angle)
            text_color = box_prop.GetColor()
            highlight_color = vcs.vtk_ui.text.contrasting_color(*text_color)

            textbox = Textbox(self.interactor, string, highlight_color=highlight_color, highlight_opacity=.8, movable=True, on_editing_end=self.finished_editing, on_drag=self.moved_textbox, textproperty=box_prop, on_click=self.textbox_clicked)
            textbox.x = x
            textbox.y = y
            textbox.show()
            textbox.show_highlight()

            if ind == self.index:
                textbox.start_editing()

            self.textboxes.append(textbox)
Ejemplo n.º 17
0
Archivo: text.py Proyecto: NESII/uvcdat
def text_dimensions(text, text_prop, dpi, at_angle=0):
    ren = vtkTextRenderer()
    bounds = [0, 0, 0, 0]
    p = vtkTextProperty()
    p.ShallowCopy(text_prop)
    p.SetOrientation(at_angle)
    ren.GetBoundingBox(p, text, bounds, dpi)
    return bounds[1] - bounds[0] + 1, bounds[3] - bounds[2] + 1
Ejemplo n.º 18
0
 def textProperty(self, fontsize = 20):
     """Return properties for a text."""
     tprop = vtk.vtkTextProperty()
     tprop.SetColor(0., 0., 0.)
     tprop.SetFontSize(fontsize)
     tprop.SetFontFamilyToArial()
     tprop.BoldOff()
     return tprop
Ejemplo n.º 19
0
    def __init__(self, parent):
        QVTKRenderWindowInteractor.__init__(self, parent)

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

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

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

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

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

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

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

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

        self.renderer.GetActiveCamera().Pitch(90)     # Want effort to be vertical
        self.renderer.GetActiveCamera().OrthogonalizeViewUp()
        self.renderer.ResetCamera()
        self.renderer.GetActiveCamera().Elevation(15)  # Be slightly above the data
Ejemplo n.º 20
0
def text_dimensions(text, index, winsize, dpi):
    prop = vtkTextProperty()
    vcs.vcs2vtk.prepTextProperty(
        prop,
        winsize,
        text.To,
        text.Tt,
        vcs.getcolormap())
    return vcs.vtk_ui.text.text_dimensions(text.string[index], prop, dpi)
Ejemplo n.º 21
0
    def __init__(self, interactor, marker, index, display, configurator):
        self.interactor = interactor
        self.marker = marker
        self.index = index
        self.configurator = configurator

        actors = display.backend["vtk_backend_marker_actors"][index]

        self.glyph, self.glyph_source, self.polydata, self.actor, self.geo = actors

        self.display = display

        self.handles = []

        for ind, x in enumerate(marker.x[index]):
            y = marker.y[index][ind]
            h = vtk_ui.Handle(self.interactor, (x, y), dragged=self.adjust, color=(0,0,0), normalize=True)
            h.show()
            self.handles.append(h)

        self.toolbar = vtk_ui.toolbar.Toolbar(self.interactor, "Marker Options")
        self.toolbar.show()

        self.toolbar.add_button(["Change Color"], action=self.change_color)
        self.toolbar.add_slider_button(marker.size[index], 1, 300, "Marker Size", update=self.set_size)

        self.type_bar = self.toolbar.add_toolbar("Marker Type", open_label="Change")

        shapes = marker_shapes()

        shapes.insert(0, "Select Shape")
        self.shape_button = self.type_bar.add_button(shapes, action=self.change_shape)

        wmos = wmo_shapes()
        wmos.insert(0, "Select WMO Marker")

        self.wmo_button = self.type_bar.add_button(wmos, action=self.change_wmo)

        if self.marker.type[self.index] in shapes:
            self.shape_button.set_state(shapes.index(self.marker.type[self.index]))
        else:
            self.wmo_button.set_state(wmos.index(self.marker.type[self.index]))

        # Used to store the color picker when it's active
        self.picker = None
        prop = vtk.vtkTextProperty()
        prop.SetBackgroundColor(.87, .79, .55)
        prop.SetBackgroundOpacity(1)
        prop.SetColor(0, 0, 0)

        self.tooltip = vtk_ui.Label(self.interactor, "%s + Click to place new markers." % ("Cmd" if sys.platform == "darwin" else "Ctrl"), textproperty=prop)
        self.tooltip.left = 0
        self.tooltip.top = self.interactor.GetRenderWindow().GetSize()[1] - self.tooltip.get_dimensions()[1]
        self.tooltip.show()
        super(MarkerEditor, self).__init__()
        self.register()
	def __init__(self, parent, visualizer, **kws):
		"""
		Initialization
		"""
		self.x, self.y, self.z = -1, -1, -1
		self.renew = 1
		self.mapper = vtk.vtkPolyDataMapper()
		self.axes = None
		VisualizationModule.__init__(self, parent, visualizer, **kws)
		iactor = self.wxrenwin.GetRenderWindow().GetInteractor()

		self.descs = {"X": "X axis", "Y": "Y axis", "Z": "Z axis"}
		self.axes = axes = vtk.vtkAxesActor()
		axes.SetShaftTypeToCylinder()
		axes.SetXAxisLabelText("X")
		axes.SetYAxisLabelText("Y")
		axes.SetZAxisLabelText("Z")
		axes.SetTotalLength(2.0, 2.0, 2.0)
		self.length = math.sqrt(2.0**2 + 2.0**2 + 2.0**2)
		
		tprop = vtk.vtkTextProperty()
		tprop.ItalicOn()
		tprop.ShadowOn()
		tprop.SetFontFamilyToTimes()
		axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(tprop)
		tprop2 = vtk.vtkTextProperty()
		tprop2.ShallowCopy(tprop)
		axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(tprop2)
		tprop3 = vtk.vtkTextProperty()
		tprop3.ShallowCopy(tprop)
		axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(tprop3)  
		self.renderer = self.parent.getRenderer()
		self.actor = self.axes
		self.marker = vtk.vtkOrientationMarkerWidget()
		self.marker.SetOutlineColor(0.93, 0.57, 0.13)
		self.marker.SetOrientationMarker(axes)
		self.marker.SetViewport(0.0, 0.0, 0.2, 0.2)
		
		self.marker.SetInteractor(iactor)
		self.marker.SetEnabled(1)
		self.marker.InteractiveOff()
		self.filterDesc = "Add axes in 3D view"
Ejemplo n.º 23
0
    def init_buttons(self):
        # An "off" and "on" state
        states = [vtk_ui.button.ButtonState(bgcolor=x) for x in ((.5, .5, .5), (.75, .75, .75))]

        prop = vtk.vtkTextProperty()
        prop.SetBackgroundColor(.87, .79, .55)
        prop.SetBackgroundOpacity(1)
        prop.SetColor(0, 0, 0)

        self.text_button = vtk_ui.button.Button(self.interactor, states=states, image=os.path.join(sys.prefix, "share", "vcs", "text_icon.png"), top=10, left=10, halign=vtk_ui.button.RIGHT_ALIGN, action=self.text_click, tooltip="Create Text: click to place.", tooltip_property=prop)
        self.marker_button = vtk_ui.button.Button(self.interactor, states=states, image=os.path.join(sys.prefix, "share", "vcs", "marker_icon.png"), top=10, left=63, halign=vtk_ui.button.RIGHT_ALIGN, action=self.marker_click, tooltip="Create Marker: click to place.", tooltip_property=prop)
 def __init__(self,data_reader,scalar_bar_number):
     # Create a colorscale lookup table
     self.lut=vtk.vtkLookupTable()
     self.lut.SetNumberOfColors(256)
     self.lut.SetTableRange(data_reader.get_scalar_range())
     self.lut.SetHueRange(0,1)
     self.lut.SetRange(data_reader.get_scalar_range())
     self.lut.Build()
     self.actor= vtk.vtkScalarBarActor()
     self.actor.SetOrientationToVertical()
     self.actor.SetPosition( 0.9, 0.77-0.25*scalar_bar_number)
     self.actor.SetPosition2( 0.09, 0.24 )
     self.propT = vtk.vtkTextProperty()
     self.propL = vtk.vtkTextProperty()
     self.propT.SetFontFamilyToArial()
     self.propT.SetColor(0.5,0.5,0.5)
     self.propT.ItalicOff()
     self.propT.BoldOn()
     self.propL.BoldOff()
     self.actor.SetLookupTable(self.lut)
Ejemplo n.º 25
0
    def visualize_map(self, VOIclip):
        # get info from image before visualization
        VOIclip.UpdateInformation()
        self.dims = VOIclip.GetDimensions()
        (xMin, xMax, yMin, yMax, zMin, zMax) = VOIclip.GetWholeExtent()
        self.spacing = VOIclip.GetSpacing()

        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInput( VOIclip )
        self.xImagePlaneWidget.SetPlaneOrientationToXAxes()
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInput( VOIclip )
        self.yImagePlaneWidget.SetPlaneOrientationToYAxes()
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInput( VOIclip )
        self.zImagePlaneWidget.SetPlaneOrientationToZAxes()
        self.zImagePlaneWidget.SetSliceIndex(0)
                
        self.xImagePlaneWidget.On()
        self.yImagePlaneWidget.On()
        self.zImagePlaneWidget.On()
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(1, 1, 1)
        tprop.ShadowOff()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axes = vtk.vtkCubeAxesActor2D()
        axes.SetInput(VOIclip)
        axes.SetCamera(self.renderer1.GetActiveCamera())
        axes.SetLabelFormat("%6.4g")
        axes.SetFlyModeToOuterEdges()
        axes.SetFontFactor(1.2)
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axes)
        
        ############
        # bounds and initialize camera
        bounds = VOIclip.GetBounds()
        self.renderer1.ResetCamera(bounds)    
        self.renderer1.ResetCameraClippingRange()
        self.camera.SetViewUp(0.0,-1.0,0.0)
        self.camera.Azimuth(360)
        
        # Initizalize
        #self.renWin1.Render()
        self.renderer1.Render()
        self.iren1.Start()  
                            
        return
Ejemplo n.º 26
0
    def _create_species_legend(self):
        species_legend = vtk.vtkLegendBoxActor()
        # Get number of lines
        legend_line_numbers = len(self._mapped_species_idset) \
                            + len(domain_kind_constants.DOMAIN_KIND_NAME)

        # Create legend actor
        species_legend.SetNumberOfEntries(legend_line_numbers)
        species_legend.SetPosition(
            self._get_legend_position(
                self.settings.species_legend_location,
                self.settings.species_legend_height,
                self.settings.species_legend_width,
                self.settings.species_legend_offset))
        species_legend.SetWidth(self.settings.species_legend_width)
        species_legend.SetHeight(self.settings.species_legend_height)

        tprop = vtk.vtkTextProperty()
        tprop.SetColor(rgb_colors.RGB_WHITE)
        tprop.SetVerticalJustificationToCentered()

        species_legend.SetEntryTextProperty(tprop)

        if self.settings.species_legend_border_display:
            species_legend.BorderOn()
        else:
            species_legend.BorderOff()

        # Entry legend string to the actor
        sphere = vtk.vtkSphereSource()

        # Create legends of particle speices
        count = 0
        for species_id in self._mapped_species_idset:
            species_legend.SetEntryColor \
                (count, self._pattrs[species_id]['color'])
            species_legend.SetEntryString \
                (count, self._pattrs[species_id]['name'])
            species_legend.SetEntrySymbol(count, sphere.GetOutput())
            count += 1

        # Create legends of shell spesies
        offset = count
        count = 0
        for kind, name in domain_kind_constants.DOMAIN_KIND_NAME.items():
            species_legend.SetEntryColor \
                (offset + count, self._get_domain_color(kind))
            species_legend.SetEntrySymbol \
                (offset + count, sphere.GetOutput())
            species_legend.SetEntryString(offset + count, name)
            count += 1
        return species_legend
    def get_default_text_prop(self):
        """
        Sets up and returns the default text properties for text display
        """
        # set up the default text properties for nice text
        font_size = 10
        text_prop = vtkTextProperty()
        text_prop.SetFontSize(font_size)
        text_prop.SetFontFamilyToArial()
        text_prop.BoldOff()
        text_prop.ItalicOff()
        text_prop.ShadowOff()

        return text_prop
Ejemplo n.º 28
0
def  addaxeswithlabels(length=(1,1,1),labelx="x",labely="y",labelz="z"):
    
    axes=vtk.vtkAxesActor()
    #axes.SetShaftTypeToCylinder()
    axes.SetXAxisLabelText(labelx)
    axes.SetYAxisLabelText(labely)
    axes.SetZAxisLabelText(labelz)    
    axes.SetTotalLength(length)
    
    tprop = vtk.vtkTextProperty()
    tprop.ItalicOn()
    tprop.ShadowOn()
    tprop.SetFontFamilyToTimes()
    axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(tprop)
    
    tprop2 = vtk.vtkTextProperty()
    tprop2.ShallowCopy(tprop)
    axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(tprop2)

    tprop3 = vtk.vtkTextProperty()
    tprop3.ShallowCopy(tprop)
    axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(tprop3)
    
    return axes
Ejemplo n.º 29
0
Archivo: epdp.py Proyecto: ecell/newio
    def __create_axes(self):
        axes = vtk.vtkCubeAxesActor2D()
        axes.SetBounds(numpy.array([0.0, 1.0, 0.0, 1.0, 0.0, 1.0]) * self.settings.scaling)
        axes.SetRanges(0.0, self.__world_size, 0.0, self.__world_size, 0.0, self.__world_size)
        axes.SetLabelFormat("%g")
        axes.SetFontFactor(1.5)
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(self.settings.axis_annotation_color)
        tprop.ShadowOn()
        axes.SetAxisTitleTextProperty(tprop)
        axes.SetAxisLabelTextProperty(tprop)
        axes.UseRangesOn()
        axes.SetCornerOffset(0.0)

        return axes
Ejemplo n.º 30
0
 def ShowLabel(self):
   self.tprop = vtk.vtkTextProperty()
   size = self.GetSize()
   #self.text_label.ScaledTextOn()
   self.text_label.SetPosition(10, size[1] - 12)
   self.text_label.SetInput(self.label_t) 
   self.tprop.SetFontSize(12)
   self.tprop.SetFontFamilyToArial()
   self.tprop.SetJustificationToLeft()
   #self.tprop.BoldOn()
   #self.tprop.ItalicOn()
   self.tprop.ShadowOn()
   self.tprop.SetColor(0.9, 0.8, 0.8)
   self.text_label.SetTextProperty(self.tprop)
   self.AddActor2D(self.text_label)
Ejemplo n.º 31
0
def neuron3d(neuron_graph,
             label_nodes=[],
             labels=[],
             priorities=[],
             nodecolor=nodecolor_4cp,
             background=(0, 0, 0),
             lines=False,
             stereo=False,
             axes=True,
             fullscreen=True):
    """axes: If true, show axis with scale bar info
    """
    renderer, actor = nrngraph2vtk(neuron_graph,
                                   label_nodes=label_nodes,
                                   labels=labels,
                                   priorities=priorities,
                                   nodecolor=nodecolor,
                                   background=background,
                                   lines=lines)
    if axes:  # show axis with scale bar info
        _ax = vtk.vtkCubeAxesActor2D()
        _ax.SetLabelFormat('%3.0f')
        _ax.SetNumberOfLabels(0)
        _ax.SetYAxisVisibility(False)
        _ax.SetZAxisVisibility(False)
        _ax.SetBounds(0, 200, -600, -400, 0, 200)
        _ax.SetXLabel('')
        _ax.SetXOrigin(0)
        _ax.SetYOrigin(-600)
        _ax.SetZOrigin(0)
        color = (1.0 - background[0], 1.0 - background[1], 1.0 - background[2])
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(color)
        _ax.SetAxisLabelTextProperty(tprop)
        _ax.GetProperty().SetColor(*color)
        _ax.SetFlyModeToClosestTriad()
        _ax.SetCamera(renderer.GetActiveCamera())
        renderer.AddActor(_ax)
    renderer.ResetCamera()
    win = vtk.vtkRenderWindow()
    win.AddRenderer(renderer)
    if fullscreen:
        win.FullScreenOn()
    if stereo:
        win.GetStereoCapableWindow()
        win.StereoCapableWindowOn()
        win.SetStereoRender(1)
        win.SetStereoTypeToCrystalEyes()
        win.SetFullScreen(1)
        #win.SetStereoTypeToRedBlue()

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

    win.Render()

    # exporter = vtk.vtkX3DExporter()
    # exporter.SetFileName('ggn.x3d')
    # exporter.SetRenderWindow(win)
    # exporter.Write()

    interactor.Initialize()
    interactor.Start()
Ejemplo n.º 32
0
    def GeometricObjects(self):

        GeometricObjects = list()
        GeometricObjects.append(vtk.vtkArrowSource())
        GeometricObjects.append(vtk.vtkConeSource())
        GeometricObjects.append(vtk.vtkCubeSource())
        GeometricObjects.append(vtk.vtkCylinderSource())
        GeometricObjects.append(vtk.vtkDiskSource())
        GeometricObjects.append(vtk.vtkLineSource())
        GeometricObjects.append(vtk.vtkRegularPolygonSource())
        GeometricObjects.append(vtk.vtkSphereSource())

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

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

        # Create a parametric function source, renderer, mapper
        # and actor for each object.
        for idx, item in enumerate(GeometricObjects):
            GeometricObjects[idx].Update()

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(
                GeometricObjects[idx].GetOutputPort())

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

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

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

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 3

        for idx in range(len(GeometricObjects)):
            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(GeometricObjects) - 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()
Ejemplo n.º 33
0
def main():
    colors = vtk.vtkNamedColors()

    planes = list()
    titles = list()

    # Using frustum planes.
    titles.append('Using frustum planes')
    camera = vtk.vtkCamera()
    planesArray = [0] * 24
    camera.GetFrustumPlanes(1, planesArray)
    planes.append(vtk.vtkPlanes())
    planes[0].SetFrustumPlanes(planesArray)

    # Using bounds.
    titles.append('Using bounds')
    sphereSource = vtk.vtkSphereSource()
    sphereSource.Update()
    bounds = [0] * 6
    sphereSource.GetOutput().GetBounds(bounds)
    planes.append(vtk.vtkPlanes())
    planes[1].SetBounds(bounds)

    # At this point we have the planes created by both of the methods above.
    # You can do whatever you want with them.

    # For visualisation we will produce an n-sided convex hull
    # and visualise it.

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

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

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

    hulls = list()
    pds = list()
    mappers = list()
    actors = list()
    renderers = list()
    textMappers = list()
    textActors = list()
    for i in range(0, len(planes)):
        hulls.append(vtk.vtkHull())
        hulls[i].SetPlanes(planes[i])

        pds.append(vtk.vtkPolyData())

        # To generate the convex hull we supply a vtkPolyData object and a bounding box.
        # We define the bounding box to be where we expect the resulting polyhedron to lie.
        # Make it a generous fit as it is only used to create the initial
        # polygons that are eventually clipped.
        hulls[i].GenerateHull(pds[i], -200, 200, -200, 200, -200, 200)

        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputData(pds[i])

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d('Moccasin'))
        actors[i].GetProperty().SetSpecular(0.8)
        actors[i].GetProperty().SetSpecularPower(30)

        renderers.append(vtk.vtkRenderer())
        renderers[i].AddActor(actors[i])

        textMappers.append(vtk.vtkTextMapper())
        textMappers[i].SetInput(titles[i])
        textMappers[i].SetTextProperty(textProperty)

        textActors.append(vtk.vtkActor2D())
        textActors[i].SetMapper(textMappers[i])
        textActors[i].SetPosition(100, 10)
        renderers[i].AddViewProp(textActors[i])

        renWin.AddRenderer(renderers[i])

    # Setup the viewports
    xGridDimensions = 2
    yGridDimensions = 1
    rendererSize = 300
    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('DarkSlateGray'))
                ren.SetViewport(viewport)
                renWin.AddRenderer(ren)
                continue

            renderers[index].SetViewport(viewport)
            renderers[index].SetBackground(colors.GetColor3d('DarkSlateGray'))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(-30)
            renderers[index].ResetCameraClippingRange()

    iRen.Initialize()
    renWin.Render()
    iRen.Start()
Ejemplo n.º 34
0
    def __init__(self, widget=None):
        """
        Nueva visuaización de corte
        @param widget: el widget donde se muestra la visualizición, si es None se crea uno nuevo
        """
        if widget is None:
            widget = SliceVisualizationWidget()
        super(SliceVisualization, self).__init__(widget)

        self._image = None  #imagen que se muesta en la visualización
        self._view = CanonicalSliceView(
        )  #esta es la vista de esta visualización
        self._ui = self._widget.ui  #interfaz del widget
        ui = self._ui
        #conexión de señales de Qt
        ui.sliceSelector.valueChanged.connect(self._setSliceNumLabel)
        ui.sliceNum.editingFinished.connect(self._setSliceNumSlider)
        #cambiar el evento 'resize' del widget de esta visualización para agregarle el reseteo de la cámara
        widget.resizeEvent = self._widget_resized

        #propiedad para definir el color de las líneas
        self._lines_color_prop = vtk.vtkProperty()
        self._lines_color_prop.SetColor(1, 1, 0)  #amarillo por defecto

        #líneas que muestran un pick point
        #línea vertical
        self._vLine = vtk.vtkLineSource()
        vLineMapper = vtk.vtkPolyDataMapper()
        vLineMapper.SetInput(self._vLine.GetOutput())
        self._vLineActor = vtk.vtkActor()  #actor de la línea vertical
        self._vLineActor.SetMapper(vLineMapper)
        self._vLineActor.SetProperty(
            self._lines_color_prop)  #esta línea se verá de color rojo
        self._vLineActor.VisibilityOff(
        )  #por defecto esta línea no se muestra
        #línea horizontal
        self._hLine = vtk.vtkLineSource()
        hLineMapper = vtk.vtkPolyDataMapper()
        hLineMapper.SetInput(self._hLine.GetOutput())
        self._hLineActor = vtk.vtkActor()  #actor de la línea horizontal
        self._hLineActor.SetMapper(hLineMapper)
        self._hLineActor.SetProperty(
            self._lines_color_prop)  #esta línea se verá de color rojo
        self._hLineActor.VisibilityOff(
        )  #por defecto esta línea no se muestra

        #posición seleccionada
        self._selected_position = (0, 0, 0)  #valor por defecto
        self._selected_value = 0  #valor del punto seleccionado
        self._picked_position = (0, 0, 0)

        #texto a mostrar en el widget
        self._textActor = vtk.vtkTextActor()
        self._text_color_prop = vtk.vtkTextProperty(
        )  #propiedad que maneja el color del texto
        self._text_color_prop.SetColor(1, 1, 0)  #azul por defecto
        self._textActor.SetTextProperty(
            self._text_color_prop)  #el texto se verá amarillo
        self._textActor.VisibilityOff()  #por defecto el texto no se ve

        axises = ["X", "Y", "Z"]  #letras de los ejes
        #conexión de las señales de Qt relativas a los botones de cambio de ejes verticales
        #self._signalMapper = QSignalMapper(self._widget)
        #self._signalMapper.connect(self._signalMapper, SIGNAL("mapped(QString)"), self._setVerticalAxis)

        self._ui.XButton.clicked.connect(self._setXVerticalAxis)
        self._ui.YButton.clicked.connect(self._setYVerticalAxis)
        self._ui.ZButton.clicked.connect(self._setZVerticalAxis)

        #for button, axis in zip(self._getButtons()[:3], axises):
        #    button.clicked.connect(self._signalMapper.map)
        #    self._signalMapper.setMapping(button, axis)

        #conexión de las señales de Qt relativas a los botones de cambio de ejes horizontales
        #self._signalMapper_2 = QSignalMapper(self._widget)
        #self._signalMapper_2.connect(self._signalMapper_2, SIGNAL("mapped(QString)"), self._setHorizontalAxis)

        self._ui.XButton_2.clicked.connect(self._setXHorizontalAxis)
        self._ui.YButton_2.clicked.connect(self._setYHorizontalAxis)
        self._ui.ZButton_2.clicked.connect(self._setZHorizontalAxis)

        #for button, axis in zip(self._getButtons()[3:], axises):
        #    button.clicked.connect(self._signalMapper_2.map)
        #    self._signalMapper_2.setMapping(button, axis)

        #estados de la inversión de los ejes
        self._HInvert = False  #por defecto no se invierte
        self._VInvert = False  #por defecto no se invierte
        ui.invert.stateChanged.connect(self._setVInvert)
        ui.invert_2.stateChanged.connect(self._setHInvert)

        self._horizontalAxis = "X"  #eje representado horizontalmente
        self._verticalAxis = "Y"  #eje representado verticalmente

        #selector usado en esta visalización
        self._picker = vtk.vtkPointPicker(
        )  #de tipo vtkPointPicker para seleccionar puntos
        #para observar el evento de selección con prioridad 9
        self._picker.AddObserver("EndPickEvent", self._onPickEvent, 9)

        self._iren = ui.visualization  #el Interactor es el que esta en la interfaz del widget
        self._init_interactor()  #incializar la visualización
        #agregar los actores de las líneas
        self._render.AddActor(self._vLineActor)
        self._render.AddActor(self._hLineActor)
        #agregar el actor del texto
        self._render.AddActor(self._textActor)
        #fijar el selector del interactor
        self._iren.SetPicker(self._picker)
        #el  estilo del interactor es de tipo imagen
        self._iren.SetInteractorStyle(vtk.vtkInteractorStyleImage())
        #observar el vento de click iz\quiero para lanzar el evento de selección
        self._iren.AddObserver("LeftButtonPressEvent", self._raisePickEvent)
        #quitar los observadores de eventos de teclado.
        #para eliminar los siguientes observadores indeseados:
        #  - pick event con p
        #  - cambiar el estilo del interactor con j o t
        #  -y otros pesaitos como w,e,f,s etc.
        # (ver cometarios de QVTKRenderWindowInteractor para más información)
        self._iren.RemoveObservers("KeyPressEvent")
        self._iren.RemoveObservers("CharEvent")
Ejemplo n.º 35
0
    def place_cursor(self):
        # Find current position of the text actor
        x, y = self.left, self.top

        # Use to adjust all window-space numbers
        w, h = self.interactor.GetRenderWindow().GetSize()

        # Translate distance from top to distance from bottom
        y = h - y

        # Prep a text property for getting measurements
        prop = vtk.vtkTextProperty()
        prop.ShallowCopy(self.actor.GetTextProperty())

        # Store for rotating the cursor's coords
        angle = prop.GetOrientation()

        # Reset so we get accurate dimensions
        prop.SetOrientation(0)

        rows = self.text.split("\n")

        dpi = self.interactor.GetRenderWindow().GetDPI()
        width, height = text_dimensions(self.text, prop, dpi)
        line_height = float(height) / len(rows)

        column_adjustment, _ = text_dimensions(rows[self.row][:self.column],
                                               prop, dpi)

        x += column_adjustment

        row_width, _ = text_dimensions(rows[self.row], prop, dpi)

        # Adjust for blank space caused by justifications
        halign = prop.GetJustificationAsString()
        if halign == "Centered":
            x += (width - row_width) / 2.
        elif halign == "Right":
            x += (width - row_width) + 1  # Adjust for some margin issues
        elif halign == "Left":
            x -= 3  # Adjust for some margin issues

        # Manual adjustments for justification artefacts
        valign = prop.GetVerticalJustificationAsString()
        if valign == "Top":
            y += 2
        elif valign == "Centered":
            pass
        elif valign == "Bottom":
            y -= 2

        # Get to the current row
        y -= line_height * self.row

        # Rotate both points to the orientation as the text
        y1 = y
        y2 = y - line_height

        x1 = x
        x2 = x

        x1, x2 = x1 - self.x, x2 - self.x
        y1, y2 = y1 - self.y, y2 - self.y

        x1, y1 = rotate((x1, y1), angle)
        x2, y2 = rotate((x2, y2), angle)

        x1 += self.x
        x2 += self.x
        y1 += self.y
        y2 += self.y

        self.cursor.point_1 = (x1, y1)
        self.cursor.point_2 = (x2, y2)
Ejemplo n.º 36
0
isoSurface = vtk.vtkContourFilter()
isoSurface.SetInputConnection(reader.GetOutputPort())
# valor inicial
val = 0.5
isoSurface.SetValue(0, val)
#
surfaceMapper = vtk.vtkPolyDataMapper()
surfaceMapper.SetLookupTable(paleta)
surfaceMapper.SetInputConnection(isoSurface.GetOutputPort())
surfaceActor = vtk.vtkActor()
surfaceActor.SetMapper(surfaceMapper)

# probabilidade
textActor = vtk.vtkTextActor()
# propriedades do texto da probabilidade
prop_texto = vtk.vtkTextProperty()
prop_texto.SetFontSize(40)
textActor.SetTextProperty(prop_texto)
pos_texto = textActor.GetPositionCoordinate()
pos_texto.SetCoordinateSystemToNormalizedViewport()
pos_texto.SetValue(0.01, 0.9)
prop_texto.SetColor(paleta.GetColor(val))
textActor.SetInput("%.2f" % (val))

# renderer and render window
ren = vtk.vtkRenderer()
ren.SetBackground(.8, .8, .8)
renWin = vtk.vtkRenderWindow()
renWin.SetSize(400, 400)
renWin.AddRenderer(ren)
Ejemplo n.º 37
0
#
# All Plot3D scalar functions
#
# Create the RenderWindow, Renderer and both Actors
#
renWin = vtk.vtkRenderWindow()
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
scalarLabels = "Density Pressure Temperature Enthalpy Internal_Energy Kinetic_Energy Velocity_Magnitude Stagnation_Energy Entropy Swirl"
scalarFunctions = "100 110 120 130 140 144 153 163 170 184"
camera = vtk.vtkCamera()
light = vtk.vtkLight()
math = vtk.vtkMath()
# All text actors will share the same text prop
textProp = vtk.vtkTextProperty()
textProp.SetFontSize(10)
textProp.SetFontFamilyToArial()
textProp.SetColor(0, 0, 0)
i = 0
for scalarFunction in scalarFunctions.split():
    locals()[get_variable_name("pl3d", scalarFunction,
                               "")] = vtk.vtkMultiBlockPLOT3DReader()
    locals()[get_variable_name("pl3d", scalarFunction,
                               "")].SetXYZFileName("" + str(VTK_DATA_ROOT) +
                                                   "/Data/bluntfinxyz.bin")
    locals()[get_variable_name("pl3d", scalarFunction,
                               "")].SetQFileName("" + str(VTK_DATA_ROOT) +
                                                 "/Data/bluntfinq.bin")
    locals()[get_variable_name(
        "pl3d", scalarFunction, "")].SetScalarFunctionNumber(
Ejemplo n.º 38
0
    def ParametricObjects(self):

        parametricObjects = list()
        parametricObjects.append(vtk.vtkParametricBoy())
        parametricObjects.append(vtk.vtkParametricConicSpiral())
        parametricObjects.append(vtk.vtkParametricCrossCap())
        parametricObjects.append(vtk.vtkParametricDini())

        parametricObjects.append(vtk.vtkParametricEllipsoid())
        parametricObjects[-1].SetXRadius(0.5)
        parametricObjects[-1].SetYRadius(2.0)
        parametricObjects.append(vtk.vtkParametricEnneper())
        parametricObjects.append(vtk.vtkParametricFigure8Klein())
        parametricObjects.append(vtk.vtkParametricKlein())

        parametricObjects.append(vtk.vtkParametricMobius())
        parametricObjects.append(vtk.vtkParametricRandomHills())
        parametricObjects[-1].AllowRandomGenerationOff()
        parametricObjects.append(vtk.vtkParametricRoman())
        parametricObjects.append(vtk.vtkParametricSuperEllipsoid())
        parametricObjects[-1].SetN1(0.5)
        parametricObjects[-1].SetN2(0.1)

        parametricObjects.append(vtk.vtkParametricSuperToroid())
        parametricObjects[-1].SetN1(0.2)
        parametricObjects[-1].SetN2(3.0)
        parametricObjects.append(vtk.vtkParametricTorus())
        parametricObjects.append(vtk.vtkParametricSpline())
        # Add some points to the parametric spline.
        # You can use vtkRandom instead of the python random methods.
        inputPoints = vtk.vtkPoints()
        random.seed(8775070)
        for i in range(10):
            x = random.uniform(0.0, 1.0)
            y = random.uniform(0.0, 1.0)
            z = random.uniform(0.0, 1.0)
            inputPoints.InsertNextPoint(x, y, z)
        parametricObjects[-1].SetPoints(inputPoints)

        # There are only 15 objects.
        #parametricObjects.append(vtk.??)

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

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

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

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

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

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

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

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 4

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

        rendererSize = 200

        # 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(parametricObjects) - 1):
                    continue

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

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.2, 0.3, 0.4)
                renderers[idx].ResetCamera()
                renderers[idx].GetActiveCamera().Azimuth(30)
                renderers[idx].GetActiveCamera().Elevation(-30)
                renderers[idx].ResetCameraClippingRange()

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

        renderWindow.Render()

        interactor.Start()
Ejemplo n.º 39
0
def render(Data1, Data2, point):

    ren = vtk.vtkRenderer()
    ren.SetBackground(.1, .2, .5)
    ren2dimg1 = vtk.vtkRenderer()
    ren2dimg2 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.AddRenderer(ren2dimg1)
    renWin.AddRenderer(ren2dimg2)
    renWin.SetSize(1536, 1024)

    # Create a render window
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    pts = vtk.vtkPoints()

    [img1_position, img2_position, epi_point1,
     epi_point2] = epigeometry_points(pts, point, Data1, Data2)

    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    colors.SetName("Colors")

    lines = vtk.vtkCellArray()

    add_3dline(lines, pts, 0, 1, colors, 'r')
    add_3dline(lines, pts, 2, 3, colors, 'g')
    add_3dline(lines, pts, 1, 4, colors, 'w')
    add_3dline(lines, pts, 3, 5, colors, 'w')
    add_3dline(lines, pts, 3, 6, colors, 'w')
    add_3dline(lines, pts, 5, 6, colors, 'w')

    linesPolyData = vtk.vtkPolyData()
    linesPolyData.SetPoints(pts)
    linesPolyData.SetLines(lines)
    linesPolyData.GetCellData().SetScalars(colors)

    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(linesPolyData)
    else:
        mapper.SetInputData(linesPolyData)
    lineactor = vtk.vtkActor()
    lineactor.SetMapper(mapper)

    img1 = Data1.img.copy()
    img2 = Data2.img.copy()

    cv2.circle(img1, (point[0], point[1]), 10, (255, 0, 0), -1)
    cv2.line(img2, (int(epi_point1[0]), int(epi_point1[1])),
             (int(epi_point2[0]), int(epi_point2[1])), (255, 0, 0), 5)
    cv2.putText(
        img1,
        str(int(np.rad2deg(Data1.PA))) + ', ' + str(int(np.rad2deg(Data1.SA))),
        (10, 100), 1, 4, (255, 255, 255), 2, cv2.LINE_AA)
    cv2.putText(
        img2,
        str(int(np.rad2deg(Data2.PA))) + ', ' + str(int(np.rad2deg(Data2.SA))),
        (10, 100), 1, 4, (255, 255, 255), 2, cv2.LINE_AA)

    reader1 = vtkImageImportFromArray()
    reader1.SetArray(img1)
    reader1.Update()
    fliper1 = vtk.vtkImageFlip()
    fliper1.SetFilteredAxis(1)
    fliper1.SetInputConnection(reader1.GetOutputPort())
    fliper1.Update()

    reader2 = vtkImageImportFromArray()
    reader2.SetArray(img2)
    reader2.Update()
    fliper2 = vtk.vtkImageFlip()
    fliper2.SetFilteredAxis(1)
    fliper2.SetInputConnection(reader2.GetOutputPort())
    fliper2.Update()

    # transform1 = vtk.vtkTransform()
    # transform1.Translate(img1_position)
    # transform1.RotateY(np.rad2deg(Data1.PA))
    # transform1.RotateX(-np.rad2deg(Data1.SA))
    # transform1.Scale(img1.shape[0]*Data1.PS[0],img1.shape[1]*Data1.PS[1],1)

    # transform2 = vtk.vtkTransform()
    # transform2.Translate(img2_position)
    # transform2.RotateY(np.rad2deg(Data2.PA))
    # transform2.RotateZ(-np.rad2deg(Data2.SA))
    # transform2.Scale(img2.shape[0]*Data2.PS[0],img2.shape[1]*Data2.PS[1],1)

    planeA_actor = createQuad(img1)
    planeA_actor.SetPosition(img1_position)
    planeA_actor.SetScale(Data1.PS[0], Data1.PS[1], 1)
    planeA_actor.RotateY(np.rad2deg(Data1.PA))
    planeA_actor.RotateX(-np.rad2deg(Data1.SA))
    # planeA_actor.SetUserTransform(transform1)

    planeB_actor = createQuad(img2)
    planeB_actor.SetPosition(img2_position)
    planeB_actor.SetScale(Data2.PS[0], Data2.PS[1], 1)
    planeB_actor.RotateY(np.rad2deg(Data2.PA))
    planeB_actor.RotateZ(-np.rad2deg(Data2.SA))
    # planeB_actor.SetUserTransform(transform2)

    axes = vtk.vtkAxesActor()
    transform = vtk.vtkTransform()
    transform.Scale(100, 100, 100)
    axes.SetUserTransform(transform)

    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(25)
    textProperty.SetJustificationToCentered()

    textMapper = vtk.vtkTextMapper()
    textActor = vtk.vtkActor2D()
    textMapper.SetInput('Epipolar Geometry')
    textMapper.SetTextProperty(textProperty)
    textActor.SetMapper(textMapper)
    textActor.SetPosition(512, 950)

    ren.AddActor(lineactor)
    ren.AddActor(planeA_actor)
    ren.AddActor(planeB_actor)
    ren.AddActor(axes)
    ren.AddViewProp(textActor)
    ren.SetViewport([0.0, 0.0, 2 / 3, 1.0])

    mapper2d1 = vtk.vtkImageMapper()
    mapper2d1.SetInputConnection(fliper1.GetOutputPort())
    mapper2d1.SetColorWindow(255)
    mapper2d1.SetColorLevel(127.5)
    actor2d1 = vtk.vtkActor2D()
    actor2d1.SetMapper(mapper2d1)
    ren2dimg1.AddActor2D(actor2d1)
    ren2dimg1.SetViewport([2 / 3, 0.5, 1.0, 1.0])

    mapper2d2 = vtk.vtkImageMapper()
    mapper2d2.SetInputConnection(fliper2.GetOutputPort())
    mapper2d2.SetColorWindow(255)
    mapper2d2.SetColorLevel(127.5)
    actor2d2 = vtk.vtkActor2D()
    actor2d2.SetMapper(mapper2d2)
    ren2dimg2.AddActor2D(actor2d2)
    ren2dimg2.SetViewport([2 / 3, 0.0, 1.0, 0.5])

    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 40
0
    def text(
        self,
        txt,
        pos=(0, 0, 0),
        s=1,
        c=None,
        alpha=1,
        bg=None,
        font="Gula",
        dpi=500,
        justify="bottom-left",
    ):
        """Build an image from a string."""

        if c is None:  # automatic black or white
            if settings.plotter_instance and settings.plotter_instance.renderer:
                c = (0.9, 0.9, 0.9)
                if np.sum(settings.plotter_instance.renderer.GetBackground()
                          ) > 1.5:
                    c = (0.1, 0.1, 0.1)
            else:
                c = (0.3, 0.3, 0.3)

        r = vtk.vtkTextRenderer()
        img = vtk.vtkImageData()

        tp = vtk.vtkTextProperty()
        tp.BoldOff()
        tp.SetColor(colors.getColor(c))
        tp.SetJustificationToLeft()
        if "top" in justify:
            tp.SetVerticalJustificationToTop()
        if "bottom" in justify:
            tp.SetVerticalJustificationToBottom()
        if "cent" in justify:
            tp.SetVerticalJustificationToCentered()
            tp.SetJustificationToCentered()
        if "left" in justify:
            tp.SetJustificationToLeft()
        if "right" in justify:
            tp.SetJustificationToRight()

        if font.lower() == "courier": tp.SetFontFamilyToCourier()
        elif font.lower() == "times": tp.SetFontFamilyToTimes()
        elif font.lower() == "arial": tp.SetFontFamilyToArial()
        else:
            tp.SetFontFamily(vtk.VTK_FONT_FILE)
            import os
            if font in settings.fonts:
                tp.SetFontFile(settings.fonts_path + font + '.ttf')
            elif os.path.exists(font):
                tp.SetFontFile(font)
            else:
                colors.printc("\sad Font",
                              font,
                              "not found in",
                              settings.fonts_path,
                              c="r")
                colors.printc("\pin Available fonts are:",
                              settings.fonts,
                              c="m")
                return None

        if bg:
            bgcol = colors.getColor(bg)
            tp.SetBackgroundColor(bgcol)
            tp.SetBackgroundOpacity(alpha * 0.5)
            tp.SetFrameColor(bgcol)
            tp.FrameOn()

        #GetConstrainedFontSize (const vtkUnicodeString &str,
        # vtkTextProperty *tprop, int targetWidth, int targetHeight, int dpi)
        fs = r.GetConstrainedFontSize(txt, tp, 900, 1000, dpi)
        tp.SetFontSize(fs)

        r.RenderString(tp, txt, img, [1, 1], dpi)
        # RenderString (vtkTextProperty *tprop, const vtkStdString &str,
        #   vtkImageData *data, int textDims[2], int dpi, int backend=Default)

        self.SetInputData(img)
        self.GetMapper().Modified()

        self.SetPosition(pos)
        x0, x1 = self.xbounds()
        if x1 != x0:
            sc = s / (x1 - x0)
            self.SetScale(sc, sc, sc)
        return self
Ejemplo n.º 41
0
    def load_vtk_legacy_file(self, file):
        """
		Loads the vtk mesh and displays the scalar data in a color map.
		Allows further postprocessing to be done, such as grayscale and contour plots.
		"""

        if hasattr(self, "mesh_actor"):
            self.ren.RemoveActor(self.mesh_actor)
            self.ren.RemoveActor(self.sbActor)

        if file is None:
            file, _ = get_file("*.vtk")

        self.ui.statLabel.setText("Reading %s for mesh . . ." % file)
        mesh_source = vtk.vtkUnstructuredGridReader()
        mesh_source.SetFileName(file)

        # read scalar to vtk
        mesh_source.SetScalarsName("S33")
        mesh_source.Update()
        mesh_reader_output = mesh_source.GetOutput()

        # bounds for axis
        bounds = mesh_reader_output.GetBounds()

        # show element edges
        edges = vtk.vtkExtractEdges()
        edges.SetInputConnection(mesh_source.GetOutputPort())
        edges.Update()

        # lookup table and scalar range for a vtk file
        mesh_lookup_table = vtk.vtkLookupTable()

        # make scalar red = max; blue = min
        self.ui.statLabel.setText("Building lookup table . . .")
        self.draw_color_range(mesh_lookup_table)
        mesh_lookup_table.Build()
        scalar_range = mesh_reader_output.GetScalarRange()

        # mesh data set
        self.mesh_mapper = vtk.vtkDataSetMapper()
        self.mesh_mapper.SetInputData(mesh_reader_output)
        self.mesh_mapper.SetScalarRange(scalar_range)
        self.mesh_mapper.SetLookupTable(mesh_lookup_table)

        #define actors
        self.mesh_actor = vtk.vtkActor()
        # self.sbActor = vtk.vtkScalarBarActor()

        # #the scalar bar widget is associated with the qt interactor box
        scalar_bar_widget = vtk.vtkScalarBarWidget()
        scalar_bar_widget.SetInteractor(self.iren)
        # scalar_bar_widget.SetCurrentRenderer(self.ren.GetRenderer())
        # scalar_bar_widget.SetDefaultRenderer(self.ren.GetRenderer())
        scalar_bar_widget.SetEnabled(True)
        scalar_bar_widget.RepositionableOn()
        scalar_bar_widget.On()

        # define scalar bar actor
        self.sbActor = scalar_bar_widget.GetScalarBarActor()
        # self.sbActor.SetOrientationToVertical()
        self.sbActor.SetLookupTable(mesh_lookup_table)
        self.sbActor.SetTitle("S33")

        scalarBarRep = scalar_bar_widget.GetRepresentation()
        scalarBarRep.GetPositionCoordinate().SetValue(0.01, 0.01)
        scalarBarRep.GetPosition2Coordinate().SetValue(0.09, 0.9)

        #attempt to change scalebar properties [ineffective]
        propT = vtk.vtkTextProperty()
        propL = vtk.vtkTextProperty()
        propT.SetFontFamilyToArial()
        # propT.ItalicOff()
        propT.BoldOn()
        propL.BoldOff()
        propL.SetFontSize(1)
        propT.SetFontSize(2)
        self.sbActor.SetTitleTextProperty(propT)
        self.sbActor.SetLabelTextProperty(propL)
        self.sbActor.GetLabelTextProperty().SetFontSize(7)
        self.sbActor.GetTitleTextProperty().SetFontSize(7)
        self.sbActor.SetLabelFormat("%.1f")

        #define the mesh actor properties
        self.mesh_actor.SetMapper(self.mesh_mapper)
        self.mesh_actor.GetProperty().SetLineWidth(1)
        self.mesh_actor.GetProperty().EdgeVisibilityOn()

        #display the actors
        self.ren.AddActor(self.mesh_actor)
        self.ren.AddActor(self.sbActor)

        #get boundary of mesh
        self.limits = mesh_reader_output.GetBounds()

        self.ui.vtkWidget.setFocus()
        self.AddAxis(self.limits, 1)
        xyview_post(self.ren, self.ren.GetActiveCamera(), self.cp,
                    self.fp)  #sorts out the camera issue
        self.ui.vtkWidget.update()
        self.ui.statLabel.setText("Loaded results. Idle.")
        QtWidgets.QApplication.processEvents()
Ejemplo n.º 42
0
    def _plotInternal(self):
        """Overrides baseclass implementation."""
        numLevels = len(self._contourLevels)

        cot = vtk.vtkContourFilter()
        if self._useCellScalars:
            cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
        else:
            cot.SetInputData(self._vtkDataSet)
        cot.SetNumberOfContours(numLevels)

        if self._contourLevels[0] == 1.e20:
            self._contourLevels[0] = -1.e20
        for i in range(numLevels):
            cot.SetValue(i, self._contourLevels[i])
        cot.SetValue(numLevels, self._contourLevels[-1])
        # TODO remove update
        cot.Update()

        mappers = []

        lut = vtk.vtkLookupTable()
        lut.SetNumberOfTableValues(len(self._contourColors))
        cmap = vcs.elements["colormap"][self._context.canvas.getcolormapname()]
        for i, col in enumerate(self._contourColors):
            r, g, b = cmap.index[col]
            lut.SetTableValue(i, r / 100., g / 100., b / 100.)

        # Setup isoline labels
        if self._gm.label:
            # Setup label mapping array:
            tpropMap = vtk.vtkDoubleArray()
            tpropMap.SetNumberOfComponents(1)
            tpropMap.SetNumberOfTuples(numLevels)
            for i, val in enumerate(self._contourLevels):
                tpropMap.SetTuple(i, [
                    val,
                ])

            # Prep text properties:
            tprops = vtk.vtkTextPropertyCollection()
            if self._gm.text or self._gm.textcolors:
                # Text objects:
                if self._gm.text:
                    texts = self._gm.text
                    while len(texts) < numLevels:
                        texts.append(texts[-1])
                else:
                    texts = [None] * len(self._gm.textcolors)

                # Custom colors:
                if self._gm.textcolors:
                    colorOverrides = self._gm.textcolors
                    while len(colorOverrides) < numLevels:
                        colorOverrides.append(colorOverrides[-1])
                else:
                    colorOverrides = [None] * len(self._gm.text)

                for tc, colorOverride in zip(texts, colorOverrides):
                    if vcs.queries.istextcombined(tc):
                        tt, to = tuple(tc.name.split(":::"))
                    elif tc is None:
                        tt = "default"
                        to = "default"
                    elif vcs.queries.istexttable(tc):
                        tt = tc.name
                        to = "default"
                    elif vcs.queries.istextorientation(tc):
                        to = tc.name
                        tt = "default"
                    if colorOverride is not None:
                        tt = vcs.createtexttable(None, tt)
                        tt.color = colorOverride
                        tt = tt.name
                    tprop = vtk.vtkTextProperty()
                    vcs2vtk.prepTextProperty(tprop,
                                             self._context.renWin.GetSize(),
                                             to, tt)
                    tprops.AddItem(tprop)
                    if colorOverride is not None:
                        del (vcs.elements["texttable"][tt])
            else:  # No text properties specified. Use the default:
                tprop = vtk.vtkTextProperty()
                vcs2vtk.prepTextProperty(tprop, self._context.renWin.GetSize())
                tprops.AddItem(tprop)
            self._resultDict["vtk_backend_contours_labels_text_properties"] = \
                  tprops

            mapper = vtk.vtkLabeledContourMapper()
            mapper.SetTextProperties(tprops)
            mapper.SetTextPropertyMapping(tpropMap)
            mapper.SetLabelVisibility(1)

            pdMapper = mapper.GetPolyDataMapper()

            self._resultDict["vtk_backend_labeled_luts"] = [[
                lut, [self._contourLevels[0], self._contourLevels[-1], False]
            ]]
        else:  # No isoline labels:
            mapper = vtk.vtkPolyDataMapper()
            pdMapper = mapper
            self._resultDict["vtk_backend_luts"] = [[
                lut, [self._contourLevels[0], self._contourLevels[-1], False]
            ]]
        pdMapper.SetLookupTable(lut)
        pdMapper.SetScalarRange(self._contourLevels[0],
                                self._contourLevels[-1])
        pdMapper.SetScalarModeToUsePointData()

        stripper = vtk.vtkStripper()
        stripper.SetInputConnection(cot.GetOutputPort())
        mapper.SetInputConnection(stripper.GetOutputPort())
        # TODO remove update, make pipeline
        stripper.Update()
        mappers.append(mapper)
        self._resultDict["vtk_backend_contours"] = [
            cot,
        ]

        if self._maskedDataMapper is not None:
            mappers.insert(0, self._maskedDataMapper)

        x1, x2, y1, y2 = vcs.utils.getworldcoordinates(self._gm,
                                                       self._data1.getAxis(-1),
                                                       self._data1.getAxis(-2))

        # And now we need actors to actually render this thing
        actors = []
        for mapper in mappers:
            act = vtk.vtkActor()
            act.SetMapper(mapper)

            if self._vtkGeoTransform is None:
                # If using geofilter on wireframed does not get wrppaed not sure
                # why so sticking to many mappers
                act = vcs2vtk.doWrap(act, [x1, x2, y1, y2],
                                     self._dataWrapModulo)

            # TODO See comment in boxfill.
            if mapper is self._maskedDataMapper:
                actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]])
            else:
                actors.append([act, [x1, x2, y1, y2]])

            # create a new renderer for this mapper
            # (we need one for each mapper because of cmaera flips)
            ren = self._context.fitToViewport(
                act, [
                    self._template.data.x1, self._template.data.x2,
                    self._template.data.y1, self._template.data.y2
                ],
                wc=[x1, x2, y1, y2],
                geo=self._vtkGeoTransform,
                priority=self._template.data.priority)

        self._resultDict["vtk_backend_actors"] = actors

        t = self._originalData1.getTime()
        if self._originalData1.ndim > 2:
            z = self._originalData1.getAxis(-3)
        else:
            z = None

        self._resultDict.update(
            self._context.renderTemplate(self._template, self._data1, self._gm,
                                         t, z))

        if self._context.canvas._continents is None:
            self._useContinents = False
        if self._useContinents:
            projection = vcs.elements["projection"][self._gm.projection]
            self._context.plotContinents(x1, x2, y1, y2, projection,
                                         self._dataWrapModulo, self._template)
Ejemplo n.º 43
0
    def addT2transvisualize(self, T2images, image_pos_pat, image_ori_pat, T2dims, T2spacing, interact):
        '''Added to build second reference frame and display T2 overlayed into T1 reference frame'''
        # Proceed to build reference frame for display objects based on DICOM coords   
        [transformed_T2image, transform_cube] = self.dicomTransform(T2images, image_pos_pat, image_ori_pat)
        
        self.T2origin = list(transformed_T2image.GetOrigin())
        print "T2 Extent"
        self.T2extent = list(transformed_T2image.GetExtent())
        print self.T2extent        
        
        alignR = int(raw_input('\nAlign right? Yes:1 or align with T1w: !=1 : '))
        if alignR:
            zf1 = self.T1spacing[2]*self.T1extent[5] + self.T1origin[2]
            self.T2origin[2] = zf1 - T2spacing[2]*self.T2extent[5] # this is z-span
        else:
            self.T2origin[2] = self.T1origin[2]
                
        # Change info origin
        transformedInfo_T2image = vtk.vtkImageChangeInformation()
        transformedInfo_T2image.SetInputData( transformed_T2image )
        transformedInfo_T2image.SetOutputOrigin(self.T2origin)
        transformedInfo_T2image.Update()
        
        self.transformed_T2image = transformedInfo_T2image.GetOutput()
        
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0.5, 0.5, 0)
        tprop.ShadowOff()
        
        # Update the reneder window to receive new image !Important*****
        self.renderer1.Modified()
        self.renWin1.Modified()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInputData(self.transformed_T2image)
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)
        
        ### Update T2Images
        t_T2images = vtk.vtkImageChangeInformation()
        t_T2images.SetInputData( T2images )
        t_T2images.SetOutputOrigin(self.T2origin)
        t_T2images.Update()        

        ############                
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()
            
        return 
Ejemplo n.º 44
0
    def __init__(self):
        self.data = {
            "atom_types": DavTKAtomTypes(),
            "colormaps": {},
            "cell_box": {
                "color": [1.0, 1.0, 1.0],
                "opacity": 1.0,
                "line_width": 2.0,
                "prop": None
            },
            "background_color": [0.0, 0.0, 0.0],
            "picked": {
                "color": [1.0, 1.0, 0.0],
                "opacity": 1.0,
                "prop": None
            },
            "frame_label": {
                "color": [1.0, 1.0, 1.0],
                "fontsize": 36,
                "prop": None,
                "string": "${config_n}",
                "show": True
            },
            "atom_label": {
                "color": [1.0, 1.0, 1.0],
                "fontsize": 24,
                "prop": None,
                "string": "$${ID}",
                "show": False
            },
            "frame_step": 1,
            "legend": {
                'show': False,
                'position': np.array([-10, -10]),
                'spacing': 1.0,
                'sphere_scale': 1.0
            },
            'atom_type_field': 'Z'
        }

        self.parsers = {}

        self.parser_atom_type_field = ThrowingArgumentParser(
            prog="atom_type_field",
            description="ASE at.arrays field to use for atom type")
        self.parser_atom_type_field.add_argument(
            "field",
            type=str,
            help=
            "name of field ('Z' for atomic numbers, 'species' for chemical symbols",
            default='Z')
        self.parsers["atom_type_field"] = (
            self.parse_atom_type_field,
            self.parser_atom_type_field.format_usage(),
            self.parser_atom_type_field.format_help(),
            self.write_atom_type_field)

        self.parser_print_settings = ThrowingArgumentParser(
            prog="print_settings", description="print settings")
        self.parser_print_settings.add_argument("-keyword_regexp", type=str)
        self.parsers["print_settings"] = (
            self.parse_print_settings,
            self.parser_print_settings.format_usage(),
            self.parser_print_settings.format_help(), None)

        self.parser_legend = ThrowingArgumentParser(
            prog="legend", description="control legend, toggle by default")
        group = self.parser_legend.add_mutually_exclusive_group()
        group.add_argument("-on", action='store_true', help="enable legend")
        group.add_argument("-off", action='store_true', help="disable legend")
        group = self.parser_legend.add_mutually_exclusive_group()
        group.add_argument(
            "-position",
            type=int,
            nargs=2,
            help="position relative to bottom left corner of display" +
            " (negative values relative to top right)",
            default=None)
        group.add_argument("-offset",
                           type=int,
                           nargs=2,
                           help="offset relative to current position",
                           default=None)
        self.parser_legend.add_argument(
            "-spacing",
            type=float,
            help="multiplier for spacing between rows",
            default=None)
        self.parser_legend.add_argument(
            "-sphere_scale",
            action='store',
            type=float,
            help="scaling factor for sphere radius",
            default=None)
        self.parsers["legend"] = (self.parse_legend,
                                  self.parser_legend.format_usage(),
                                  self.parser_legend.format_help(),
                                  self.write_legend)

        self.parser_step = ThrowingArgumentParser(
            prog="step",
            description="number of frames to skip in +/- and prev/next")
        self.parser_step.add_argument("n",
                                      type=int,
                                      help="number of frames to step")
        self.parsers["step"] = (self.parse_step,
                                self.parser_step.format_usage(),
                                self.parser_step.format_help(),
                                self.write_step)

        self.parser_colormap = ThrowingArgumentParser(
            prog="colormap",
            description="repeated sequence of groups of 4 numbers: V R G B ..."
        )
        self.parser_colormap.add_argument("name", type=str)
        self.parser_colormap.add_argument("-P",
                                          dest="colormap",
                                          nargs=4,
                                          action='append',
                                          type=float,
                                          metavar=('V', 'R', 'G', 'B'))
        self.parsers["colormap"] = (self.parse_colormap,
                                    self.parser_colormap.format_usage(),
                                    self.parser_colormap.format_help(),
                                    self.write_colormap)

        self.parser_atom_type = ThrowingArgumentParser(prog="atom_type")
        self.parser_atom_type.add_argument("name", type=str)
        group = self.parser_atom_type.add_mutually_exclusive_group()
        group.add_argument("-color",
                           "-c",
                           nargs=3,
                           type=float,
                           default=None,
                           metavar=("R", "G", "B"))
        group.add_argument("-colormap",
                           nargs=2,
                           type=str,
                           default=None,
                           metavar=("COLORMAP", "FIELD"))
        group = self.parser_atom_type.add_mutually_exclusive_group()
        group.add_argument("-radius", "-rad", "-r", type=float, default=None)
        group.add_argument("-radius_field",
                           type=str,
                           nargs=2,
                           metavar=("RADIUS_FIELD", "FACTOR"),
                           default=None)
        self.parser_atom_type.add_argument("-bonding_radius",
                                           type=float,
                                           default=None)
        add_material_args_to_parser(self.parser_atom_type)
        self.parsers["atom_type"] = (self.parse_atom_type,
                                     self.parser_atom_type.format_usage(),
                                     self.parser_atom_type.format_help(),
                                     self.write_atom_type)

        self.parser_cell_box = ThrowingArgumentParser(prog="cell_box")
        self.parser_cell_box.add_argument("-color",
                                          nargs=3,
                                          type=float,
                                          metavar=['R', 'G', 'B'],
                                          default=None)
        self.parser_cell_box.add_argument("-opacity", type=float, default=None)
        self.parser_cell_box.add_argument("-width", type=float, default=None)
        self.parsers["cell_box"] = (self.parse_cell_box,
                                    self.parser_cell_box.format_usage(),
                                    self.parser_cell_box.format_help(),
                                    self.write_cell_box)

        self.parser_picked = ThrowingArgumentParser(prog="picked")
        self.parser_picked.add_argument("-color",
                                        nargs=3,
                                        type=float,
                                        metavar=['R', 'G', 'B'])
        self.parsers["picked"] = (self.parse_picked,
                                  self.parser_picked.format_usage(),
                                  self.parser_picked.format_help(),
                                  self.write_picked)

        self.parser_background_color = ThrowingArgumentParser(
            prog="background_color")
        self.parser_background_color.add_argument("-color",
                                                  nargs=3,
                                                  type=float,
                                                  metavar=['R', 'G', 'B'])
        self.parsers["background_color"] = (
            self.parse_background_color,
            self.parser_background_color.format_usage(),
            self.parser_background_color.format_help(),
            self.write_background_color)

        self.parser_frame_label = ThrowingArgumentParser(prog="frame_label")
        self.parser_frame_label.add_argument(
            "-string",
            "-s",
            type=str,
            nargs='+',
            help=
            "string, evaluating $( EXPRESSION ) and substituting ${STRING} with fields in atoms.info (or 'config_n'), or _NONE_",
            default=None)
        self.parser_frame_label.add_argument("-color",
                                             "-c",
                                             nargs=3,
                                             type=float,
                                             default=None,
                                             metavar=("R", "G", "B"))
        self.parser_frame_label.add_argument("-fontsize",
                                             type=int,
                                             default=None)
        group = self.parser_frame_label.add_mutually_exclusive_group()
        group.add_argument("-on", action='store_true')
        group.add_argument("-off", action='store_true')
        self.parsers["frame_label"] = (self.parse_frame_label,
                                       self.parser_frame_label.format_usage(),
                                       self.parser_frame_label.format_help(),
                                       self.write_frame_label)

        self.parser_atom_label = ThrowingArgumentParser(prog="atom_label")
        self.parser_atom_label.add_argument(
            "-string",
            type=str,
            help=
            "string to use for label, evaluating $( EXPRESSION ) and substituting $${STRING} with fields in atoms.arrays "
            +
            "(or 'ID' for number of atom, 'Z' for atomic number, 'species' for chemical symbol), "
            + "or '_NONE_'",
            default=None)
        self.parser_atom_label.add_argument("-color",
                                            "-c",
                                            nargs=3,
                                            type=float,
                                            default=None,
                                            metavar=("R", "G", "B"))
        self.parser_atom_label.add_argument("-fontsize",
                                            type=int,
                                            default=None)
        group = self.parser_atom_label.add_mutually_exclusive_group()
        group.add_argument("-on", action='store_true')
        group.add_argument("-off", action='store_true')
        self.parsers["atom_label"] = (self.parse_atom_label,
                                      self.parser_atom_label.format_usage(),
                                      self.parser_atom_label.format_help(),
                                      self.write_atom_label)

        # properties
        # 3D Actor properties
        for f in ["cell_box", "picked"]:
            prop = vtk.vtkProperty()
            prop.SetColor(self.data[f]["color"])
            prop.SetOpacity(self.data[f]["opacity"])
            if "line_width" in self.data[f]:
                prop.SetLineWidth(self.data[f]["line_width"])
            self.data[f]["prop"] = prop

        # make picked very flat
        self.data["picked"]["prop"].SetAmbient(0.6)
        self.data["picked"]["prop"].SetDiffuse(0.4)

        # text properties
        for f in ["frame_label", "atom_label"]:
            prop = vtk.vtkTextProperty()
            self.data[f]["prop"] = prop
            prop.SetOpacity(1.0)
            prop.SetColor(self.data[f]["color"])
            prop.SetFontSize(self.data[f]["fontsize"])
Ejemplo n.º 45
0
    def SetUp(self):
        '''
        Set up cursor3D
        '''
        def OnClosing():
            self.root.quit()

        def AddSphere(ren):
            objSource = vtk.vtkSphereSource()

            objMapper = vtk.vtkPolyDataMapper()
            objMapper.SetInputConnection(objSource.GetOutputPort())

            objActor = vtk.vtkActor()
            objActor.SetMapper(objMapper)
            objActor.GetProperty().SetRepresentationToWireframe()

            ren.AddActor(objActor)

        def AddOneTextActor(baseTextProp):
            name = "ia"
            self.textActors[name] = vtk.vtkTextActor3D()
            # This adjustment is needed to reduce the difference
            # between the Tcl and Python versions.
            self.textActors[name].SetOrigin(0, -0.127878, 0)

            tprop = self.textActors[name].GetTextProperty()
            tprop.ShallowCopy(baseTextProp)
            tprop.SetColor(1, 0, 0)

        # Add many text actors.
        def AddManyTextActors(baseTextProp):
            lut = vtk.vtkColorTransferFunction()
            lut.SetColorSpaceToHSV()
            lut.AddRGBPoint(0.0, 0.0, 1.0, 1.0)
            lut.AddRGBPoint(1.0, 1.0, 1.0, 1.0)

            for i in range(0, 10):
                name = "ia" + str(i)

                self.textActors[name] = vtk.vtkTextActor3D()
                self.textActors[name].SetOrientation(0, i * 36, 0)
                #self.textActors[name].SetPosition(math.cos(i * 0.0314), 0, 0)
                # This adjustment is needed to reduce the diffierence
                # between the Tcl and Python versions.
                self.textActors[name].SetOrigin(0, -0.127878, 0)

                tprop = self.textActors[name].GetTextProperty()
                tprop.ShallowCopy(baseTextProp)
                value = i / 10.0
                tprop.SetColor(lut.GetColor(value))

            del lut

        # Update all text actors
        def UpdateTextActors(event):
            orientation = self.scaleOrientation.get()
            fontSize = self.scaleFontSize.get()
            scale = self.scaleScale.get() / 10000.0
            text = self.entryText.get("1.0", 'end+1c')
            opacity = self.scaleOpacity.get()

            for actor in self.textActors.values():
                actor.SetScale(scale)
                actor.SetInput(text)
                tprop = actor.GetTextProperty()
                tprop.SetFontSize(fontSize)
                tprop.SetOrientation(orientation)
                tprop.SetOpacity(opacity)

            self.renWin.Render()

        ren = vtk.vtkRenderer()
        ren.SetBackground(0.1, 0.2, 0.4)
        self.renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(ren)
        #self.renWin.SetSize(600, 600)

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

        # The Tk render widget.
        self.tkrw = vtkTkRenderWidget(self.root,
                                      width=450,
                                      height=450,
                                      rw=self.renWin)
        self.tkrw.BindTkRenderWidget()
        #self.renWin.GetInteractor().GetInteractorStyle().SetCurrentStyleToTrackballCamera()
        self.tkrw.pack(side=LEFT, fill=BOTH, expand=YES)

        # Base text property
        baseTextProp = vtk.vtkTextProperty()
        baseTextProp.SetFontSize(48)
        baseTextProp.ShadowOn()
        baseTextProp.SetColor(1.0, 0.0, 0.0)
        baseTextProp.SetFontFamilyToArial()

        baseScale = 0.0025

        baseText = "This is a test"

        # The text actors
        self.textActors = dict()

        scaleLength = 200
        controls = tkinter.Frame(self.root, relief=GROOVE, bd=2)
        controls.pack(padx=2,
                      pady=2,
                      anchor=N + W,
                      side=LEFT,
                      fill=BOTH,
                      expand=NO)

        # Add control of text.
        self.entryText = tkinter.Text(controls, height=1, width=25)
        self.entryText.insert(INSERT, baseText)
        self.entryText.pack(padx=4, pady=4, side=TOP, fill=X, expand=NO)
        self.entryText.bind('<Return>', UpdateTextActors)
        self.entryText.bind('<FocusOut>', UpdateTextActors)

        # Add control of orientation.
        self.scaleOrientation = tkinter.Scale(controls,
                                              from_=0,
                                              to=360,
                                              res=1,
                                              length=scaleLength,
                                              orient=HORIZONTAL,
                                              label="Text orientation:",
                                              command=UpdateTextActors)
        self.scaleOrientation.set(baseTextProp.GetOrientation())
        self.scaleOrientation.pack(side=TOP, fill=X, expand=NO)

        # Add control of font size.
        self.scaleFontSize = tkinter.Scale(controls,
                                           from_=5,
                                           to=150,
                                           res=1,
                                           length=scaleLength,
                                           orient=HORIZONTAL,
                                           label="Font Size:",
                                           command=UpdateTextActors)
        self.scaleFontSize.set(baseTextProp.GetFontSize())
        self.scaleFontSize.pack(side=TOP, fill=X, expand=NO)

        # Add control of scale.
        self.scaleScale = tkinter.Scale(controls,
                                        from_=0,
                                        to=100,
                                        res=1,
                                        length=scaleLength,
                                        orient=HORIZONTAL,
                                        label="Actor scale:",
                                        command=UpdateTextActors)
        self.scaleScale.set(baseScale * 10000.0)
        self.scaleScale.pack(side=TOP, fill=X, expand=NO)

        # Add control of scale.
        self.scaleOpacity = tkinter.Scale(controls,
                                          from_=0,
                                          to=1.0,
                                          res=0.01,
                                          length=scaleLength,
                                          orient=HORIZONTAL,
                                          label="Text opacity:",
                                          command=UpdateTextActors)
        self.scaleOpacity.set(baseTextProp.GetOpacity())
        self.scaleOpacity.pack(side=TOP, fill=X, expand=NO)

        # Create and add all the text actors.
        if False:
            AddSphere(ren)
            AddOneTextActor(baseTextProp)
            ren.ResetCamera()
        else:
            AddManyTextActors(baseTextProp)
            ren.ResetCamera()

            ren.GetActiveCamera().Elevation(30.0)
            ren.GetActiveCamera().Dolly(0.40)

        UpdateTextActors(0)

        for actor in self.textActors.values():
            ren.AddActor(actor)
Ejemplo n.º 46
0
light.SetColor(1, 1, 1)
light.SetFocalPoint(cam1.GetFocalPoint())
light.SetPosition(cam1.GetPosition())

ren.AddLight(light)

print cam1

# axes a la paraview
axes = vtk.vtkAxesActor()
axes.SetShaftTypeToCylinder()
axes.SetXAxisLabelText("x")
axes.SetYAxisLabelText("y")
axes.SetZAxisLabelText("z")
axes.SetTotalLength(1, 1, 1)
tprop = vtk.vtkTextProperty()
tprop.ItalicOn()
# tprop.ShadowOn()
# tprop.SetFontFamilyToTimes()
axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(tprop)
tprop2 = vtk.vtkTextProperty()  # inutile
tprop2.ShallowCopy(tprop)  # inutile
axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(tprop2)
tprop3 = vtk.vtkTextProperty()  # inutile
tprop3.ShallowCopy(tprop)  # inutile
axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(tprop3)

marker = vtk.vtkOrientationMarkerWidget()
#marker.SetOutlineColor(0.93, 0.57, 0.13)
marker.SetOrientationMarker(axes)
marker.SetViewport(0.85, 0.8, 1.1, 1.1)
Ejemplo n.º 47
0
def text_dimensions(text, index, winsize):
    prop = vtkTextProperty()
    vcs.vcs2vtk.prepTextProperty(prop, winsize, text, text, vcs.getcolormap())
    return vcs.vtk_ui.text.text_dimensions(text.string[index], prop)
Ejemplo n.º 48
0
    def set_initial_display(self):
        if self.renwininter is None:
            self.renwininter = MEQ_QVTKRenderWindowInteractor(self.winsplitter)
            self.renwininter.setWhatsThis(rendering_control_instructions)
            self.renwin = self.renwininter.GetRenderWindow()
            self.inter = self.renwin.GetInteractor()
            self.winsplitter.insertWidget(0, self.renwininter)
            self.winsplitter.addWidget(self.v_box_controls)
            self.winsplitter.setSizes([500, 100])
            self.renwininter.show()

            # Paul Kemper suggested the following:
            camstyle = vtk.vtkInteractorStyleTrackballCamera()
            self.renwininter.SetInteractorStyle(camstyle)

        self.extents = self.image_array.GetDataExtent()
        self.spacing = self.image_array.GetDataSpacing()
        self.origin = self.image_array.GetDataOrigin()

        # An outline is shown for context.
        if self.warped_surface:
            self.index_selector.initWarpContextmenu()
            sx, sy, sz = self.image_array.GetDataSpacing()
            xMin, xMax, yMin, yMax, zMin, zMax = self.image_array.GetDataExtent(
            )
            xMin = sx * xMin
            xMax = sx * xMax
            yMin = sy * yMin
            yMax = sy * yMax
            self.scale_factor = 0.5 * (
                (xMax - xMin) +
                (yMax - yMin)) / (self.data_max - self.data_min)
            zMin = self.data_min * self.scale_factor
            zMax = self.data_max * self.scale_factor
            self.outline = vtk.vtkOutlineSource()
            self.outline.SetBounds(xMin, xMax, yMin, yMax, zMin, zMax)
        else:
            self.index_selector.init3DContextmenu()
            self.outline = vtk.vtkOutlineFilter()
            self.outline.SetInput(self.image_array.GetOutput())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInput(self.outline.GetOutput())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # create blue to red color table
        self.lut = vtk.vtkLookupTable()
        self.lut.SetHueRange(0.6667, 0.0)
        self.lut.SetNumberOfColors(256)
        self.lut.Build()

        # here is where the 2-D image gets warped
        if self.warped_surface:
            geometry = vtk.vtkImageDataGeometryFilter()
            geometry.SetInput(self.image_array.GetOutput())
            self.warp = vtk.vtkWarpScalar()
            self.warp.SetInput(geometry.GetOutput())
            self.warp.SetScaleFactor(self.scale_factor)
            self.mapper = vtk.vtkPolyDataMapper()
            self.mapper.SetInput(self.warp.GetPolyDataOutput())
            self.mapper.SetScalarRange(self.data_min, self.data_max)
            self.mapper.SetLookupTable(self.lut)
            self.mapper.ImmediateModeRenderingOff()
            warp_actor = vtk.vtkActor()
            #     warp_actor.SetScale(2,1,1)
            warp_actor.SetMapper(self.mapper)

            min_range = 0.5 * self.scale_factor
            max_range = 2.0 * self.scale_factor
            self.index_selector.set_emit(False)
            self.index_selector.setMaxValue(max_range, False)
            self.index_selector.setMinValue(min_range)
            self.index_selector.setTickInterval((max_range - min_range) / 10)
            self.index_selector.setRange(max_range, False)
            self.index_selector.setValue(self.scale_factor)
            self.index_selector.setLabel('display gain')
            self.index_selector.hideNDControllerOption()
            self.index_selector.reset_scale_toggle()
            self.index_selector.set_emit(True)
        else:
            # set up ImagePlaneWidgets ...

            # The shared picker enables us to use 3 planes at one time
            # and gets the picking order right
            picker = vtk.vtkCellPicker()
            picker.SetTolerance(0.005)

            # get locations for initial slices
            xMin, xMax, yMin, yMax, zMin, zMax = self.extents
            x_index = (xMax - xMin) / 2
            y_index = (yMax - yMin) / 2
            z_index = (zMax - zMin) / 2

            # The 3 image plane widgets are used to probe the dataset.
            self.planeWidgetX = vtk.vtkImagePlaneWidget()
            self.planeWidgetX.DisplayTextOn()
            self.planeWidgetX.SetInput(self.image_array.GetOutput())
            self.planeWidgetX.SetPlaneOrientationToXAxes()
            self.planeWidgetX.SetSliceIndex(x_index)
            self.planeWidgetX.SetPicker(picker)
            self.planeWidgetX.SetKeyPressActivationValue("x")
            self.planeWidgetX.SetLookupTable(self.lut)
            self.planeWidgetX.TextureInterpolateOff()
            self.planeWidgetX.SetResliceInterpolate(0)

            self.planeWidgetY = vtk.vtkImagePlaneWidget()
            self.planeWidgetY.DisplayTextOn()
            self.planeWidgetY.SetInput(self.image_array.GetOutput())
            self.planeWidgetY.SetPlaneOrientationToYAxes()
            self.planeWidgetY.SetSliceIndex(y_index)
            self.planeWidgetY.SetPicker(picker)
            self.planeWidgetY.SetKeyPressActivationValue("y")
            self.planeWidgetY.SetLookupTable(
                self.planeWidgetX.GetLookupTable())
            self.planeWidgetY.TextureInterpolateOff()
            self.planeWidgetY.SetResliceInterpolate(0)

            self.planeWidgetZ = vtk.vtkImagePlaneWidget()
            self.planeWidgetZ.DisplayTextOn()
            self.planeWidgetZ.SetInput(self.image_array.GetOutput())
            self.planeWidgetZ.SetPlaneOrientationToZAxes()
            self.planeWidgetZ.SetSliceIndex(z_index)
            self.planeWidgetZ.SetPicker(picker)
            self.planeWidgetZ.SetKeyPressActivationValue("z")
            self.planeWidgetZ.SetLookupTable(
                self.planeWidgetX.GetLookupTable())
            self.planeWidgetZ.TextureInterpolateOff()
            self.planeWidgetZ.SetResliceInterpolate(0)

            self.current_widget = self.planeWidgetZ
            self.mode_widget = self.planeWidgetZ
            self.index_selector.set_emit(False)
            self.index_selector.setMinValue(zMin)
            self.index_selector.setMaxValue(zMax, False)
            self.index_selector.setTickInterval((zMax - zMin) / 10)
            self.index_selector.setRange(zMax, False)
            self.index_selector.setValue(z_index)
            self.index_selector.setLabel('Z axis')
            self.index_selector.reset_scale_toggle()
            self.index_selector.set_emit(True)

# create scalar bar for display of intensity range
        self.scalar_bar = vtk.vtkScalarBarActor()
        self.scalar_bar.SetLookupTable(self.lut)
        self.scalar_bar.SetOrientationToVertical()
        self.scalar_bar.SetWidth(0.1)
        self.scalar_bar.SetHeight(0.8)
        self.scalar_bar.SetTitle("Intensity")
        self.scalar_bar.GetPositionCoordinate(
        ).SetCoordinateSystemToNormalizedViewport()
        self.scalar_bar.GetPositionCoordinate().SetValue(0.01, 0.1)

        # Create the RenderWindow and Renderer
        self.ren = vtk.vtkRenderer()
        self.renwin.AddRenderer(self.ren)

        # Add the outline actor to the renderer, set the background color and size
        if self.warped_surface:
            self.ren.AddActor(warp_actor)
        self.ren.AddActor(outlineActor)
        self.ren.SetBackground(0.1, 0.1, 0.2)
        self.ren.AddActor2D(self.scalar_bar)

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

        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        self.axes = vtk.vtkCubeAxesActor2D()
        if self.warped_surface:
            if zMin < 0.0 and zMax > 0.0:
                zLoc = 0.0
            else:
                zLoc = zMin
            self.axes.SetBounds(xMin, xMax, yMin, yMax, zLoc, zLoc)
            self.axes.SetZLabel(" ")
        else:
            self.axes.SetInput(self.image_array.GetOutput())
            self.axes.SetZLabel("Z")
        self.axes.SetCamera(self.ren.GetActiveCamera())
        self.axes.SetLabelFormat("%6.4g")
        self.axes.SetFlyModeToOuterEdges()
        self.axes.SetFontFactor(0.8)
        self.axes.SetAxisTitleTextProperty(tprop)
        self.axes.SetAxisLabelTextProperty(tprop)
        self.axes.SetXLabel("X")
        self.axes.SetYLabel("Y")
        self.ren.AddProp(self.axes)

        # Set the interactor for the widgets
        if not self.warped_surface:
            self.planeWidgetX.SetInteractor(self.inter)
            self.planeWidgetX.On()
            self.planeWidgetY.SetInteractor(self.inter)
            self.planeWidgetY.On()
            self.planeWidgetZ.SetInteractor(self.inter)
            self.planeWidgetZ.On()

        self.initialize_camera()
Ejemplo n.º 49
0
    def __init__(self, interactor, marker, index, display, configurator):
        self.interactor = interactor
        self.marker = marker
        self.index = index
        self.configurator = configurator

        actors = display.backend["vtk_backend_marker_actors"][index]

        self.glyph, self.glyph_source, self.polydata, self.actor, self.geo = actors

        self.display = display

        self.handles = []

        for ind, x in enumerate(marker.x[index]):
            y = marker.y[index][ind]
            h = vtk_ui.Handle(self.interactor, (x, y),
                              dragged=self.adjust,
                              color=(0, 0, 0),
                              normalize=True)
            h.show()
            self.handles.append(h)

        self.toolbar = vtk_ui.toolbar.Toolbar(self.interactor,
                                              "Marker Options")
        self.toolbar.show()

        self.toolbar.add_button(["Change Color"], action=self.change_color)
        self.toolbar.add_slider_button(marker.size[index],
                                       1,
                                       300,
                                       "Marker Size",
                                       update=self.set_size)

        self.type_bar = self.toolbar.add_toolbar("Marker Type",
                                                 open_label="Change")

        shapes = marker_shapes()

        shapes.insert(0, "Select Shape")
        self.shape_button = self.type_bar.add_button(shapes,
                                                     action=self.change_shape)

        wmos = wmo_shapes()
        wmos.insert(0, "Select WMO Marker")

        self.wmo_button = self.type_bar.add_button(wmos,
                                                   action=self.change_wmo)

        if self.marker.type[self.index] in shapes:
            self.shape_button.set_state(
                shapes.index(self.marker.type[self.index]))
        else:
            self.wmo_button.set_state(wmos.index(self.marker.type[self.index]))

        # Used to store the color picker when it's active
        self.picker = None
        prop = vtk.vtkTextProperty()
        prop.SetBackgroundColor(.87, .79, .55)
        prop.SetBackgroundOpacity(1)
        prop.SetColor(0, 0, 0)

        self.tooltip = vtk_ui.Label(
            self.interactor,
            "%s + Click to place new markers." %
            ("Cmd" if sys.platform == "darwin" else "Ctrl"),
            textproperty=prop)
        self.tooltip.left = 0
        self.tooltip.top = self.interactor.GetRenderWindow().GetSize(
        )[1] - self.tooltip.get_dimensions()[1]
        self.tooltip.show()
        super(MarkerEditor, self).__init__()
        self.register()
Ejemplo n.º 50
0
def main():
    cellName = get_program_parameters()

    # Store the cell class names in a dictionary.
    cellMap = dict()
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_LINE)] = vtk.VTK_LINE
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_QUADRATIC_EDGE)] = vtk.VTK_QUADRATIC_EDGE
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_CUBIC_LINE)] = vtk.VTK_CUBIC_LINE

    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_TRIANGLE)] = vtk.VTK_TRIANGLE
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_QUADRATIC_TRIANGLE)] = vtk.VTK_QUADRATIC_TRIANGLE
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_QUAD)] = vtk.VTK_QUAD
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_QUADRATIC_QUAD)] = vtk.VTK_QUADRATIC_QUAD

    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_TETRA)] = vtk.VTK_TETRA
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_HEXAHEDRON)] = vtk.VTK_HEXAHEDRON
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_WEDGE)] = vtk.VTK_WEDGE
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_PYRAMID)] = vtk.VTK_PYRAMID
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_QUADRATIC_WEDGE)] = vtk.VTK_QUADRATIC_WEDGE
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_QUADRATIC_PYRAMID)] = vtk.VTK_QUADRATIC_PYRAMID
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_QUADRATIC_HEXAHEDRON)] = vtk.VTK_QUADRATIC_HEXAHEDRON
    cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(
        vtk.VTK_QUADRATIC_TETRA)] = vtk.VTK_QUADRATIC_TETRA

    if cellName not in cellMap:
        print('Cell type ', cellName, ' is not supported.')
        return
    source = vtk.vtkCellTypeSource()
    source.SetCellType(cellMap[cellName])
    source.Update()
    print('Cell: ', cellName)

    originalPoints = source.GetOutput().GetPoints()
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(source.GetOutput().GetNumberOfPoints())
    rng = vtk.vtkMinimalStandardRandomSequence()
    rng.SetSeed(5070)  # for testing
    for i in range(0, points.GetNumberOfPoints()):
        perturbation = [0.0] * 3
        for j in range(0, 3):
            rng.Next()
            perturbation[j] = rng.GetRangeValue(-0.1, 0.1)
        currentPoint = [0.0] * 3
        originalPoints.GetPoint(i, currentPoint)
        points.SetPoint(i, currentPoint[0] + perturbation[0],
                        currentPoint[1] + perturbation[1],
                        currentPoint[2] + perturbation[2])
    source.GetOutput().SetPoints(points)

    numCells = source.GetOutput().GetNumberOfCells()
    print('Number of cells: ', numCells)
    idArray = vtk.vtkIntArray()
    idArray.SetNumberOfTuples(numCells)
    for i in range(0, numCells):
        idArray.InsertTuple1(i, i + 1)
    idArray.SetName('Ids')
    source.GetOutput().GetCellData().AddArray(idArray)
    source.GetOutput().GetCellData().SetActiveScalars('Ids')

    shrink = vtk.vtkShrinkFilter()
    shrink.SetInputConnection(source.GetOutputPort())
    shrink.SetShrinkFactor(.8)

    tessellate = vtk.vtkTessellatorFilter()
    tessellate.SetInputConnection(shrink.GetOutputPort())
    tessellate.SetMaximumNumberOfSubdivisions(3)

    # Create a lookup table to map cell data to colors.
    lut = vtk.vtkLookupTable()

    colorSeries = vtk.vtkColorSeries()
    seriesEnum = colorSeries.BREWER_QUALITATIVE_SET3
    colorSeries.SetColorScheme(seriesEnum)
    colorSeries.BuildLookupTable(lut, colorSeries.ORDINAL)

    # Fill in a few known colors, the rest will be generated if needed.
    colors = vtk.vtkNamedColors()

    # Create a mapper and actor.
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(source.GetOutputPort())
    mapper.SetInputConnection(shrink.GetOutputPort())
    mapper.SetScalarRange(0, numCells + 1)
    mapper.SetLookupTable(lut)
    mapper.SetScalarModeToUseCellData()
    mapper.SetResolveCoincidentTopologyToPolygonOffset()
    if (source.GetCellType() == vtk.VTK_QUADRATIC_PYRAMID
            or source.GetCellType() == vtk.VTK_QUADRATIC_WEDGE):
        mapper.SetInputConnection(shrink.GetOutputPort())
    else:
        mapper.SetInputConnection(tessellate.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().EdgeVisibilityOn()
    #  actor.GetProperty().SetLineWidth(3)

    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(20)
    textProperty.SetJustificationToCentered()
    textProperty.SetColor(colors.GetColor3d('Lamp_Black'))

    textMapper = vtk.vtkTextMapper()
    textMapper.SetInput(cellName)
    textMapper.SetTextProperty(textProperty)

    textActor = vtk.vtkActor2D()
    textActor.SetMapper(textMapper)
    textActor.SetPosition(320, 20)

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

    # Add the actors to the scene.
    renderer.AddViewProp(textActor)
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('Silver'))

    renderer.ResetCamera()
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)
    renderer.ResetCameraClippingRange()

    # Render and interact.
    renderWindow.SetSize(640, 480)
    renderWindow.Render()
    renderWindowInteractor.Start()
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        # Create source
        # Each face has a different cell scalar
        # So create a lookup table with a different colour
        # for each face.
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfTableValues(20)
        lut.SetTableRange(0.0, 19.0)
        lut.Build()
        lut.SetTableValue(0, 0, 0, 0)
        lut.SetTableValue(1, 0, 0, 1)
        lut.SetTableValue(2, 0, 1, 0)
        lut.SetTableValue(3, 0, 1, 1)
        lut.SetTableValue(4, 1, 0, 0)
        lut.SetTableValue(5, 1, 0, 1)
        lut.SetTableValue(6, 1, 1, 0)
        lut.SetTableValue(7, 1, 1, 1)
        lut.SetTableValue(8, 0.7, 0.7, 0.7)
        lut.SetTableValue(9, 0, 0, 0.7)
        lut.SetTableValue(10, 0, 0.7, 0)
        lut.SetTableValue(11, 0, 0.7, 0.7)
        lut.SetTableValue(12, 0.7, 0, 0)
        lut.SetTableValue(13, 0.7, 0, 0.7)
        lut.SetTableValue(14, 0.7, 0.7, 0)
        lut.SetTableValue(15, 0, 0, 0.4)
        lut.SetTableValue(16, 0, 0.4, 0)
        lut.SetTableValue(17, 0, 0.4, 0.4)
        lut.SetTableValue(18, 0.4, 0, 0)
        lut.SetTableValue(19, 0.4, 0, 0.4)

        platonicSolids = list()
        # There are five Platonic solids.
        platonicSolids.append(vtk.vtkPlatonicSolidSource())
        platonicSolids.append(vtk.vtkPlatonicSolidSource())
        platonicSolids.append(vtk.vtkPlatonicSolidSource())
        platonicSolids.append(vtk.vtkPlatonicSolidSource())
        platonicSolids.append(vtk.vtkPlatonicSolidSource())
        # Specify the Platonic Solid to create.
        for idx, item in enumerate(platonicSolids):
            platonicSolids[idx].SetSolidType(idx)
        names = [
            "Tetrahedron", "Cube", "Octahedron", "Icosahedron", "Dodecahedron"
        ]

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

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

        # Create a parametric function source, renderer, mapper
        # and actor for each object.
        for idx, item in enumerate(platonicSolids):
            platonicSolids[idx].Update()

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(
                platonicSolids[idx].GetOutputPort())
            mappers[idx].SetLookupTable(lut)
            mappers[idx].SetScalarRange(0, 20)

            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(120, 16)

            renderers.append(vtk.vtkRenderer())

        rowDimensions = 3
        colDimensions = 2

        for idx in range(rowDimensions * colDimensions):
            if idx >= len(platonicSolids):
                renderers.append(vtk.vtkRenderer)

        rendererSize = 300

        # Setup the RenderWindow
        self.vtkWidget.GetRenderWindow().SetSize(
            rendererSize * rowDimensions / colDimensions,
            rendererSize * colDimensions)

        # Add and position the renders to the render window.
        viewport = list()
        idx = -1
        for row in range(rowDimensions):
            for col in range(colDimensions):
                idx += 1
                viewport[:] = []
                viewport.append(
                    float(col) * rendererSize / (colDimensions * rendererSize))
                viewport.append(
                    float(rowDimensions - (row + 1)) * rendererSize /
                    (rowDimensions * rendererSize))
                viewport.append(
                    float(col + 1) * rendererSize /
                    (colDimensions * rendererSize))
                viewport.append(
                    float(rowDimensions - row) * rendererSize /
                    (rowDimensions * rendererSize))

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

                renderers[idx].SetViewport(viewport)
                self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx])

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

        self._initialized = False
Ejemplo n.º 52
0
    def CreateMarker(self):
        # Create a composite orientation marker using
        # vtkAnnotatedCubeActor and vtkAxesActor.
        #
        cube = vtkAnnotatedCubeActor()
        cube.SetXPlusFaceText("R")
        cube.SetXMinusFaceText("L")
        cube.SetYPlusFaceText("A")
        cube.SetYMinusFaceText("P")
        cube.SetZPlusFaceText("I")
        cube.SetZMinusFaceText("S")
        cube.SetXFaceTextRotation(0)
        cube.SetYFaceTextRotation(0)
        cube.SetZFaceTextRotation(-90)
        cube.SetFaceTextScale(0.65)

        prop = cube.GetCubeProperty()
        prop.SetColor(0.5, 1, 1)

        prop = cube.GetTextEdgesProperty()
        prop.SetLineWidth(1)
        prop.SetDiffuse(0)
        prop.SetAmbient(1)
        prop.SetColor(0.18, 0.28, 0.23)

        for axis, colour in (('X', (0, 0, 1)), ('Y', (0, 1, 0)), ('Z', (1, 0,
                                                                        0))):
            for orient in ('Plus', 'Minus'):
                prop = getattr(cube, 'Get' + axis + orient + 'FaceProperty')()
                prop.SetColor(*colour)
                prop.SetInterpolationToFlat()
                continue
            continue

        axes = vtkAxesActor()
        axes.SetShaftTypeToCylinder()
        axes.SetXAxisLabelText("x")
        axes.SetYAxisLabelText("y")
        axes.SetZAxisLabelText("z")
        axes.SetTotalLength(1.5, 1.5, 1.5)

        tpropx = vtkTextProperty()
        tpropx.ItalicOn()
        tpropx.ShadowOn()
        tpropx.SetFontFamilyToTimes()
        axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(tpropx)
        tpropy = vtkTextProperty()
        tpropy.ShallowCopy(tpropx)
        axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(tpropy)
        tpropz = vtkTextProperty()
        tpropz.ShallowCopy(tpropx)
        axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(tpropz)

        # Combine the two actors into one with vtkPropAssembly ...
        #
        assembly = vtkPropAssembly()
        assembly.AddPart(axes)
        assembly.AddPart(cube)

        # Add the composite marker to the widget.  The widget
        # should be kept in non-interactive mode and the aspect
        # ratio of the render window taken into account explicitly,
        # since the widget currently does not take this into
        # account in a multi-renderer environment.
        #
        marker = vtkOrientationMarkerWidget()
        marker.SetOutlineColor(0.93, 0.57, 0.13)
        marker.SetOrientationMarker(assembly)
        marker.SetViewport(0.0, 0.0, 0.15, 0.3)
        self.OrientationMarker = marker
        return
Ejemplo n.º 53
0
    def __init__(self, parent=None, dcm_dir='', view_plane='Transverse'):
        """
        建立DICOM VTK 畫布
        :param dcm_dir: 影像路徑
        :param view_plane: 切面:預設'Transverse',可選'Coronal','Sagittal'
        """
        QtWidgets.QMainWindow.__init__(self, parent)
        self.frame = QtWidgets.QFrame()
        self.vl = QtWidgets.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.vl.addWidget(self.vtkWidget)

        if dcm_dir != '':
            self.dcm_series_path = Path(dcm_dir).expanduser()

        # set up VTK dicom reader
        self.dcmReader = vtkDICOMImageReader()
        self.dcmReader.SetDataByteOrderToLittleEndian()
        self.dcmReader.SetDirectoryName(str(self.dcm_series_path))
        self.dcmRescaleSlope = self.dcmReader.GetRescaleSlope()
        self.dcmRescaleOffset = self.dcmReader.GetRescaleOffset()
        self.dcmReader.Update()
        # '------default with WW & WL-----'
        self.ww = 3500  # WW
        self.wl = 600  # WL
        # '----------viewer---------'
        self.dcmViewer = vtk.vtkImageViewer2()
        self.dcmViewer.SetInputConnection(self.dcmReader.GetOutputPort())
        self.dcmViewer.SetColorLevel(500)
        self.dcmViewer.SetColorWindow(3500)
        self.dcmViewer.SetSize(600, 600)
        self.dcmViewer.UpdateDisplayExtent()
        # #!下面那一行確保不會多渲染出一個視窗物件! ##
        self.dcmViewer.SetRenderWindow(
            self.vtkWidget.GetRenderWindow())  # #!這一行確保不會多渲染出一個視窗物件! # #
        # #!上面那一行確保不會多渲染出一個視窗物件! ##
        #   下面三個方法可渲染不同人體不同的切面
        self.viewPlane = view_plane
        if self.viewPlane == 'Coronal':
            self.dcmViewer.SetSliceOrientationToXZ()  # 冠狀面 (Coronal plane)
        elif self.viewPlane == 'Sagittal':
            self.dcmViewer.SetSliceOrientationToYZ()  # 縱切面 (Sagittal plane)
        else:
            self.dcmViewer.SetSliceOrientationToXY(
            )  # Default: 橫狀面 (Transverse plane)

        # '----------TextOverLay---------'
        # slice status message
        self.sliceTextProp = vtk.vtkTextProperty()
        self.sliceTextProp.SetFontFamilyToCourier()
        self.sliceTextProp.SetFontSize(60)
        self.sliceTextProp.SetVerticalJustificationToBottom()
        self.sliceTextProp.SetJustificationToLeft()
        # '---------set up Text Overlay mapper----------'
        self.sliceTextMapper = vtk.vtkTextMapper()
        self.current_slice = self.dcmViewer.GetSlice()
        print('cur_slice  = ', self.current_slice, ' viewer.GetSliceMax() = ',
              self.dcmViewer.GetSliceMax())
        msg = (
            ' %d / %d ' %
            (self.dcmViewer.GetSlice() + 1, self.dcmViewer.GetSliceMax() + 1))
        self.sliceTextMapper.SetInput(msg)
        # '---------set up Text Overlay Actor----------'
        self.sliceTextActor = vtk.vtkActor2D()
        self.sliceTextActor.SetMapper(self.sliceTextMapper)
        self.sliceTextActor.SetPosition(15, 10)

        # ########--Get RENDERER--############
        self.renderer = self.dcmViewer.GetRenderer()
        self.renderer.AddActor2D(self.sliceTextActor)
        # ########--Set Up RENDER Window--############
        self.renderWindow = self.vtkWidget.GetRenderWindow()
        self.renderWindow.AddRenderer(self.renderer)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.renderer)
        # '---------    Interactor  ----------'
        self.inter = self.renderWindow.GetInteractor()
        # ----!Stay in 2D View!-----
        self.inter.SetInteractorStyle(
            vtkInteractionStyle.vtkInteractorStyleImage())

        # '----------add keyboard observer---------'
        self.vtkWidget.AddObserver(vtk.vtkCommand.KeyPressEvent,
                                   self.keyboard_callback_func)
        self.cam = self.renderer.GetActiveCamera()
        if self.viewPlane == 'Coronal':
            # self.cam.SetFocalPoint(0, 0, 0)     # 设焦点
            # self.cam.SetPosition(0, 0, -1)  # Camera in Z so it display XY planes. # 设观察对象位
            self.cam.SetViewUp(
                0, 0, -1
            )  # Up direction is the X not the y. #(0,0,-1) for Coronal plane
        # self.cam.ComputeViewPlaneNormal()  # 自动

        self.renderer.ResetCamera()
        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)
        self.show()
        self.inter.Initialize()
Ejemplo n.º 54
0
    def __init__(self, is_horizontal=False):
        """creates the scalar bar"""
        self.scalar_bar = vtk.vtkScalarBarActor()
        self.color_function = vtk.vtkColorTransferFunction()
        self.color_function.SetNanColor(0., 0., 0.)
        self.is_shown = True
        self.is_horizontal = False

        #self.color_function.SetNanColor(0., 0., 0.)
        #self.color_function.SetColorSpaceToLab()
        #self.color_function.SetColorSpaceToRGB()
        #self.scalar_bar.SetDragable(True)
        #self.scalar_bar.SetPickable(True)

        # blue - low
        # red - high
        drange = [10., 20.]
        self.color_function.SetColorSpaceToHSV()
        self.color_function.HSVWrapOff()
        self.color_function.SetRange(*drange)
        self.color_function.AddRGBPoint(drange[0], 0.0, 0.0, 1.0)
        self.color_function.AddRGBPoint(drange[1], 1.0, 0.0, 0.0)

        self.scalar_bar.SetTitle("Title1")

        self.scalar_bar.SetLookupTable(self.color_function)
        #self.scalar_bar.SetNanColor(0., 0., 0.) # RGB color - black
        #self.scalar_bar.SetNanColor(1., 1., 1., 0.) # RGBA color - white

        # old
        #self.scalar_bar.SetHeight(0.9)
        #self.scalar_bar.SetWidth(0.20)  # the width is set first
        #self.scalar_bar.SetPosition(0.77, 0.1)
        if is_horizontal:
            # put the scalar bar at the top
            self.scalar_bar.SetOrientationToHorizontal()
            width = 0.95
            height = 0.15
            x = (1 - width) / 2.
            y = 1 - 0.02 - height
        else:
            # put the scalar bar at the right side
            self.scalar_bar.SetOrientationToVertical()

            width = 0.2
            height = 0.9
            x = 1 - 0.01 - width
            y = (1 - height) / 2.
            self.scalar_bar.SetPosition(x, y)

        # the width is set first
        # after the width is set, this is adjusted
        self.scalar_bar.SetHeight(height)
        self.scalar_bar.SetWidth(width)
        self.scalar_bar.SetPosition(x, y)

        prop_title = vtk.vtkTextProperty()
        prop_title.SetFontFamilyToArial()
        #prop_title.ItalicOff()
        prop_title.BoldOn()
        prop_title.ShadowOn()

        prop_label = vtk.vtkTextProperty()
        prop_label.BoldOff()
        prop_label.ShadowOn()

        #self.scalar_bar.SetTitleTextProperty(prop_title)
        #self.scalar_bar.SetLabelTextProperty(prop_label)
        self.scalar_bar.SetLabelFormat("%i")

        # allows 0-1 to be nice number when ranging values (gotta pick something)
        self.scalar_bar.SetNumberOfLabels(11)
        self.scalar_bar.SetMaximumNumberOfColors(11)

        #self.scalar_bar.VisibilityOff()  # first load -> scalar bar off
        #self.scalar_bar.ShadowOn()
        #self.scalar_bar.RepositionableOn()
        self.scalar_bar.VisibilityOff()
Ejemplo n.º 55
0
from vtk.util.misc import vtkGetDataRoot

VTK_DATA_ROOT = vtkGetDataRoot()

# This example demonstrates the use of multiline 2D text using
# vtkTextMappers.  It shows several justifications as well as single-line
# and multiple-line text inputs.
#
# First we include the VTK Tcl packages which will make available
# all of the vtk commands to Tcl
#
font_size = 14
# Create the text mappers and the associated Actor2Ds.
# The font and text properties (except justification) are the same for each
# single line mapper. Let's create a common text property object
singleLineTextProp = vtk.vtkTextProperty()
singleLineTextProp.SetFontSize(font_size)
singleLineTextProp.SetFontFamilyToArial()
singleLineTextProp.BoldOff()
singleLineTextProp.ItalicOff()
singleLineTextProp.ShadowOff()
# The font and text properties (except justification) are the same for each
# multi line mapper. Let's create a common text property object
multiLineTextProp = vtk.vtkTextProperty()
multiLineTextProp.ShallowCopy(singleLineTextProp)
multiLineTextProp.BoldOn()
multiLineTextProp.ItalicOn()
multiLineTextProp.ShadowOn()
# The text is on a single line and bottom-justified.
singleLineTextB = vtk.vtkTextMapper()
singleLineTextB.SetInput("Single line (bottom)")
Ejemplo n.º 56
0
 def visualize(self, images, image_pos_pat, image_ori_pat, sub, postS, interact=True):
     '''Display and render volumes, reference frames, actors and widgets'''
     if(sub):
         #subtract volumes based on indicated postS            
         # define image based on subtraction of postS -preS
         image = self.subImage(images, postS)
     else:
         image = images[postS]            
          
     # Proceed to build reference frame for display objects based on DICOM coords   
     [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat)
     
     # get info from image before visualization
     self.dims = self.transformed_image.GetDimensions()
     print "Image Dimensions"
     print self.dims
     self.T1spacing = self.transformed_image.GetSpacing()
     print "Image Spacing"
     print self.T1spacing
     self.T1origin = self.transformed_image.GetOrigin()
     print "Image Origin"
     print self.T1origin
     self.T1extent = list(self.transformed_image.GetExtent())
     print "Image Extent"
     print self.T1extent
         
     # Set up ortogonal planes
     self.xImagePlaneWidget.SetInputData( self.transformed_image )
     self.xImagePlaneWidget.SetPlaneOrientationToXAxes()
     self.xImagePlaneWidget.SetSliceIndex(0)
     self.yImagePlaneWidget.SetInputData( self.transformed_image )
     self.yImagePlaneWidget.SetPlaneOrientationToYAxes()
     self.yImagePlaneWidget.SetSliceIndex(0)
     self.zImagePlaneWidget.SetInputData( self.transformed_image )
     self.zImagePlaneWidget.SetPlaneOrientationToZAxes()
     self.zImagePlaneWidget.SetSliceIndex(0)
         
     self.xImagePlaneWidget.On()
     self.yImagePlaneWidget.On()
     self.zImagePlaneWidget.On()
     
     # set up cube actor with Orientation(A-P, S-I, L-R) using transform_cube
     # Set up to ALS (+X=A, +Y=S, +Z=L) source:
     cube = vtk.vtkAnnotatedCubeActor()
     cube.SetXPlusFaceText( "L" );
     cube.SetXMinusFaceText( "R" );
     cube.SetYPlusFaceText( "A" );
     cube.SetYMinusFaceText( "P" );
     cube.SetZPlusFaceText( "S" );
     cube.SetZMinusFaceText( "I" );
     cube.SetFaceTextScale( 0.5 );
     cube.GetAssembly().SetUserTransform( transform_cube );
         
     # Set UP the axes
     axes2 = vtk.vtkAxesActor()
     axes2.SetShaftTypeToCylinder();
     #axes2.SetUserTransform( transform_cube );         
     axes2.SetTotalLength( 1.5, 1.5, 1.5 );
     axes2.SetCylinderRadius( 0.500 * axes2.GetCylinderRadius() );
     axes2.SetConeRadius( 1.025 * axes2.GetConeRadius() );
     axes2.SetSphereRadius( 1.500 * axes2.GetSphereRadius() );
 
     tprop2 = axes2.GetXAxisCaptionActor2D()
     tprop2.GetCaptionTextProperty();
 
     assembly = vtk.vtkPropAssembly();
     assembly.AddPart( axes2 );
     assembly.AddPart( cube );
     
     widget = vtk.vtkOrientationMarkerWidget();
     widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 );
     widget.SetOrientationMarker( assembly );
     widget.SetInteractor( self.iren1 );
     widget.SetViewport( 0.0, 0.0, 0.4, 0.4 );
     widget.SetEnabled( 1 );
     widget.InteractiveOff();
                 
     # Create a text property for both cube axes
     tprop = vtk.vtkTextProperty()
     tprop.SetColor(1, 1, 1)
     tprop.ShadowOff()
     
     # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
     # draw the axes.  Add the actor to the renderer.
     axes = vtk.vtkCubeAxesActor2D()
     axes.SetInputData(self.transformed_image)
     axes.SetCamera(self.renderer1.GetActiveCamera())
     axes.SetLabelFormat("%6.4g")
     axes.SetFlyModeToOuterEdges()
     axes.SetFontFactor(1.2)
     axes.SetAxisTitleTextProperty(tprop)
     axes.SetAxisLabelTextProperty(tprop)      
     self.renderer1.AddViewProp(axes)
     
     ############
     # bounds and initialize camera
     bounds = self.transformed_image.GetBounds()
     self.renderer1.ResetCamera(bounds)    
     self.renderer1.ResetCameraClippingRange()
     self.camera.SetViewUp(0.0,-1.0,0.0)
     self.camera.Azimuth(315)
     
     # Initizalize
     self.renWin1.Modified()
     self.renWin1.Render()
     self.renderer1.Render()
     
     if(interact==True):
         interactor = self.renWin1.GetInteractor()
         interactor.Start()
                         
     return
Ejemplo n.º 57
0
def main():

    argc = len(sys.argv)

    # Verify input arguments
    if argc != 2:
        print "Usage: ", sys.argv[0], " FolderName"
        return sys.exit(1)

    folder = sys.argv[1]

    # Read all the DICOM files in the specified directory.
    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(folder)
    reader.Update()

    # Visualize
    imageViewer = vtk.vtkImageViewer2()
    imageViewer.SetInputConnection(reader.GetOutputPort())

    # slice status message
    sliceTextProp = vtk.vtkTextProperty()
    sliceTextProp.SetFontFamilyToCourier()
    sliceTextProp.SetFontSize(20)
    sliceTextProp.SetVerticalJustificationToBottom()
    sliceTextProp.SetJustificationToLeft()

    sliceTextMapper = vtk.vtkTextMapper()
    msg = "Slice {} out of {}".format(imageViewer.GetSliceMin() + 1, \
                                      imageViewer.GetSliceMax() + 1)
    sliceTextMapper.SetInput(msg)
    sliceTextMapper.SetTextProperty(sliceTextProp)

    sliceTextActor = vtk.vtkActor2D()
    sliceTextActor.SetMapper(sliceTextMapper)
    sliceTextActor.SetPosition(15, 10)

    # usage hint message
    usageTextProp = vtk.vtkTextProperty()
    usageTextProp.SetFontFamilyToCourier()
    usageTextProp.SetFontSize(14)
    usageTextProp.SetVerticalJustificationToTop()
    usageTextProp.SetJustificationToLeft()

    usageTextMapper = vtk.vtkTextMapper()
    usageTextMapper.SetInput(
        "- Slice with mouse wheel\n  or Up/Down-Key\n- Zoom with pressed right\n  mouse button while dragging"
    )
    usageTextMapper.SetTextProperty(usageTextProp)

    usageTextActor = vtk.vtkActor2D()
    usageTextActor.SetMapper(usageTextMapper)
    usageTextActor.GetPositionCoordinate(
    ).SetCoordinateSystemToNormalizedDisplay()
    usageTextActor.GetPositionCoordinate().SetValue(0.05, 0.95)

    interactor = vtk.vtkInteractorStyleImage()
    #interactor.SetImageViewer(imageViewer)
    #interactor.SetStatusMapper(sliceTextMapper)

    #imageViewer.SetupInteractor(renWin)
    #renderWindowInteractor.SetInteractorStyle(myInteractorStyle)
    # add slice status message and usage hint message to the renderer
    imageViewer.GetRenderer().AddActor2D(sliceTextActor)
    imageViewer.GetRenderer().AddActor2D(usageTextActor)
Ejemplo n.º 58
0
def main():
    font_size = 24

    # Create the text mappers and the associated Actor2Ds.
    # The font and text properties (except justification) are the same for
    # each single line mapper. Let's create a common text property object
    singleLineTextProp = vtk.vtkTextProperty()
    singleLineTextProp.SetFontSize(font_size)
    singleLineTextProp.SetFontFamilyToArial()
    singleLineTextProp.BoldOff()
    singleLineTextProp.ItalicOff()
    singleLineTextProp.ShadowOff()

    # The font and text properties (except justification) are the same for
    # each multi line mapper. Let's create a common text property object
    multiLineTextProp = vtk.vtkTextProperty()
    multiLineTextProp.ShallowCopy(singleLineTextProp)
    multiLineTextProp.BoldOn()
    multiLineTextProp.ItalicOn()
    multiLineTextProp.ShadowOn()
    multiLineTextProp.SetLineSpacing(0.8)

    colors = vtk.vtkNamedColors()

    # The text is on a single line and bottom-justified.
    singleLineTextB = vtk.vtkTextMapper()
    singleLineTextB.SetInput("Single line (bottom)")
    tprop = singleLineTextB.GetTextProperty()
    tprop.ShallowCopy(singleLineTextProp)
    tprop.SetVerticalJustificationToBottom()
    tprop.SetColor(colors.GetColor3d("Tomato"))

    singleLineTextActorB = vtk.vtkActor2D()
    singleLineTextActorB.SetMapper(singleLineTextB)
    singleLineTextActorB.GetPositionCoordinate(
    ).SetCoordinateSystemToNormalizedDisplay()
    singleLineTextActorB.GetPositionCoordinate().SetValue(0.05, 0.85)

    # The text is on a single line and center-justified (vertical justification).
    singleLineTextC = vtk.vtkTextMapper()
    singleLineTextC.SetInput("Single line (centered)")
    tprop = singleLineTextC.GetTextProperty()
    tprop.ShallowCopy(singleLineTextProp)
    tprop.SetVerticalJustificationToCentered()
    tprop.SetColor(colors.GetColor3d("DarkGreen"))
    singleLineTextActorC = vtk.vtkActor2D()

    singleLineTextActorC.SetMapper(singleLineTextC)
    singleLineTextActorC.GetPositionCoordinate(
    ).SetCoordinateSystemToNormalizedDisplay()
    singleLineTextActorC.GetPositionCoordinate().SetValue(0.05, 0.75)

    # The text is on a single line and top-justified.
    singleLineTextT = vtk.vtkTextMapper()
    singleLineTextT.SetInput("Single line (top)")
    tprop = singleLineTextT.GetTextProperty()
    tprop.ShallowCopy(singleLineTextProp)
    tprop.SetVerticalJustificationToTop()
    tprop.SetColor(colors.GetColor3d("Peacock"))

    singleLineTextActorT = vtk.vtkActor2D()
    singleLineTextActorT.SetMapper(singleLineTextT)
    singleLineTextActorT.GetPositionCoordinate(
    ).SetCoordinateSystemToNormalizedDisplay()
    singleLineTextActorT.GetPositionCoordinate().SetValue(0.05, 0.65)

    # The text is on multiple lines and left- and top-justified.
    textMapperL = vtk.vtkTextMapper()
    textMapperL.SetInput("This is\nmulti-line\ntext output\n(left-top)")
    tprop = textMapperL.GetTextProperty()
    tprop.ShallowCopy(multiLineTextProp)
    tprop.SetJustificationToLeft()
    tprop.SetVerticalJustificationToTop()
    tprop.SetColor(colors.GetColor3d("Tomato"))

    textActorL = vtk.vtkActor2D()
    textActorL.SetMapper(textMapperL)
    textActorL.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
    textActorL.GetPositionCoordinate().SetValue(0.05, 0.5)

    # The text is on multiple lines and center-justified (both horizontal and vertical).
    textMapperC = vtk.vtkTextMapper()
    textMapperC.SetInput("This is\nmulti-line\ntext output\n(centered)")
    tprop = textMapperC.GetTextProperty()
    tprop.ShallowCopy(multiLineTextProp)
    tprop.SetJustificationToCentered()
    tprop.SetVerticalJustificationToCentered()
    tprop.SetColor(colors.GetColor3d("DarkGreen"))

    textActorC = vtk.vtkActor2D()
    textActorC.SetMapper(textMapperC)
    textActorC.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
    textActorC.GetPositionCoordinate().SetValue(0.5, 0.5)

    # The text is on multiple lines and right- and bottom-justified.
    textMapperR = vtk.vtkTextMapper()
    textMapperR.SetInput("This is\nmulti-line\ntext output\n(right-bottom)")
    tprop = textMapperR.GetTextProperty()
    tprop.ShallowCopy(multiLineTextProp)
    tprop.SetJustificationToRight()
    tprop.SetVerticalJustificationToBottom()
    tprop.SetColor(colors.GetColor3d("Peacock"))

    textActorR = vtk.vtkActor2D()
    textActorR.SetMapper(textMapperR)
    textActorR.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
    textActorR.GetPositionCoordinate().SetValue(0.95, 0.5)

    # Draw the grid to demonstrate the placement of the text.

    # Set up the necessary points.
    Pts = vtk.vtkPoints()
    Pts.InsertNextPoint(0.05, 0.0, 0.0)
    Pts.InsertNextPoint(0.05, 1.0, 0.0)
    Pts.InsertNextPoint(0.5, 0.0, 0.0)
    Pts.InsertNextPoint(0.5, 1.0, 0.0)
    Pts.InsertNextPoint(0.95, 0.0, 0.0)
    Pts.InsertNextPoint(0.95, 1.0, 0.0)
    Pts.InsertNextPoint(0.0, 0.5, 0.0)
    Pts.InsertNextPoint(1.0, 0.5, 0.0)
    Pts.InsertNextPoint(0.00, 0.85, 0.0)
    Pts.InsertNextPoint(0.50, 0.85, 0.0)
    Pts.InsertNextPoint(0.00, 0.75, 0.0)
    Pts.InsertNextPoint(0.50, 0.75, 0.0)
    Pts.InsertNextPoint(0.00, 0.65, 0.0)
    Pts.InsertNextPoint(0.50, 0.65, 0.0)

    # Set up the lines that use these points.
    Lines = vtk.vtkCellArray()
    Lines.InsertNextCell(2)
    Lines.InsertCellPoint(0)
    Lines.InsertCellPoint(1)
    Lines.InsertNextCell(2)
    Lines.InsertCellPoint(2)
    Lines.InsertCellPoint(3)
    Lines.InsertNextCell(2)
    Lines.InsertCellPoint(4)
    Lines.InsertCellPoint(5)
    Lines.InsertNextCell(2)
    Lines.InsertCellPoint(6)
    Lines.InsertCellPoint(7)
    Lines.InsertNextCell(2)
    Lines.InsertCellPoint(8)
    Lines.InsertCellPoint(9)
    Lines.InsertNextCell(2)
    Lines.InsertCellPoint(10)
    Lines.InsertCellPoint(11)
    Lines.InsertNextCell(2)
    Lines.InsertCellPoint(12)
    Lines.InsertCellPoint(13)

    # Create a grid that uses these points and lines.
    Grid = vtk.vtkPolyData()
    Grid.SetPoints(Pts)
    Grid.SetLines(Lines)
    # Set up the coordinate system.
    normCoords = vtk.vtkCoordinate()
    normCoords.SetCoordinateSystemToNormalizedViewport()

    # Set up the mapper and actor (2D) for the grid.
    mapper = vtk.vtkPolyDataMapper2D()
    mapper.SetInputData(Grid)
    mapper.SetTransformCoordinate(normCoords)
    gridActor = vtk.vtkActor2D()
    gridActor.SetMapper(mapper)
    gridActor.GetProperty().SetColor(colors.GetColor3d("DimGray"))

    # Create the Renderer, RenderWindow, and RenderWindowInteractor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()

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

    # Add the actors to the renderer set the background and size zoom in closer to the image render
    renderer.AddActor2D(textActorL)
    renderer.AddActor2D(textActorC)
    renderer.AddActor2D(textActorR)
    renderer.AddActor2D(singleLineTextActorB)
    renderer.AddActor2D(singleLineTextActorC)
    renderer.AddActor2D(singleLineTextActorT)
    renderer.AddActor2D(gridActor)

    renderer.SetBackground(colors.GetColor3d("Silver"))
    renderWindow.SetSize(640, 480)
    renderer.GetActiveCamera().Zoom(1.5)

    # Enable user interface interactor
    interactor.Initialize()
    renderWindow.Render()
    interactor.Start()
Ejemplo n.º 59
0
def main():
    colors = vtk.vtkNamedColors()

    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(10)
    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("White"))
        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(100, 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()
    rendererSize = 200
    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("SlateGray"))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(30)
            renderers[index].GetActiveCamera().Zoom(0.9)
            renderers[index].ResetCameraClippingRange()

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

    renderWindow.Render()
    interactor.Start()
Ejemplo n.º 60
0
    def _plotInternal(self):
        """Overrides baseclass implementation."""
        tmpLevels = []
        tmpColors = []
        tmpLineWidths = []
        tmpLineTypes = []

        linewidth = self._gm.linewidths
        self.extendAttribute(linewidth, default=1.0)

        linetype = self._gm.linetypes
        self.extendAttribute(linetype, default='solid')

        plotting_dataset_bounds = self.getPlottingBounds()
        x1, x2, y1, y2 = plotting_dataset_bounds

        for i, lv_tmp in enumerate(self._contourLevels):
            if i == 0:
                W = linewidth[i]
                S = linetype[i]
                C = [self._contourColors[i]]
                if lv_tmp == 1.e20:
                    L = [-1.e20]
                else:
                    L = [lv_tmp]
            else:
                if W == linewidth[i] and S == linetype[i]:
                    # Ok same style and width, lets keep going
                    L.append(lv_tmp)
                    C.append(self._contourColors[i])
                else:
                    tmpLevels.append(L)
                    tmpColors.append(C)
                    tmpLineWidths.append(W)
                    tmpLineTypes.append(S)
                    L = [lv_tmp]
                    C = [self._contourColors[i]]
                    W = linewidth[i]
                    S = linetype[i]

        tmpLevels.append(L)
        tmpColors.append(C)
        tmpLineWidths.append(W)
        tmpLineTypes.append(S)

        cots = []
        textprops = []
        luts = []

        actors = []
        mappers = []

        if self._gm.label and (self._gm.text or self._gm.textcolors):
            # Text objects:
            if self._gm.text:
                texts = self._gm.text
                while len(texts) < len(self._contourLevels):
                    texts.append(texts[-1])
            else:
                texts = [None] * len(self._contourLevels)

            # Custom colors:
            if self._gm.textcolors:
                colorOverrides = self._gm.textcolors
                while len(colorOverrides) < len(self._contourLevels):
                    colorOverrides.append(colorOverrides[-1])
            else:
                colorOverrides = [None] * len(self._gm.text)

            # Custom background colors and opacities:
            backgroundColors = self._gm.labelbackgroundcolors
            if backgroundColors:
                while len(backgroundColors) < len(self._contourLevels):
                    backgroundColors.append(backgroundColors[-1])
            backgroundOpacities = self._gm.labelbackgroundopacities
            if backgroundOpacities:
                while len(backgroundOpacities) < len(self._contourLevels):
                    backgroundOpacities.append(backgroundOpacities[-1])

        countLevels = 0
        vp = self._resultDict.get('ratio_autot_viewport', [
            self._template.data.x1, self._template.data.x2,
            self._template.data.y1, self._template.data.y2
        ])
        dataset_renderer = None
        xScale, yScale = (1, 1)
        for i, l in enumerate(tmpLevels):
            numLevels = len(l)

            cot = vtk.vtkContourFilter()
            if self._hasCellData:
                cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
            else:
                cot.SetInputData(self._vtkDataSet)
            cot.SetNumberOfContours(numLevels)

            for n in range(numLevels):
                cot.SetValue(n, l[n])
            # TODO remove update
            cot.Update()

            lut = vtk.vtkLookupTable()
            lut.SetNumberOfTableValues(len(tmpColors[i]))
            cmap = self.getColorMap()
            for n, col in enumerate(tmpColors[i]):
                r, g, b, a = self.getColorIndexOrRGBA(cmap, col)
                lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.)

            # Setup isoline labels
            if self._gm.label:
                # Setup label mapping array:
                tpropMap = vtk.vtkDoubleArray()
                tpropMap.SetNumberOfComponents(1)
                tpropMap.SetNumberOfTuples(numLevels)
                for n, val in enumerate(l):
                    tpropMap.SetTuple(n, [val])

                # Prep text properties:
                tprops = vtk.vtkTextPropertyCollection()
                if self._gm.text or self._gm.textcolors:
                    ttexts = texts[countLevels:(countLevels + len(l))]

                    for idx, tc in enumerate(ttexts):
                        if vcs.queries.istextcombined(tc):
                            tt, to = tuple(tc.name.split(":::"))
                        elif tc is None:
                            tt = "default"
                            to = "default"
                        elif vcs.queries.istexttable(tc):
                            tt = tc.name
                            to = "default"
                        elif vcs.queries.istextorientation(tc):
                            to = tc.name
                            tt = "default"
                        elif isinstance(tc, str):
                            sp = tc.split(":::")
                            if len(sp) == 2:
                                tt = sp[0]
                                to = sp[1]
                            else:  # Hum don't know what do do with this
                                if sp[0] in vcs.listelements("textcombined"):
                                    tc = vcs.gettextcombined(tc)
                                    tt, to = tuple(tc.name.split(":::"))
                                elif sp[0] in vcs.listelements(
                                        "textorientation"):
                                    to = sp[0]
                                    tt = "default"
                                elif sp[0] in vcs.listelements("texttable"):
                                    tt = sp[0]
                                    to = "default"

                        colorOverride = colorOverrides[countLevels + idx]
                        if colorOverride is not None:
                            tt = vcs.createtexttable(None, tt)
                            tt.color = colorOverride
                            tt = tt.name
                        if backgroundColors is not None:
                            texttbl = vcs.gettexttable(tt)
                            texttbl.backgroundcolor = backgroundColors[
                                countLevels + idx]
                        if backgroundOpacities is not None:
                            texttbl = vcs.gettexttable(tt)
                            texttbl.backgroundopacity = backgroundOpacities[
                                countLevels + idx]
                        tprop = vtk.vtkTextProperty()
                        vcs2vtk.prepTextProperty(
                            tprop,
                            self._context().renWin.GetSize(),
                            to,
                            tt,
                            cmap=cmap)
                        tprops.AddItem(tprop)
                        if colorOverride is not None:
                            del (vcs.elements["texttable"][tt])
                else:  # No text properties specified. Use the default:
                    tprop = vtk.vtkTextProperty()
                    vcs2vtk.prepTextProperty(tprop,
                                             self._context().renWin.GetSize(),
                                             cmap=cmap)
                    tprops.AddItem(tprop)
                textprops.append(tprops)

                mapper = vtk.vtkLabeledContourMapper()
                mapper.SetTextProperties(tprops)
                mapper.SetTextPropertyMapping(tpropMap)
                mapper.SetLabelVisibility(1)
                mapper.SetSkipDistance(self._gm.labelskipdistance)

                pdMapper = mapper.GetPolyDataMapper()

                luts.append([lut, [l[0], l[-1], False]])
            else:  # No isoline labels:
                mapper = vtk.vtkPolyDataMapper()
                pdMapper = mapper
                luts.append([lut, [l[0], l[-1], False]])
            pdMapper.SetLookupTable(lut)
            pdMapper.SetScalarRange(l[0], l[-1])
            pdMapper.SetScalarModeToUsePointData()

            stripper = vtk.vtkStripper()
            stripper.SetInputConnection(cot.GetOutputPort())
            mapper.SetInputConnection(stripper.GetOutputPort())
            # TODO remove update, make pipeline
            stripper.Update()
            mappers.append(mapper)
            cots.append(cot)

            # Create actor to add to scene
            act = vtk.vtkActor()
            act.SetMapper(mapper)
            # Set line properties here
            p = act.GetProperty()
            p.SetLineWidth(tmpLineWidths[i])
            vcs2vtk.stippleLine(p, tmpLineTypes[i])

            actors.append([act, plotting_dataset_bounds])

            # create a new renderer for this mapper
            # (we need one for each mapper because of cmaera flips)
            dataset_renderer, xScale, yScale = self._context().fitToViewport(
                act,
                vp,
                wc=plotting_dataset_bounds,
                geoBounds=self._vtkDataSetBoundsNoMask,
                geo=self._vtkGeoTransform,
                priority=self._template.data.priority,
                create_renderer=(dataset_renderer is None))

            countLevels += len(l)
        if len(textprops) > 0:
            self._resultDict["vtk_backend_contours_labels_text_properties"] = \
                textprops
        if len(luts) > 0:
            if self._gm.label:
                self._resultDict["vtk_backend_labeled_luts"] = luts
            else:
                self._resultDict["vtk_backend_luts"] = luts
        if len(cots) > 0:
            self._resultDict["vtk_backend_contours"] = cots

        if self._maskedDataMapper is not None:
            mappers.insert(0, self._maskedDataMapper)
            act = vtk.vtkActor()
            act.SetMapper(self._maskedDataMapper)
            actors.append(
                [act, self._maskedDataMapper, plotting_dataset_bounds])
            # create a new renderer for this mapper
            # (we need one for each mapper because of cmaera flips)
            self._context().fitToViewport(
                act,
                vp,
                wc=plotting_dataset_bounds,
                geoBounds=self._vtkDataSetBoundsNoMask,
                geo=self._vtkGeoTransform,
                priority=self._template.data.priority,
                create_renderer=True)

        self._resultDict["vtk_backend_actors"] = actors

        t = self._originalData1.getTime()
        if self._originalData1.ndim > 2:
            z = self._originalData1.getAxis(-3)
        else:
            z = None
        kwargs = {
            "vtk_backend_grid": self._vtkDataSet,
            "dataset_bounds": self._vtkDataSetBounds,
            "plotting_dataset_bounds": plotting_dataset_bounds,
            "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask,
            "vtk_backend_geo": self._vtkGeoTransform
        }
        if ("ratio_autot_viewport" in self._resultDict):
            kwargs["ratio_autot_viewport"] = vp
        self._resultDict.update(self._context().renderTemplate(
            self._template, self._data1, self._gm, t, z, **kwargs))

        if self._context().canvas._continents is None:
            self._useContinents = False
        if self._useContinents:
            projection = vcs.elements["projection"][self._gm.projection]
            continents_renderer, xScale, yScale = self._context(
            ).plotContinents(plotting_dataset_bounds, projection,
                             self._dataWrapModulo, vp,
                             self._template.data.priority, **kwargs)