Example #1
0
    def leftDownEvt(self, obj, event):
        if self.leftDown == False:
            #Get current camera position
            renWin = self.GetInteractor().GetRenderWindow()
            renderer = renWin.GetRenderers().GetFirstRenderer()
            #Get click location and compute world coordinates
            click = self.GetInteractor().GetEventPosition()
            coord = vtk.vtkCoordinate()
            coord.SetCoordinateSystemToDisplay()
            coord.SetValue(click[0], click[1], -1)
            clickPos = coord.GetComputedWorldValue(renderer)
            #Update position
            self.click = [clickPos[0], clickPos[1], clickPos[2]]
            #Get camera focal point
            cam = renderer.GetActiveCamera()
            camFoc = cam.GetFocalPoint()
            camFocCoord = vtk.vtkCoordinate()
            camFocCoord.SetCoordinateSystemToDisplay()
            camFocCoord.SetValue(camFoc[0], camFoc[1], camFoc[2])
            foc = camFocCoord.GetComputedWorldValue(renderer)
            #Get camera position
            camPos = cam.GetPosition()
            camPosCoord = vtk.vtkCoordinate()
            camPosCoord.SetCoordinateSystemToDisplay()
            camPosCoord.SetValue(camPos[0], camPos[1], camPos[2])
            pos = camPosCoord.GetComputedWorldValue(renderer)
            #Update variables
            self.click = [clickPos[0], clickPos[1], clickPos[2]]
            self.pos = [pos[0], pos[1], pos[2]]
            self.foc = [foc[0], foc[1], 0]
            self.leftDown = True

        return
def get_camera_coordinate(renderer, mode='world'):
    choices = ['world', 'display']
    if mode not in choices:
        raise ValueError("Invalid mode, select one from %s" % choices)

    #Get camera
    cam = renderer.GetActiveCamera()

    #Get focal point
    foc_ = cam.GetFocalPoint()
    foc_coord = vtk.vtkCoordinate()
    foc_coord.SetCoordinateSystemToDisplay()
    foc_coord.SetValue(foc_[0], foc_[1], foc_[2])

    #Get position
    pos_ = cam.GetPosition()
    pos_coord = vtk.vtkCoordinate()
    pos_coord.SetCoordinateSystemToDisplay()
    pos_coord.SetValue(pos_[0], pos_[1], pos_[2])

    if mode == 'world':
        foc = foc_coord.GetComputedWorldValue(renderer)
        pos = pos_coord.GetComputedWorldValue(renderer)
    elif mode == 'display':
        foc = foc_coord.GetComputedDisplayValue(renderer)
        pos = pos_coord.GetComputedDisplayValue(renderer)

    return pos, foc
Example #3
0
    def Move2d(self, obj, event):
        self.cursor.__move__()
        if self.leftDown == True:
            #Get render window  components
            renWin = self.GetInteractor().GetRenderWindow()
            renderer = renWin.GetRenderers().GetFirstRenderer()
            #Remove old contour actor
            renderer.RemoveActor(self.actor)
            #Compute click coordinates
            move = self.GetInteractor().GetEventPosition()
            coord = vtk.vtkCoordinate()
            coord.SetCoordinateSystemToDisplay()
            coord.SetValue(move[0], move[1], 0)
            movePos = coord.GetComputedWorldValue(renderer)

            #Record point
            self.points[1, :] = np.array([movePos[0], movePos[1]])

            self.actor = make_actor(self.points)

            self.actor.GetProperty().SetLineWidth(self.lw)
            self.actor.GetProperty().SetColor(self.lc)
            #Update actor position
            actPos = self.actor.GetPosition()
            self.actor.SetPosition(actPos[0], actPos[1], -1)

            renderer.AddActor(self.actor)
            renWin.Render()

            jsw = (self.points[0, :] - self.points[1, :])**2
            jsw = (jsw.sum()**0.5) * 0.148
            self.jsw = jsw

        if self.rightDown == True:
            #Get event position
            renWin = self.GetInteractor().GetRenderWindow()
            renderer = renWin.GetRenderers().GetFirstRenderer()
            move = self.GetInteractor().GetEventPosition()
            #Compute position in world coordinates
            coord = vtk.vtkCoordinate()
            coord.SetCoordinateSystemToDisplay()
            coord.SetValue(move[0], move[1], -1)
            pos = coord.GetComputedWorldValue(renderer)
            #Compute new location, opposite of the movement direction
            self.pos = [
                self.pos[0] - (pos[0] - self.click[0]),
                self.pos[1] - (pos[1] - self.click[1]), self.pos[2]
            ]
            #Update camera
            cam = renderer.GetActiveCamera()
            cam.SetPosition(self.pos[0], self.pos[1], self.pos[2])
            cam.SetFocalPoint(self.pos[0], self.pos[1], self.foc[2])
            renWin.Render()

        return
Example #4
0
    def __build_cross_lines(self):
        renderer = self.slice_data.overlay_renderer

        cross = vtk.vtkCursor3D()
        cross.AllOff()
        cross.AxesOn()
        self.cross = cross

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

        cross_mapper = vtk.vtkPolyDataMapper()
        cross_mapper.SetInput(cross.GetOutput())
        #cross_mapper.SetTransformCoordinate(c)

        p = vtk.vtkProperty()
        p.SetColor(1, 0, 0)

        cross_actor = vtk.vtkActor()
        cross_actor.SetMapper(cross_mapper)
        cross_actor.SetProperty(p)
        cross_actor.VisibilityOff()
        # Only the slices are pickable
        cross_actor.PickableOff()
        self.cross_actor = cross_actor

        renderer.AddActor(cross_actor)
Example #5
0
    def __init__(self, list):
        self.list = list

        self.points = vtk.vtkPoints()

        self.cells = vtk.vtkCellArray()
        self.cells.Initialize()

        self.line = vtk.vtkLine()

        self.update()

        self.polyData = vtk.vtkPolyData()
        self.polyData.Initialize()
        self.polyData.SetPoints(self.points)
        self.polyData.SetLines(self.cells)
        self.polyData.Modified()

        self.coordinate = vtk.vtkCoordinate()
        self.coordinate.SetCoordinateSystemToDisplay()

        self.lassoMapper = vtk.vtkPolyDataMapper2D()
        self.lassoMapper.SetInput(self.polyData)
        self.lassoMapper.SetTransformCoordinate(self.coordinate)
        self.lassoMapper.ScalarVisibilityOn()
        self.lassoMapper.SetScalarModeToUsePointData()

        self.lassoMapper.Update()

        self.actor = vtk.vtkActor2D()
        self.actor.SetMapper(self.lassoMapper)
        self.actor.GetProperty().SetLineWidth(2.0)
        self.actor.GetProperty().SetColor(1, 0, 0)
Example #6
0
def CreateViewportBox(colorfg,linewidth=3) :
	pts = vtk.vtkPoints()
	pts.SetNumberOfPoints(4)
	pts.SetPoint(0, 0.0, 0.0, 0.0)
	pts.SetPoint(1, 0.0, 1.0, 0.0)
	pts.SetPoint(2, 1.0, 1.0, 0.0)
	pts.SetPoint(3, 1.0, 0.0, 0.0)
	lines = vtk.vtkCellArray()
	lines.InsertNextCell(5)
	lines.InsertCellPoint(0)
	lines.InsertCellPoint(1)
	lines.InsertCellPoint(2)
	lines.InsertCellPoint(3)
	lines.InsertCellPoint(0)
	box = vtk.vtkPolyData()
	box.SetPoints(pts)
	box.SetLines(lines)

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

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

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

	return boxactor
Example #7
0
    def chooseTarget(self, obj, event):
        clickPos = self.GetInteractor().GetEventPosition()
        coordinate = vtk.vtkCoordinate()
        coordinate.SetCoordinateSystemToDisplay()
        coordinate.SetValue(clickPos[0], clickPos[1], 0)
        world = coordinate.GetComputedWorldValue(self.GetInteractor(
        ).GetRenderWindow().GetRenderers().GetFirstRenderer())
        self.target[0].set(world[0])
        self.target[1].set(world[1])

        sphere = vtk.vtkRegularPolygonSource()
        sphere.SetCenter(world[0], world[1], 0.0)
        sphere.SetRadius(2.0)
        sphere.SetNumberOfSides(50)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(sphere.GetOutputPort())
        mapper.SetScalarVisibility(0)

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(1.0, 0.0, 0.0)

        self.ren.AddActor(actor)
        self.RemoveObserver(self.leftag)

        self.ren.RemoveActor(self.txt_target)
        self.rw.Render()
Example #8
0
    def __build_cross_lines(self):
        renderer = self.slice_data.overlay_renderer

        cross = vtk.vtkCursor3D()
        cross.AllOff()
        cross.AxesOn()
        self.cross = cross

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

        cross_mapper = vtk.vtkPolyDataMapper()
        cross_mapper.SetInput(cross.GetOutput())
        #cross_mapper.SetTransformCoordinate(c)

        p = vtk.vtkProperty()
        p.SetColor(1, 0, 0)

        cross_actor = vtk.vtkActor()
        cross_actor.SetMapper(cross_mapper)
        cross_actor.SetProperty(p)
        cross_actor.VisibilityOff()
        # Only the slices are pickable
        cross_actor.PickableOff()
        self.cross_actor = cross_actor

        renderer.AddActor(cross_actor)
Example #9
0
 def GetDirections(self):
     """
 Return image directions of current view in world coordinates. Changes if
 image is rotated.
 """
     renderer = self.viewer.GetRenderer()
     # Get screen frame
     coordinate = vtk.vtkCoordinate()
     coordinate.SetCoordinateSystemToNormalizedDisplay()
     coordinate.SetValue(0.0, 0.0)  # Lower left
     lowerLeft = coordinate.GetComputedWorldValue(renderer)
     coordinate.SetValue(1.0, 0.0)  # Lower right
     lowerRight = coordinate.GetComputedWorldValue(renderer)
     coordinate.SetValue(0.0, 1.0)  # Upper left
     upperLeft = coordinate.GetComputedWorldValue(renderer)
     first1 = vtk.vtkVector3d()
     vtk.vtkMath.Subtract(lowerRight, lowerLeft, first1)
     tmp = vtk.vtkMath.Distance2BetweenPoints(lowerRight, lowerLeft)
     vtk.vtkMath.MultiplyScalar(first1, 1.0 / math.sqrt(tmp))
     second1 = vtk.vtkVector3d()
     vtk.vtkMath.Subtract(upperLeft, lowerLeft, second1)
     tmp = vtk.vtkMath.Distance2BetweenPoints(upperLeft, lowerLeft)
     vtk.vtkMath.MultiplyScalar(second1, 1.0 / math.sqrt(tmp))
     normal1 = vtk.vtkVector3d()
     vtk.vtkMath.Cross(first1, second1, normal1)
     return first1, second1, normal1
Example #10
0
    def resizeCallback(self, widget, event):
        """
    Callback for repositioning button. Only observe this if
    a button is added
    """
        curSize = widget.GetSize()
        if (curSize != self.lastSize):
            self.lastSize = curSize

            upperRight = vtk.vtkCoordinate()
            upperRight.SetCoordinateSystemToNormalizedDisplay()
            upperRight.SetValue(1.0, 1.0)

            renderer = self.viewer.GetRenderer()
            buttonRepresentation = self.buttonWidget.GetRepresentation()

            bds = [0] * 6
            sz = self.buttonSize
            bds[0] = upperRight.GetComputedDisplayValue(renderer)[0] - sz
            bds[1] = bds[0] + sz
            bds[2] = upperRight.GetComputedDisplayValue(renderer)[1] - sz
            bds[3] = bds[2] + sz
            bds[4] = bds[5] = 0.0

            # Scale to 1, default is .5
            buttonRepresentation.SetPlaceFactor(1)
            buttonRepresentation.PlaceWidget(bds)
 def __init__( self, name, interactor, **args ):
     self.vtk_coord = vtk.vtkCoordinate()
     self.vtk_coord.SetCoordinateSystemToNormalizedDisplay()
     self.StateChangedSignal = SIGNAL('StateChanged')
     self.process_mode = ProcessMode.Default
     self.currentSliders = {}
     self.slider_postions = [ [ [ 0.25, 0.75 ] ], [ [0.01,0.48], [0.52, 0.99 ] ], [ [0.01,0.3], [0.35,0.7], [0.75, 0.99 ] ], [ [0.01,0.24], [0.26,0.49], [0.51,0.74], [0.76, 0.99 ] ]    ]
     self.slidersVisible = [ True, False, False, False ]
     self.interactor = interactor
     self.InteractionState = None
     self.LastInteractionState = None
     self.activeSliceIndex = 0  
     self.name = name 
     self.groups = {}
     self.origin = args.get( 'origin', OriginPosition.Upper_Left )
     self.orientation = args.get( 'orientation', Orientation.Vertical )
     self.position = args.get( 'position', ( 0.0, 1.0 ) )
     self.buffer = args.get( 'buffer', ( 3, 3 ) )
     self.windowSizeRange = [ 200, 1200 ]
     self.minScale = 0.3
     self.buttons = []
     self.visible = False
     self.configurableFunctions = collections.OrderedDict()
     ButtonBarWidget.button_bars[ name ] = self
     self.updateWindowSize()
Example #12
0
 def __init__(self, name, interactor, **args):
     self.vtk_coord = vtk.vtkCoordinate()
     self.vtk_coord.SetCoordinateSystemToNormalizedDisplay()
     self.StateChangedSignal = SIGNAL('StateChanged')
     self.process_mode = ProcessMode.Default
     self.currentSliders = {}
     self.slider_postions = [[[0.25, 0.75]], [[0.01, 0.48], [0.52, 0.99]],
                             [[0.01, 0.3], [0.35, 0.7], [0.75, 0.99]],
                             [[0.01, 0.24], [0.26, 0.49], [0.51, 0.74],
                              [0.76, 0.99]]]
     self.slidersVisible = [True, False, False, False]
     self.interactor = interactor
     self.InteractionState = None
     self.LastInteractionState = None
     self.activeSliceIndex = 0
     self.name = name
     self.groups = {}
     self.origin = args.get('origin', OriginPosition.Upper_Left)
     self.orientation = args.get('orientation', Orientation.Vertical)
     self.position = args.get('position', (0.0, 1.0))
     self.buffer = args.get('buffer', (3, 3))
     self.fullButtonWindowSize = 1300
     self.buttons = []
     self.visible = False
     self.configurableFunctions = collections.OrderedDict()
     ButtonBarWidget.button_bars[name] = self
     self.updateWindowSize()
Example #13
0
    def draw_to_canvas(self, gc, canvas):
        """
        Draws to an wx.GraphicsContext.

        Parameters:
            gc: is a wx.GraphicsContext
            canvas: the canvas it's being drawn.
        """

        coord = vtk.vtkCoordinate()
        points = []
        for p in self.points:
            coord.SetValue(p)
            cx, cy = coord.GetComputedDoubleDisplayValue(canvas.evt_renderer)
            print cx, cy
            #  canvas.draw_circle((cx, cy), 2.5)
            points.append((cx, cy))

        if len(points) > 1:
            for (p0, p1) in zip(points[:-1:], points[1::]):
                r, g, b = self.colour
                canvas.draw_line(p0, p1, colour=(r*255, g*255, b*255, 255))

            if len(points) == 3:
                txt = u"%.3f° / %.3f°" % (self.GetValue(), 360.0 - self.GetValue())
                r, g, b = self.colour
                canvas.draw_arc(points[1], points[0], points[2], line_colour=(r*255, g*255, b*255, 255))
                canvas.draw_text_box(txt, (points[1][0], points[1][1]), txt_colour=MEASURE_TEXT_COLOUR, bg_colour=MEASURE_TEXTBOX_COLOUR)
Example #14
0
    def Coord3DtoDisplay(self, x, y, z, canvas):

        coord = vtk.vtkCoordinate()
        coord.SetValue(x, y, z)
        cx, cy = coord.GetComputedDisplayValue(canvas.evt_renderer)

        return (cx, cy)
Example #15
0
def CreateViewportBox(colorfg, linewidth=3):
    pts = vtk.vtkPoints()
    pts.SetNumberOfPoints(4)
    pts.SetPoint(0, 0.0, 0.0, 0.0)
    pts.SetPoint(1, 0.0, 1.0, 0.0)
    pts.SetPoint(2, 1.0, 1.0, 0.0)
    pts.SetPoint(3, 1.0, 0.0, 0.0)
    lines = vtk.vtkCellArray()
    lines.InsertNextCell(5)
    lines.InsertCellPoint(0)
    lines.InsertCellPoint(1)
    lines.InsertCellPoint(2)
    lines.InsertCellPoint(3)
    lines.InsertCellPoint(0)
    box = vtk.vtkPolyData()
    box.SetPoints(pts)
    box.SetLines(lines)

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

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

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

    return boxactor
Example #16
0
    def add_border(self, color=[1, 1, 1], width=2.0):
        """Add borders around the frame."""
        points = np.array([[1., 1., 0.], [0., 1., 0.], [0., 0., 0.],
                           [1., 0., 0.]])

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

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

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

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

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

        self.AddViewProp(actor)
        self.Modified()
        return actor
Example #17
0
    def __init__(self,
                 font_size=14,
                 color=(0.0, 0.0, 0.0),
                 relative_position=(0, 1),
                 absolute_offset=(10, -10),
                 text="",
                 **kwargs):
        kwargs["text"] = text
        kwargs['color'] = color
        kwargs["absolute_offset"] = absolute_offset
        kwargs["relative_position"] = relative_position
        kwargs["font_size"] = font_size

        self.actor = vtk.vtkTextActor()

        self.text_property = self.actor.GetTextProperty()
        self.text_property.SetFontFamilyToCourier()
        self.text_property.SetVerticalJustificationToTop()

        self.relpos_coord = vtk.vtkCoordinate()
        self.relpos_coord.SetCoordinateSystemToNormalizedViewport()
        self.actor.GetPositionCoordinate().SetCoordinateSystemToViewport()
        self.actor.GetPositionCoordinate().SetReferenceCoordinate(
            self.relpos_coord)

        self._process_kwargs(**kwargs)
Example #18
0
    def draw_to_canvas(self, gc, canvas):
        """
        Draws to an wx.GraphicsContext.

        Parameters:
            gc: is a wx.GraphicsContext
            canvas: the canvas it's being drawn.
        """
        coord = vtk.vtkCoordinate()
        points = []
        for p in self.points:
            coord.SetValue(p)
            cx, cy = coord.GetComputedDisplayValue(canvas.evt_renderer)
            #  canvas.draw_circle((cx, cy), 2.5)
            points.append((cx, cy))

        if len(points) > 1:
            for (p0, p1) in zip(points[:-1:], points[1::]):
                r, g, b = self.colour
                canvas.draw_line(p0,
                                 p1,
                                 colour=(r * 255, g * 255, b * 255, 255))

            txt = u"%.3f mm" % self.GetValue()
            canvas.draw_text_box(txt, ((points[0][0] + points[1][0]) / 2.0,
                                       (points[0][1] + points[1][1]) / 2.0),
                                 txt_colour=MEASURE_TEXT_COLOUR,
                                 bg_colour=MEASURE_TEXTBOX_COLOUR)
Example #19
0
    def Coord3DtoDisplay(self, x, y, z, canvas):

        coord = vtk.vtkCoordinate()
        coord.SetValue(x, y, z)
        cx, cy = coord.GetComputedDisplayValue(canvas.evt_renderer)

        return (cx, cy)
Example #20
0
    def _draw_line(self):
        line1 = vtk.vtkLineSource()
        line1.SetPoint1(self.points[0])
        line1.SetPoint2(self.points[1])

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

        arc = self.DrawArc()

        line = vtk.vtkAppendPolyData()
        line.AddInputConnection(line1.GetOutputPort())
        line.AddInputConnection(line2.GetOutputPort())
        line.AddInputConnection(arc.GetOutputPort())

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

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

        a = vtk.vtkActor2D()
        a.SetMapper(m)
        a.GetProperty().SetColor(self.colour)
        self.line_actor = a
Example #21
0
    def _draw_line(self):
        line1 = vtk.vtkLineSource()
        line1.SetPoint1(self.points[0])
        line1.SetPoint2(self.points[1])

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

        arc = self.DrawArc()

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

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

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

        a = vtk.vtkActor2D()
        a.SetMapper(m)
        a.GetProperty().SetColor(self.colour)
        self.line_actor = a
Example #22
0
    def add_border(self, color=[1, 1, 1], width=2.0):
        points = np.array([[1., 1., 0.],
                           [0., 1., 0.],
                           [0., 0., 0.],
                           [1., 0., 0.]])

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

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

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

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

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

        self.add_actor(actor)
Example #23
0
def addFrame(c=None, alpha=0.5, bg=None, lw=0.5):

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

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

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

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

    settings.plotter_instance.renderer.AddActor(fractor)
Example #24
0
def set2d_camera(renderer):
    cam = vtk.vtkCamera()
    cam.SetViewUp(0,-1,0)
    pos = cam.GetPosition()
    coord = vtk.vtkCoordinate()
    coord.SetCoordinateSystemToDisplay()
    coord.SetValue(pos[0], pos[1], pos[2])
    newpos = coord.GetComputedWorldValue(renderer)
    cam.SetPosition(newpos[0], newpos[1], -newpos[2])
    foc = cam.GetFocalPoint()
    focCoord = vtk.vtkCoordinate()
    focCoord.SetCoordinateSystemToDisplay()
    focCoord.SetValue(foc[0], foc[1], foc[2])
    newFoc = focCoord.GetComputedWorldValue(renderer)
    cam.SetFocalPoint(newFoc[0], newFoc[1], -1)
    cam.SetClippingRange(1e-5, 1)
    renderer.ResetCamera()        
Example #25
0
def computeBounds( renderer, normalized_display_position, size ):
    upperRight = vtk.vtkCoordinate()
    upperRight.SetCoordinateSystemToNormalizedDisplay()
    upperRight.SetValue( normalized_display_position[0], normalized_display_position[1] )
    bds = [0.0]*6
    bds[0] = upperRight.GetComputedDisplayValue(renderer)[0] - size[0]
    bds[1] = bds[0] + size[0]
    bds[2] = upperRight.GetComputedDisplayValue(renderer)[1] - size[1]
    bds[3] = bds[2] + size[1]
    return bds
Example #26
0
    def draw_to_canvas(self, gc, canvas):
        coord = vtk.vtkCoordinate()
        coord.SetCoordinateSystemToNormalizedDisplay()
        coord.SetValue(*self.position)
        x, y = coord.GetComputedDisplayValue(canvas.evt_renderer)

        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        #  font.SetWeight(wx.FONTWEIGHT_BOLD)
        font.SetSymbolicSize(self.symbolic_syze)
        canvas.draw_text(self.text, (x, y), font=font)
Example #27
0
    def draw_to_canvas(self, gc, canvas):
        coord = vtk.vtkCoordinate()
        coord.SetCoordinateSystemToNormalizedDisplay()
        coord.SetValue(*self.position)
        x, y = coord.GetComputedDisplayValue(canvas.evt_renderer)

        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        #  font.SetWeight(wx.FONTWEIGHT_BOLD)
        font.SetSymbolicSize(self.symbolic_syze)
        canvas.draw_text(self.text, (x, y), font=font)
Example #28
0
    def __init__(self, text, text_size=None):
        self.vtkTransform = None
        self.pos = vtk.vtkCoordinate()
        self.SetInput(text)
        self.GetTextProperty().BoldOn()
        self.GetTextProperty().SetColor(0.0, 0.0, 0.0)
        self.GetTextProperty().SetFontFamilyToArial()
        if text_size is not None:
            self.GetTextProperty().SetFontSize(text_size)

        self.pos.SetCoordinateSystemToWorld()
        coordView = vtk.vtkCoordinate()
        coordView.SetReferenceCoordinate(self.pos)
        coordView.SetCoordinateSystemToViewport()

        mapper = vtk.vtkPolyDataMapper2D()
        mapper.SetTransformCoordinate(coordView)

        self.SetMapper(mapper)
Example #29
0
def _3d_to_2d(plotter, xyz):
    # https://vtk.org/Wiki/VTK/Examples/Cxx/Utilities/Coordinate
    import vtk
    coordinate = vtk.vtkCoordinate()
    coordinate.SetCoordinateSystemToWorld()
    xy = list()
    for coord in xyz:
        coordinate.SetValue(*coord)
        xy.append(coordinate.GetComputedLocalDisplayValue(plotter.renderer))
    xy = np.array(xy, float).reshape(-1, 2)  # in case it's empty
    return xy
Example #30
0
 def computeBounds(self, normalized_display_position, size):
     renderer = self.getRenderer()
     upperRight = vtk.vtkCoordinate()
     upperRight.SetCoordinateSystemToNormalizedDisplay()
     upperRight.SetValue(normalized_display_position[0],
                         normalized_display_position[1])
     bds = [0.0] * 6
     bds[0] = upperRight.GetComputedDisplayValue(renderer)[0] - size[0]
     bds[1] = bds[0] + size[0]
     bds[2] = upperRight.GetComputedDisplayValue(renderer)[1] - size[1]
     bds[3] = bds[2] + size[1]
     return bds
Example #31
0
            def ViewportBorder(renderer, color, last):
                # points start at upper right and proceed anti-clockwise
                points = vtk.vtkPoints()
                points.SetNumberOfPoints(4)
                points.InsertPoint(0, 1, 1, 0)
                points.InsertPoint(1, 0, 1, 0)
                points.InsertPoint(2, 0, 0, 0)
                points.InsertPoint(3, 1, 0, 0)

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

                lines = vtk.vtkPolyLine()

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

                for i in range(0, 4):
                    lines.GetPointIds().SetId(i, i)

                if (last):
                    lines.GetPointIds().SetId(4, 0)

                cells.InsertNextCell(lines)

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

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

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

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

                renderer.AddViewProp(actor)
Example #32
0
    def __move__(self):
        #Get components
        interactor = self.interactorstyle.GetInteractor()
        renWin = interactor.GetRenderWindow()
        renderer = renWin.GetRenderers().GetFirstRenderer()
        #Remove old actor
        renderer.RemoveActor(self.actor)
        #Get mouse position
        pos = interactor.GetEventPosition()
        coord = vtk.vtkCoordinate()
        coord.SetCoordinateSystemToDisplay()
        coord.SetValue(pos[0], pos[1], 0)
        center = coord.GetComputedWorldValue(renderer)

        #Create line  objects
        points = vtk.vtkPoints()
        lines = vtk.vtkCellArray()
        polydata = vtk.vtkPolyData()

        #Line positions
        x1, x2 = center[0] - self.R, center[0] + self.R
        y1, y2 = center[1] - self.R, center[1] + self.R

        id1 = points.InsertNextPoint([x1, y1, 0])
        id2 = points.InsertNextPoint([x2, y2, 0])

        lines.InsertNextCell(2)
        lines.InsertCellPoint(id1)
        lines.InsertCellPoint(id2)

        x1, x2 = center[0] - self.R, center[0] + self.R
        y1, y2 = center[1] + self.R, center[1] - self.R

        id1 = points.InsertNextPoint([x1, y1, 0])
        id2 = points.InsertNextPoint([x2, y2, 0])

        lines.InsertNextCell(2)
        lines.InsertCellPoint(id1)
        lines.InsertCellPoint(id2)

        polydata.SetPoints(points)
        polydata.SetLines(lines)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(polydata)

        #Add to render window
        self.actor.SetMapper(mapper)
        self.actor.GetProperty().SetLineWidth(self.lw)
        self.actor.GetProperty().SetColor(self.color)

        renderer.AddActor(self.actor)
        renWin.Render()
Example #33
0
def button_display_coordinates(renderer, normalized_display_position, size):
    upperRight = vtk.vtkCoordinate()
    upperRight.SetCoordinateSystemToNormalizedDisplay()
    upperRight.SetValue(normalized_display_position[0],
                        normalized_display_position[1])
    bds = [0.0] * 6
    bds[0] = upperRight.GetComputedDisplayValue(renderer)[0] - size[0]
    bds[1] = bds[0] + size[0]
    bds[2] = upperRight.GetComputedDisplayValue(renderer)[1] - size[1]
    bds[3] = bds[2] + size[1]

    return bds
Example #34
0
    def OnPaint(self, evt, obj):
        size = self.canvas_renderer.GetSize()
        w, h = size
        if self._size != size:
            self._size = size
            self._resize_canvas(w, h)

        cam_modif_time = self.evt_renderer.GetActiveCamera().GetMTime()
        if (not self.modified) and cam_modif_time == self.last_cam_modif_time:
            return

        self.last_cam_modif_time = cam_modif_time

        self._array[:] = 0

        coord = vtk.vtkCoordinate()

        self.image.SetDataBuffer(self.rgb)
        self.image.SetAlphaBuffer(self.alpha)
        self.image.Clear()
        gc = wx.GraphicsContext.Create(self.image)
        if sys.platform != 'darwin':
            gc.SetAntialiasMode(0)

        self.gc = gc

        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        #  font.SetWeight(wx.BOLD)
        font = gc.CreateFont(font, (0, 0, 255))
        gc.SetFont(font)

        pen = wx.Pen(wx.Colour(255, 0, 0, 128), 2, wx.SOLID)
        brush = wx.Brush(wx.Colour(0, 255, 0, 128))
        gc.SetPen(pen)
        gc.SetBrush(brush)
        gc.Scale(1, -1)

        self._ordered_draw_list = sorted(self._follow_draw_list(),
                                         key=lambda x: x[0])
        for l, d in self._ordered_draw_list:  #sorted(self.draw_list, key=lambda x: x.layer if hasattr(x, 'layer') else 0):
            d.draw_to_canvas(gc, self)

        gc.Destroy()

        self.gc = None

        if self._drawn:
            self.bitmap = self.image.ConvertToBitmap()
            self.bitmap.CopyToBuffer(self._array, wx.BitmapBufferFormat_RGBA)

        self._cv_image.Modified()
        self.modified = False
        self._drawn = False
    def OnPaint(self, evt, obj):
        size = self.canvas_renderer.GetSize()
        w, h = size
        if self._size != size:
            self._size = size
            self._resize_canvas(w, h)

        cam_modif_time = self.evt_renderer.GetActiveCamera().GetMTime()
        if (not self.modified) and cam_modif_time == self.last_cam_modif_time:
            return

        self.last_cam_modif_time = cam_modif_time

        self._array[:] = 0

        coord = vtk.vtkCoordinate()

        self.image.SetDataBuffer(self.rgb)
        self.image.SetAlphaBuffer(self.alpha)
        self.image.Clear()
        gc = wx.GraphicsContext.Create(self.image)
        if sys.platform != 'darwin':
            gc.SetAntialiasMode(0)

        self.gc = gc

        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        #  font.SetWeight(wx.BOLD)
        font = gc.CreateFont(font, (0, 0, 255))
        gc.SetFont(font)

        pen = wx.Pen(wx.Colour(255, 0, 0, 128), 2, wx.SOLID)
        brush = wx.Brush(wx.Colour(0, 255, 0, 128))
        gc.SetPen(pen)
        gc.SetBrush(brush)
        gc.Scale(1, -1)

        self._ordered_draw_list = sorted(self._follow_draw_list(), key=lambda x: x[0])
        for l, d in self._ordered_draw_list: #sorted(self.draw_list, key=lambda x: x.layer if hasattr(x, 'layer') else 0):
            d.draw_to_canvas(gc, self)

        gc.Destroy()

        self.gc = None

        if self._drawn:
            self.bitmap = self.image.ConvertToBitmap()
            self.bitmap.CopyToBuffer(self._array, wx.BitmapBufferFormat_RGBA)

        self._cv_image.Modified()
        self.modified = False
        self._drawn = False
Example #36
0
    def GetRepresentation(self, x, y, z):
        pc = self.camera.GetPosition() # camera position
        pf = self.camera.GetFocalPoint() # focal position
        pp = (x, y, z) # point where the user clicked

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

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

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

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

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

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

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

        a = vtk.vtkActor2D()
        a.SetMapper(m)
        a.GetProperty().SetColor(self.colour)
        return a
Example #37
0
    def GetRepresentation(self, x, y, z):
        pc = self.camera.GetPosition()  # camera position
        pf = self.camera.GetFocalPoint()  # focal position
        pp = (x, y, z)  # point where the user clicked

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

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

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

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

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

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

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

        a = vtk.vtkActor2D()
        a.SetMapper(m)
        a.GetProperty().SetColor(self.colour)
        return a
Example #38
0
 def draw_to_canvas(self, gc, canvas):
     coord = vtk.vtkCoordinate()
     coord.SetCoordinateSystemToNormalizedDisplay()
     coord.SetValue(*self.position)
     x, y = coord.GetComputedDisplayValue(canvas.evt_renderer)
     font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
     font.SetSymbolicSize(self.symbolic_syze)
     font.Scale(canvas.viewer.GetContentScaleFactor())
     if self.bottom_pos or self.right_pos:
         w, h = canvas.calc_text_size(self.text, font)
         if self.right_pos:
             x -= w
         if self.bottom_pos:
             y += h
     canvas.draw_text(self.text, (x, y), font=font)
Example #39
0
def CreateAxisTickActor(xstart, ystart, xend, yend, colorfg):
    line = vtk.vtkLineSource()
    line.SetPoint1(xstart, ystart, 0.0)
    line.SetPoint2(xend, yend, 0.0)
    coords = vtk.vtkCoordinate()
    coords.SetCoordinateSystemToNormalizedViewport()
    linemapper = vtk.vtkPolyDataMapper2D()
    linemapper.SetInputConnection(line.GetOutputPort())
    linemapper.SetTransformCoordinate(coords)
    tick = vtk.vtkActor2D()
    tick.SetMapper(linemapper)
    tick.GetProperty().SetLineWidth(1)
    tick.GetProperty().SetColor(colorfg)
    tick.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
    return tick
Example #40
0
    def convert_world_to_display(self, viewpoint, x, y, z):
        """Converts world coordinates x, y, z to display coordinates.

        Used in 2D affine alignment model to get shape feature coordinates
        in image.
        """
        self.vtkrenderer.SetActiveCamera(self.vtkcamera)
        self._setup_camera(viewpoint)

        vtkcoordinate = vtk.vtkCoordinate()
        vtkcoordinate.SetCoordinateSystemToWorld()
        vtkcoordinate.SetValue(x, y, z)
        # x and y are flipped in render method.
        y, x = vtkcoordinate.GetComputedDisplayValue(self.vtkrenderer)
        return x, y
    def convert_world_to_display(self, viewpoint, x, y, z):
        """Converts world coordinates x, y, z to display coordinates.

        Used in 2D affine alignment model to get shape feature coordinates
        in image.
        """
        self.vtkrenderer.SetActiveCamera(self.vtkcamera)
        self._setup_camera(viewpoint)

        vtkcoordinate = vtk.vtkCoordinate()
        vtkcoordinate.SetCoordinateSystemToWorld()
        vtkcoordinate.SetValue(x, y, z)
        # x and y are flipped in render method.
        y, x = vtkcoordinate.GetComputedDisplayValue(self.vtkrenderer)
        return x, y
Example #42
0
def CreateAxisTickActor(xstart,ystart,xend,yend,colorfg) :
	line=vtk.vtkLineSource()
	line.SetPoint1(xstart,ystart,0.0)
	line.SetPoint2(xend,yend,0.0)
	coords = vtk.vtkCoordinate()
	coords.SetCoordinateSystemToNormalizedViewport()
	linemapper = vtk.vtkPolyDataMapper2D()
	linemapper.SetInputConnection(line.GetOutputPort())
	linemapper.SetTransformCoordinate(coords)
	tick = vtk.vtkActor2D()
	tick.SetMapper(linemapper)
	tick.GetProperty().SetLineWidth(1)
	tick.GetProperty().SetColor(colorfg)
	tick.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
	return tick 
Example #43
0
def set_options(vtkchart, vtkrenderer, opt):
    """
    A method for updating the legend options.
    """

    legend = vtkchart.GetLegend()

    if opt.isOptionValid('visible'):
        vtkchart.SetShowLegend(opt['visible'])
    else:
        vtkchart.SetShowLegend(True)

    if opt.isOptionValid('background'):
        legend.GetBrush().SetColorF(opt['background'])
    else:
        legend.GetBrush().SetColorF(vtkrenderer.GetBackground())

    legend.GetLabelProperties().SetColor(opt['label_color'])
    legend.GetBrush().SetOpacityF(opt['opacity'])

    if opt.isOptionValid('label_font_size'):
        legend.SetLabelSize(opt['label_font_size'])

    if opt.isOptionValid('point'):
        pt = opt['point']
        legend.SetVerticalAlignment(vtk.vtkChartLegend.CUSTOM)
        legend.SetHorizontalAlignment(vtk.vtkChartLegend.CUSTOM)

        coord = vtk.vtkCoordinate()
        coord.SetCoordinateSystemToNormalizedViewport()
        coord.SetValue(pt[0], pt[1], 0)
        loc = coord.GetComputedDisplayValue(vtkrenderer)
        legend.SetPoint(*loc)
    else:
        legend.SetVerticalAlignment(eval('vtk.vtkChartLegend.' +
                                         opt['vertical_alignment'].upper()))
        legend.SetHorizontalAlignment(eval('vtk.vtkChartLegend.' +
                                           opt['horizontal_alignment'].upper()))

    if opt.isOptionValid('border'):
        legend.GetPen().SetOpacity(opt['border_opacity'])
        legend.GetPen().SetColorF(opt['border_color'])
        if opt.isOptionValid('border_width'):
            legend.GetPen().SetWidth(opt['border_width'])
    else:
        legend.GetPen().SetOpacity(0)
Example #44
0
    def __init__( self, name, interactor, **args ):
        self.name = name
        self.interactor = interactor
        self.buttons = []
        self.updateWindowSize()
        self.visible = False
        self.position = args.get( 'position', ( 0.0, 1.0 ) )
        self.vtk_coord = vtk.vtkCoordinate()
        self.vtk_coord.SetCoordinateSystemToNormalizedDisplay()
        self.StateChangedSignal = SIGNAL('StateChanged')
        self.process_mode = ProcessMode.Default
        self.origin = args.get( 'origin', OriginPosition.Upper_Left )
        self.orientation = args.get( 'orientation', Orientation.Vertical )
#        print " ButtonBar[%s]: %s" % ( name, str(self.position) )
        self.buffer = args.get( 'buffer', ( 3, 3 ) )
        self.fullButtonWindowSize = 1300
        self.magnification = args.get( 'mag', 1.0 )
Example #45
0
 def startEvent(self):
     logging.debug("In TextWidget::startEvent()")
     if not self._started: 
         self._started = True
         self.setText(self.text)
         coord = vtk.vtkCoordinate()
         coord.SetCoordinateSystemToNormalizedDisplay()
         coord.SetValue(self.position[0], self.position[1])
         pos = coord.GetComputedDisplayValue(self.scene.renderer)
         x = self.position[0]/pos[0]
         y = self.position[1]/pos[1]
         pos = self.scene.interactor.GetEventPosition()
         self.position[0] = pos[0]*x
         self.position[1] = pos[1]*y
         
         self.rep.GetPositionCoordinate().SetValue(self.position[0], self.position[1])
         self.setText(self.text)
         self.On()
    def OnRenderEvent(self, renderer, evt):

        w = self._TextMapper.GetWidth(renderer)
        h = self._TextMapper.GetHeight(renderer)
        p = self._TextActor.GetPosition()

        if self._Text.strip() == "":
            self._RectanglePoints.InsertPoint(0, 0, 0, 0)
            self._RectanglePoints.InsertPoint(1, 0, 0, 0)
            self._RectanglePoints.InsertPoint(2, 0, 0, 0)
            self._RectanglePoints.InsertPoint(3, 0, 0, 0)
            return

        coord = vtk.vtkCoordinate()
        coord.SetCoordinateSystemToNormalizedViewport()
        coord.SetValue(p[0], p[1])
        p = coord.GetComputedViewportValue(renderer)
        x = p[0]
        y = p[1]

        if self._Position[1] == "E":
            x += 5
        else:
            x -= 5
        if self._Position[0] == "N":
            y += 5
        else:
            y -= 5

        # pad
        w += 10
        h += 10

        if self._Position == "SE":
            self._RectanglePoints.InsertPoint(0, x - w, y, 0)
            self._RectanglePoints.InsertPoint(1, x - w, y + h, 0)
            self._RectanglePoints.InsertPoint(2, x, y + h, 0)
            self._RectanglePoints.InsertPoint(3, x, y, 0)
        elif self._Position == "NW":
            self._RectanglePoints.InsertPoint(0, x, y, 0)
            self._RectanglePoints.InsertPoint(1, x, y - h, 0)
            self._RectanglePoints.InsertPoint(2, x + w, y - h, 0)
            self._RectanglePoints.InsertPoint(3, x + w, y, 0)
Example #47
0
    def __init__(self, font_size=14, color=(0.0, 0.0, 0.0), relative_position=(0, 1), absolute_offset=(10, -10), text="", **kwargs):
        kwargs["text"] = text
        kwargs['color'] = color
        kwargs["absolute_offset"] = absolute_offset
        kwargs["relative_position"] = relative_position
        kwargs["font_size"] = font_size

        self.actor = vtk.vtkTextActor()

        self.text_property = self.actor.GetTextProperty()
        self.text_property.SetFontFamilyToCourier()
        self.text_property.SetVerticalJustificationToTop()
        
        self.relpos_coord = vtk.vtkCoordinate()
        self.relpos_coord.SetCoordinateSystemToNormalizedViewport()
        self.actor.GetPositionCoordinate().SetCoordinateSystemToViewport()
        self.actor.GetPositionCoordinate().SetReferenceCoordinate(self.relpos_coord)

        self._process_kwargs(**kwargs)
Example #48
0
def HandleVisibilityLonAxisTextAndTicks(renwin,ren0,ren1,text,tickb,ticku,xpos) :
	xsize,ysize=renwin.GetSize()
	ren1xstart,ren1ystart,ren1xend,ren1yend=ren1.GetViewport()
	coords = vtk.vtkCoordinate()
	coords.SetCoordinateSystemToWorld()
	coords.SetValue(xpos,0.0,0.0)
	x1,y1 = coords.GetComputedDoubleViewportValue(ren1)
	renxpos=x1/xsize+ren1xstart
	if renxpos > ren1xstart and renxpos < ren1xend : 
		ren0.AddActor(text)
		text.SetPosition(renxpos,ren1ystart-axisxoffset)
		ren0.AddActor(tickb)
		tickb.SetPosition(renxpos,ren1ystart-axisxticksize)
		ren0.AddActor(ticku)
		ticku.SetPosition(renxpos,ren1yend)
		visibility=1
	else :
		ren0.RemoveActor(text)
		ren0.RemoveActor(tickb)
		ren0.RemoveActor(ticku)
		visibility=0
	return visibility
Example #49
0
def HandleVisibilityLatAxisTextAndTicks(renwin,ren0,ren1,text,tickl,tickr,ypos) :
	xsize,ysize=renwin.GetSize()
	ren1xstart,ren1ystart,ren1xend,ren1yend=ren1.GetViewport()
	coords = vtk.vtkCoordinate()
	coords.SetCoordinateSystemToWorld()
	coords.SetValue(0.0,ypos,0.0)
	x1,y1 = coords.GetComputedDoubleViewportValue(ren1)
	renypos=y1/ysize+ren1ystart
	if renypos > ren1ystart and renypos < ren1yend : 
		ren0.AddActor(text)
		text.SetPosition(ren1xstart-axisyoffset,renypos)
		ren0.AddActor(tickl)
		tickl.SetPosition(ren1xstart-axisyticksize,renypos)
		ren0.AddActor(tickr)
		tickr.SetPosition(ren1xend,renypos)
		visibility=1
	else :
		ren0.RemoveActor(text)
		ren0.RemoveActor(tickl)
		ren0.RemoveActor(tickr)
		visibility=0
	return visibility
Example #50
0
    def GetImagedataCoordinates(self, picker_position):
        x, y, z = picker_position

        c = vtk.vtkCoordinate()
        c.SetCoordinateSystemToWorld()
        c.SetValue(bounds[::2])
        xi, yi = c.GetComputedViewportValue(self.render)

        c.SetValue(bounds[1::2])
        xf, yf = c.GetComputedViewportValue(self.render)
        
        c.SetValue(x, y, z)
        wx, wy = c.GetComputedViewportValue(self.render)
        
        wx = wx - xi
        wy = wy - yi
        
        xf = xf - xi
        yf = yf - yi

        wx = (wx * self.imagedata_dimensions[0]) / xf
        wy = (wy * self.imagedata_dimensions[1]) / yf
        
        return wx, wy
Example #51
0
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.SetInput(Grid)
mapper.SetTransformCoordinate(normCoords)
gridActor = vtk.vtkActor2D()
gridActor.SetMapper(mapper)
gridActor.GetProperty().SetColor(0.1, 0.1, 0.1)

# Create the Renderer, RenderWindow, and RenderWindowInteractor
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
Example #52
0
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetSize(600, 600)


iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
style = vtk.vtkInteractorStyleTrackballCamera()
iren.SetInteractorStyle(style)

camera = vtk.vtkCamera()
camera.SetPosition(0, 0, -30)
camera.SetFocalPoint(0, 0, 10)
ren.SetActiveCamera(camera)

coordinate = vtk.vtkCoordinate()
coordinate.SetCoordinateSystemToWorld()
coordinate.SetValue(5, 0, 0)
print coordinate.GetComputedDisplayValue(ren)




source = vtk.vtkSphereSource()
source.SetCenter(0, 0, 0)
source.SetRadius(5.0)

mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(source.GetOutput())

actor = vtk.vtkActor()
Example #53
0
def setup_renderers(renwin, fg_ren, bg_ren):
    """Utility method to configure foreground and background renderer
    and insert them into different layers of the renderenwinindow.

    Use this if you want an incredibly cool gradient background!
    """
    
    # bit of code thanks to 
    # http://www.bioengineering-research.com/vtk/BackgroundGradient.tcl
    # had to change approach though to using background renderer,
    # else transparent objects don't appear, and adding flat
    # shaded objects breaks the background gradient.
    # =================================================================
    
    qpts = vtk.vtkPoints()
    qpts.SetNumberOfPoints(4)
    qpts.InsertPoint(0, 0, 0, 0)
    qpts.InsertPoint(1, 1, 0, 0)
    qpts.InsertPoint(2, 1, 1, 0)
    qpts.InsertPoint(3, 0, 1, 0)

    quad = vtk.vtkQuad()
    quad.GetPointIds().SetId(0,0)
    quad.GetPointIds().SetId(1,1)
    quad.GetPointIds().SetId(2,2)
    quad.GetPointIds().SetId(3,3)

    uc = vtk.vtkUnsignedCharArray()
    uc.SetNumberOfComponents(4)
    uc.SetNumberOfTuples(4)
    uc.SetTuple4(0, 128, 128, 128, 255) # bottom left RGBA
    uc.SetTuple4(1, 128, 128, 128, 255) # bottom right RGBA
    uc.SetTuple4(2, 255, 255, 255, 255) # top right RGBA
    uc.SetTuple4(3, 255, 255, 255, 255) # tob left RGBA

    dta = vtk.vtkPolyData()
    dta.Allocate(1,1)
    dta.InsertNextCell(quad.GetCellType(), quad.GetPointIds())
    dta.SetPoints(qpts)
    dta.GetPointData().SetScalars(uc)

    coord = vtk.vtkCoordinate()
    coord.SetCoordinateSystemToNormalizedDisplay()

    mapper2d = vtk.vtkPolyDataMapper2D()
    mapper2d.SetInput(dta)
    mapper2d.SetTransformCoordinate(coord)

    actor2d = vtk.vtkActor2D()
    actor2d.SetMapper(mapper2d)
    actor2d.GetProperty().SetDisplayLocationToBackground()

    bg_ren.AddActor(actor2d)
    bg_ren.SetLayer(0) # seems to be background
    bg_ren.SetInteractive(0)

    fg_ren.SetLayer(1) # and foreground

    renwin.SetNumberOfLayers(2)
    renwin.AddRenderer(fg_ren)
    renwin.AddRenderer(bg_ren)
  def drawROI(self, interactor, startXY, endXY):
    coord = vtk.vtkCoordinate()
    coord.SetCoordinateSystemToDisplay()

    coord.SetValue(startXY[0], startXY[1], 0.0)
    worldStartXY = coord.GetComputedWorldValue(interactor.GetRenderWindow().GetRenderers().GetFirstRenderer())

    coord.SetValue(endXY[0], endXY[1], 0.0)
    worldEndXY = coord.GetComputedWorldValue(interactor.GetRenderWindow().GetRenderers().GetFirstRenderer())

    pts = vtk.vtkPoints()
    pts.InsertNextPoint(worldStartXY)

    vectors = vtk.vtkDoubleArray()
    vectors.SetNumberOfComponents(3)
    vectors.SetNumberOfTuples(1)
    vectors.SetTuple3(0, worldEndXY[0]-worldStartXY[0], worldEndXY[1]-worldStartXY[1], worldEndXY[2]-worldStartXY[2]) 

    r = 0
    for d in range(3):
      r += (worldEndXY[d] - worldStartXY[d]) ** 2.0
    r = math.sqrt(r)

    radii = vtk.vtkFloatArray()
    radii.InsertNextValue(r)
    radii.SetName("radius")

    pd = vtk.vtkPolyData()
    pd.SetPoints(pts)
    #pd.GetPointData().SetVectors(vectors)
    #pd.GetPointData().AddArray(radii)
    #pd.GetPointData().SetActiveScalars("radius")
    pd.GetPointData().SetScalars(radii)

    #lineSource = vtk.vtkArrowSource()

    """
    lineSource = vtk.vtkGlyphSource2D()
    lineSource.SetGlyphTypeToCircle()
    #lineSource.SetGlyphTypeToArrow()
    lineSource.FilledOff()
    lineSource.Update()
    """

    lineSource = vtk.vtkSphereSource()
    lineSource.SetRadius(1.0)
    lineSource.SetPhiResolution(12)
    lineSource.SetThetaResolution(12)

    self.roiGlyph.SetInput(pd)
    self.roiGlyph.SetSource(lineSource.GetOutput())
    self.roiGlyph.ScalingOn()
    self.roiGlyph.OrientOn()
    self.roiGlyph.SetScaleFactor(1.0)
    #self.roiGlyph.SetVectorModeToUseVector()
    #self.roiGlyph.SetScaleModeToScaleByVector()
    self.roiGlyph.SetScaleModeToScaleByScalar()
    self.roiGlyph.Update()
     
    self.roiMapper.SetInput(self.roiGlyph.GetOutput())

    self.roiActor.SetMapper(self.roiMapper)

    renOverlay = self.getOverlayRenderer( interactor.GetRenderWindow() )
    renOverlay.AddActor(self.roiActor)
Example #55
0
    def update(self, **kwargs):
        """
        Updates the 3D camera to place the image in the defined location.
        """
        super(ImageAnnotation, self).update(**kwargs)

        renderer = self.getVTKRenderer()

        # Coordinate transormation object
        tr = vtk.vtkCoordinate()
        tr.SetCoordinateSystemToNormalizedViewport()

        # Size of window
        window = renderer.GetRenderWindow().GetSize()

        # Size of image
        size = self._sources[-1].getVTKSource().GetOutput().GetDimensions()

        # Image scale
        if self.isOptionValid('scale'):
            scale = self.getOption('scale')
        else:
            scale = float(window[0])/float(size[0]) * self.getOption('width')

        # Compute the camera distance
        angle = self._vtkcamera.GetViewAngle()
        d = window[1]*0.5 / math.tan(math.radians(angle*0.5))

        # Determine the image position
        if self.isOptionValid('position'):
            p = self.getOption('position')
            tr.SetValue(p[0], p[1], 0)
            position = list(tr.GetComputedDisplayValue(renderer))

        # Adjust for off-center alignments
        if self.getOption('horizontal_alignment') == 'left':
            position[0] = position[0] + (size[0]*0.5*scale)
        elif self.getOption('horizontal_alignment') == 'right':
            position[0] = position[0] - (size[0]*0.5*scale)

        if self.getOption('vertical_alignment') == 'top':
            position[1] = position[1] - (size[1]*0.5*scale)
        elif self.getOption('vertical_alignment') == 'bottom':
            position[1] = position[1] + (size[1]*0.5*scale)

        # Reference position (middle of window)
        tr.SetValue(0.5, 0.5, 0)
        ref = tr.GetComputedDisplayValue(renderer)

        # Camera offsets
        x = (ref[0] - position[0]) * 1/scale
        y = (ref[1] - position[1]) * 1/scale

        # Set the camera
        self._vtkcamera.SetViewUp(0, 1, 0)
        self._vtkcamera.SetPosition(size[0]/2. + x, size[1]/2. + y, d * 1/scale)
        self._vtkcamera.SetFocalPoint(size[0]/2. + x, size[1]/2. + y, 0)

        # Update the renderer
        renderer.SetActiveCamera(self._vtkcamera)
        renderer.ResetCameraClippingRange()
 def _3d_to_2d(self, renderer, pos):
     coord = vtk.vtkCoordinate()
     coord.SetValue(pos)
     px, py = coord.GetComputedDoubleDisplayValue(renderer)
     return px, py
Example #57
0
    def update(self, **kwargs):
        """
        Apply setting to create a colorbar.

        Inputs:
            see ChiggerResult
        """

        # Set the options provided
        self.setOptions(**kwargs)
        if self.needsInitialize():
            self.initialize()

        # Convenience names for the various sources
        plane, axis0, axis1 = self._sources

        # Origin
        loc = self.getOption('location').lower()
        if not self.isOptionValid('colorbar_origin'):
            if (loc == 'right') or (loc == 'left'):
                self.setOption('colorbar_origin', [0.8, 0.25, 0.0])
            else:
                self.setOption('colorbar_origin', [0.25, 0.2, 0.0])

        # Get dimensions of colorbar, taking into account the orientation
        n = self.getOption('cmap_num_colors')
        length0 = 0
        length1 = 0
        loc = self.getOption('location')
        if (loc == 'right') or (loc == 'left'):
            length0 = self.getOption('width')
            length1 = self.getOption('length')
            plane.setOptions(resolution=[1, n+1])
        else:
            length0 = self.getOption('length')
            length1 = self.getOption('width')
            plane.setOptions(resolution=[n+1, 1])

        # Coordinate system transformation object
        pos = self.getOption('colorbar_origin')
        coord = vtk.vtkCoordinate()
        coord.SetCoordinateSystemToNormalizedViewport()

        # The viewport must be set, before the points are computed.
        if self.isOptionValid('viewport'):
            self._vtkrenderer.SetViewport(self.getOption('viewport'))

        # Point 0
        coord.SetViewport(self._vtkrenderer)
        coord.SetValue(pos[0]+length0, pos[1], 0)
        p0 = coord.GetComputedViewportValue(self._vtkrenderer)

        # Point 1
        coord.SetValue(pos[0], pos[1]+length1, 0)
        p1 = coord.GetComputedViewportValue(self._vtkrenderer)

        coord.SetValue(*pos)
        pos = coord.GetComputedViewportValue(self._vtkrenderer)

        # Update the bar position
        plane.setOptions(origin=[pos[0], pos[1], 0],
                         point1=[p0[0], p0[1], 0],
                         point2=[p1[0], p1[1], 0])

        # Set the colormap for the bar
        rng = self.getOption('cmap_range')
        step = (rng[1] - rng[0]) / float(n)

        data = vtk.vtkFloatArray()
        data.SetNumberOfTuples(n+1)
        for i in xrange(n+1):
            data.SetValue(i, rng[0] + i*step)
        plane.setOptions(data=data)

        # Setup the primary Axis
        axis0.options().update(self.getOption('primary'))
        location = self.__setAxisPosition(axis0, p0, p1, self.getOption('location'))

        # Setup the secondary Axis
        axis1.options().update(self.getOption('secondary'))
        self.__setAxisPosition(axis1, p0, p1, location)

        # Call base class method
        super(ColorBar, self).update()