Example #1
0
    def __init__(self):
        super(ImageSliceVisualizer, self).__init__()

        # Setup pipeline
        self.image_mapper = vtk.vtkImageSliceMapper()
        self.image_mapper.SliceAtFocalPointOn()
        self.image_mapper.SliceFacesCameraOn()

        self.image_property = vtk.vtkImageProperty()
        self.image_property.SetInterpolationTypeToNearest()

        self.image_slice = vtk.vtkImageSlice()
        self.image_slice.SetMapper(self.image_mapper)
        self.image_slice.SetProperty(self.image_property)

        self.renderer = vtk.vtkRenderer()
        self.renderer.AddActor2D(self.image_slice)

        self.interactor = vtk.vtkRenderWindowInteractor()
        self.interactor_style = vtk.vtkInteractorStyleImage()
        self.interactor_style.SetInteractionModeToImageSlicing()
        self.interactor_style.KeyPressActivationOn()
        self.interactor.SetInteractorStyle(self.interactor_style)

        # Add ability to switch between active layers
        self.interactor.AddObserver('KeyPressEvent',
                                    self._interactor_call_back, -1.0)
Example #2
0
    def __init__(self):
        """Init."""
        # Interactor responsible for moving the camera.
        self.trackball_camera = vtk.vtkInteractorStyleTrackballCamera()
        # Interactor responsible for moving/rotating a selected actor.
        self.trackball_actor = vtk.vtkInteractorStyleTrackballActor()
        # Interactor responsible for panning/zooming the camera.
        self.image = vtk.vtkInteractorStyleImage()

        # The picker allows us to know which object/actor is under the mouse.
        self.picker = vtk.vtkPropPicker()
        self.chosen_element = None
        self.event = Event()
        self.event2id = {}  # To map an event's name to an ID.

        # Define some interaction states
        self.left_button_down = False
        self.right_button_down = False
        self.middle_button_down = False
        self.active_props = set()

        self.history = deque(maxlen=10)  # Events history.

        self.selected_props = {"left_button": set(),
                               "right_button": set(),
                               "middle_button": set()}
def show_image(image, actors=[]):
    viewer = vtk.vtkImageViewer2()
    viewer.SetInputData(image)

    istyle = vtk.vtkInteractorStyleImage()
    iren = vtk.vtkRenderWindowInteractor()
    viewer.SetupInteractor(iren)
    iren.SetInteractorStyle(istyle)

    min_slice = viewer.GetSliceMin()
    max_slice = viewer.GetSliceMax()

    actions = {'slice': min_slice}

    def mouse_wheel_forward_event(caller, event):
        if actions['slice'] > min_slice:
            actions['slice'] -= 1
            viewer.SetSlice(actions['slice'])
            viewer.Render()

    def mouse_wheel_backward_event(caller, event):
        if actions['slice'] < max_slice:
            actions['slice'] += 1
            viewer.SetSlice(actions['slice'])
            viewer.Render()

    istyle.AddObserver('MouseWheelForwardEvent', mouse_wheel_forward_event)
    istyle.AddObserver('MouseWheelBackwardEvent', mouse_wheel_backward_event)

    for actor in actors:
        viewer.GetRenderer().AddActor(actor)

    viewer.Render()
    iren.Initialize()
    iren.Start()
Example #4
0
def main():
    filename = get_program_parameters()

    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(filename)
    reader.Update()

    # Visualize
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(reader.GetOutputPort())

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.ResetCamera()

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

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    style = vtk.vtkInteractorStyleImage()

    render_window_interactor.SetInteractorStyle(style)

    render_window_interactor.SetRenderWindow(render_window)
    render_window.Render()
    render_window_interactor.Initialize()

    render_window_interactor.Start()
Example #5
0
    def Start(self):
        istyle = vtk.vtkInteractorStyleImage()
        istyle.AddObserver("LeftButtonPressEvent", self.SelectRegion)
        iren = Globals.renWin.GetInteractor()
        iren.SetInteractorStyle(istyle)

        self.UpdateObservers()
Example #6
0
    def _createViewFrames(self):
        import modules.Insight.resources.python.register2DViewFrames
        reload(modules.Insight.resources.python.register2DViewFrames)

        viewerFrame = modules.Insight.resources.python.register2DViewFrames.\
                      viewerFrame
        self.viewerFrame = module_utils.instantiate_module_view_frame(
            self, self._module_manager, viewerFrame)

        self._threedRenderer = vtk.vtkRenderer()
        self._threedRenderer.SetBackground(0.5, 0.5, 0.5)
        self.viewerFrame.threedRWI.GetRenderWindow().AddRenderer(
            self._threedRenderer)

        istyle = vtk.vtkInteractorStyleImage()
        self.viewerFrame.threedRWI.SetInteractorStyle(istyle)

        # controlFrame creation
        controlFrame = modules.Insight.resources.python.\
                       register2DViewFrames.controlFrame
        self.controlFrame = module_utils.instantiate_module_view_frame(
            self, self._module_manager, controlFrame)

        # display
        self.viewerFrame.Show(True)
        self.controlFrame.Show(True)
Example #7
0
    def __init__(self):

        QMainWindow.__init__(self)

        self.setupUi(self)
        self.setWindowTitle("Medical Image Viewer")

        #Mainframe Variables

        self.map = None
        self.reader = None
        self.cam = None
        self.center_cam = None
        self.size = None

        self.spinBox.setEnabled(False)
        self.res_Slider.setMaximum(200)

        self.actionOpen_File.triggered.connect(self.open_File)
        self.res_Slider.valueChanged.connect(self.valuechange)
        self.ax_Button.clicked.connect(self.changeView)
        self.cor_Button.clicked.connect(self.changeView)
        self.sag_Button.clicked.connect(self.changeView)

        #VTK Viewer

        self.vtk_Viewer = QVTKRenderWindowInteractor(self.vtk_Frame)
        self.vtk_Viewer.SetSize(800, 800)
        self.ren = vtk.vtkRenderer()
        self.vtk_Viewer.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtk_Viewer.GetRenderWindow().GetInteractor()
        style = vtk.vtkInteractorStyleImage()
        style.SetInteractionModeToImageSlicing()
        self.iren.SetInteractorStyle(style)
Example #8
0
    def Start(self):
        istyle = vtk.vtkInteractorStyleImage()
        istyle.AddObserver("LeftButtonPressEvent",self.SelectRegion)
        iren = Globals.renWin.GetInteractor()
        iren.SetInteractorStyle(istyle)

        self.UpdateObservers()
Example #9
0
    def _createViewFrames(self):
        import modules.Insight.resources.python.register2DViewFrames
        reload(modules.Insight.resources.python.register2DViewFrames)

        viewerFrame = modules.Insight.resources.python.register2DViewFrames.\
                      viewerFrame
        self.viewerFrame = module_utils.instantiate_module_view_frame(
            self, self._module_manager, viewerFrame)

        self._threedRenderer = vtk.vtkRenderer()
        self._threedRenderer.SetBackground(0.5, 0.5, 0.5)
        self.viewerFrame.threedRWI.GetRenderWindow().AddRenderer(
            self._threedRenderer)

        istyle = vtk.vtkInteractorStyleImage()
        self.viewerFrame.threedRWI.SetInteractorStyle(istyle)
        

        

        # controlFrame creation
        controlFrame = modules.Insight.resources.python.\
                       register2DViewFrames.controlFrame
        self.controlFrame = module_utils.instantiate_module_view_frame(
            self, self._module_manager, controlFrame)

        # display
        self.viewerFrame.Show(True)
        self.controlFrame.Show(True)
Example #10
0
def main():
    rwi = vtk.vtkRenderWindowInteractor()

    istyle = vtk.vtkInteractorStyleImage()
    rwi.SetInteractorStyle(istyle)

    rw = vtk.vtkRenderWindow()
    rwi.SetRenderWindow(rw)

    ren = vtk.vtkRenderer()
    ren.SetBackground(1, 1, 1)
    ren.GetActiveCamera().SetParallelProjection(1)
    rw.AddRenderer(ren)

    rwi.Initialize()

    # with the string "what gh", this will generate the following
    # error at render:

    # RuntimeError: ERROR: In ..\..\..\archive\VTK\Filtering\
    # vtkStreamingDemandDrivenPipeline.cxx, line 698
    # vtkStreamingDemandDrivenPipeline (017CF3C8): The update
    # extent specified in the information for output port 0 on
    # algorithm vtkTrivialProducer(017D2FF0) is 0 255
    # 0 63 0 0, which is outside the whole extent 0 255 0 31 0 0.

    # with the string "what h" (i.e. without the g and its downward
    # stroke, there's no error)
    ta2 = make_glyph(ren, (0, 0), 'What h')

    ren.ResetCamera()
    rw.Render()

    rwi.Start()
Example #11
0
    def __set_up_renderer(self, volume, mask_volume):
        self.img_ren = vtk.vtkRenderer()
        self.img_ren.AddActor(self.actor)
        self.img_ren.AddActor(self.mask_actor)
        self.img_ren.ResetCamera()
        self.img_ren.SetViewport([0.0, 0.0, 1.0, 0.5
                                  ])  # slicer renderer position - bottom half

        self.vol_ren = vtk.vtkRenderer()
        self.vol_ren.AddVolume(volume)
        self.vol_ren.AddVolume(mask_volume)
        self.vol_ren.ResetCamera()
        self.vol_ren.SetViewport(0.0, 0.5, 1.0,
                                 1.0)  # volume renderer position
        self.vol_ren.SetBackground(0.0, 0.01, 0.05)

        self.win = vtk.vtkRenderWindow()
        self.win.SetSize(400, 800)
        self.win.AddRenderer(self.img_ren)
        self.win.AddRenderer(self.vol_ren)

        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.win)

        # set styles for interactor
        self.image_style = vtk.vtkInteractorStyleImage()
        self.image_style.AddObserver("RightButtonReleaseEvent",
                                     self.switch_axis_call_back)
        self.image_style.SetDefaultRenderer(self.img_ren)

        self.volume_style = vtk.vtkInteractorStyleSwitch()
        self.volume_style.SetDefaultRenderer(self.vol_ren)

        self.iren.AddObserver("MouseMoveEvent", self.switch_interactor_style)
def main():
    rwi = vtk.vtkRenderWindowInteractor()

    istyle = vtk.vtkInteractorStyleImage()
    rwi.SetInteractorStyle(istyle)

    rw = vtk.vtkRenderWindow()
    rwi.SetRenderWindow(rw)

    ren = vtk.vtkRenderer()
    ren.SetBackground(1, 1, 1)
    ren.GetActiveCamera().SetParallelProjection(1)
    rw.AddRenderer(ren)

    rwi.Initialize()

    # with the string "what gh", this will generate the following
    # error at render:

    # RuntimeError: ERROR: In ..\..\..\archive\VTK\Filtering\
    # vtkStreamingDemandDrivenPipeline.cxx, line 698
    # vtkStreamingDemandDrivenPipeline (017CF3C8): The update
    # extent specified in the information for output port 0 on
    # algorithm vtkTrivialProducer(017D2FF0) is 0 255
    # 0 63 0 0, which is outside the whole extent 0 255 0 31 0 0.

    # with the string "what h" (i.e. without the g and its downward
    # stroke, there's no error)
    ta2 = make_glyph(ren, (0, 0), "What h")

    ren.ResetCamera()
    rw.Render()

    rwi.Start()
Example #13
0
def main(args):

    reader = vtk.vtkNrrdReader()
    reader.SetFileName(args.img)
    reader.Update()
    img = reader.GetOutput()

    print(img)

    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputData(img)

    # Setup rendering
    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.SetBackground(1, 1, 1)
    renderer.ResetCamera()

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

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetInteractorStyle(vtk.vtkInteractorStyleImage())
    renderWindowInteractor.AddObserver("KeyPressEvent", Keypress)
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderWindowInteractor.Initialize()
    renderWindowInteractor.Start()
	def SetInteractorStyleToImage(self):
		self.interactor = self.renWin.GetInteractor()
		self.istyle = vtk.vtkInteractorStyleImage()
		self.renWin.GetInteractor().SetInteractorStyle(self.istyle)
		self.renderer.GetActiveCamera().ParallelProjectionOn()
		# self.istyle.AddObserver("MouseMoveEvent", self.MouseMoveCallback)
		self.istyle.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
		self.istyle.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback)
    def __init_vtk(self):
        text_image_size = vtku.TextZero()
        text_image_size.SetPosition(const.TEXT_POS_LEFT_UP)
        text_image_size.SetValue("")
        text_image_size.SetSymbolicSize(wx.FONTSIZE_SMALL)
        self.text_image_size = text_image_size

        text_image_location = vtku.TextZero()
        #  text_image_location.SetVerticalJustificationToBottom()
        text_image_location.SetPosition(const.TEXT_POS_LEFT_DOWN)
        text_image_location.SetValue("")
        text_image_location.bottom_pos = True
        text_image_location.SetSymbolicSize(wx.FONTSIZE_SMALL)
        self.text_image_location = text_image_location

        text_patient = vtku.TextZero()
        #  text_patient.SetJustificationToRight()
        text_patient.SetPosition(const.TEXT_POS_RIGHT_UP)
        text_patient.SetValue("")
        text_patient.right_pos = True
        text_patient.SetSymbolicSize(wx.FONTSIZE_SMALL)
        self.text_patient = text_patient

        text_acquisition = vtku.TextZero()
        #  text_acquisition.SetJustificationToRight()
        #  text_acquisition.SetVerticalJustificationToBottom()
        text_acquisition.SetPosition(const.TEXT_POS_RIGHT_DOWN)
        text_acquisition.SetValue("")
        text_acquisition.right_pos = True
        text_acquisition.bottom_pos = True
        text_acquisition.SetSymbolicSize(wx.FONTSIZE_SMALL)
        self.text_acquisition = text_acquisition

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetLayer(0)

        cam = self.renderer.GetActiveCamera()

        self.canvas_renderer = vtk.vtkRenderer()
        self.canvas_renderer.SetLayer(1)
        self.canvas_renderer.SetActiveCamera(cam)
        self.canvas_renderer.SetInteractive(0)
        self.canvas_renderer.PreserveDepthBufferOn()

        style = vtk.vtkInteractorStyleImage()

        self.interactor.GetRenderWindow().SetNumberOfLayers(2)
        self.interactor.GetRenderWindow().AddRenderer(self.renderer)
        self.interactor.GetRenderWindow().AddRenderer(self.canvas_renderer)
        self.interactor.SetInteractorStyle(style)
        self.interactor.Render()

        self.canvas = CanvasRendererCTX(self, self.renderer,
                                        self.canvas_renderer)
        self.canvas.draw_list.append(self.text_image_size)
        self.canvas.draw_list.append(self.text_image_location)
        self.canvas.draw_list.append(self.text_patient)
        self.canvas.draw_list.append(self.text_acquisition)
Example #16
0
    def Start(self):
        self.caller.imageObservers.append(self.UpdateObservers)
        istyle = vtk.vtkInteractorStyleImage()
        istyle.AddObserver("LeftButtonPressEvent", self.ClickRegion)
        iren = Globals.renWin.GetInteractor()
        iren.SetInteractorStyle(istyle)

        self.dic = {}
        self.BuildCellLocator()
Example #17
0
 def Start(self):
     self.caller.imageObservers.append(self.UpdateObservers)
     istyle = vtk.vtkInteractorStyleImage()
     istyle.AddObserver("LeftButtonPressEvent",self.ClickRegion)
     iren = Globals.renWin.GetInteractor()
     iren.SetInteractorStyle(istyle)
     
     self.dic = {}
     self.BuildCellLocator()
Example #18
0
    def Start(self):
        self.caller.imageObservers.append(self.UpdateObserver)
        self.ResetSpline()

        istyle = vtk.vtkInteractorStyleImage()
        istyle.AddObserver("LeftButtonReleaseEvent", self.AddPoint)
        istyle.AddObserver("RightButtonPressEvent", self.AddSpline)
        iren = Globals.renWin.GetInteractor()
        iren.SetInteractorStyle(istyle)
Example #19
0
def Slicer2d(volume, size=(900, 900), bg=(0.6, 0.6, 0.7), zoom=1.3):
    """Create a 2D window with a single balck a nd white
    slice of a Volume, wich can be oriented arbitrarily in space.
    """
    img = volume.imagedata()

    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    im = vtk.vtkImageResliceMapper()
    im.SetInputData(img)
    im.SliceFacesCameraOn()
    im.SliceAtFocalPointOn()
    im.BorderOn()

    ip = vtk.vtkImageProperty()
    ip.SetInterpolationTypeToLinear()

    ia = vtk.vtkImageSlice()
    ia.SetMapper(im)
    ia.SetProperty(ip)

    ren1.AddViewProp(ia)
    ren1.SetBackground(bg)
    renWin.SetSize(size)

    iren = vtk.vtkRenderWindowInteractor()
    style = vtk.vtkInteractorStyleImage()
    style.SetInteractionModeToImage3D()
    iren.SetInteractorStyle(style)
    renWin.SetInteractor(iren)

    renWin.Render()
    cam1 = ren1.GetActiveCamera()
    cam1.ParallelProjectionOn()
    ren1.ResetCameraClippingRange()
    cam1.Zoom(zoom)
    renWin.Render()

    printc("Slicer2D tool", invert=1, c="m")
    printc(
        """Press  SHIFT+Left mouse    to rotate the camera for oblique slicing
       SHIFT+Middle mouse  to slice perpendicularly through the image
       Left mouse and Drag to modify luminosity and contrast
       X                   to Reset to sagittal view
       Y                   to Reset to coronal view
       Z                   to Reset to axial view
       R                   to Reset the Window/Levels
       Q                   to Quit.""",
        c="m",
    )

    iren.Start()
    return iren
Example #20
0
def showImage(inputFileName):
    imgData = None
    dataType = None

    renderer = vtk.vtkRenderer()

    if type(inputFileName) == str:
        fileName, fileExtension = os.path.splitext(inputFileName)
        fileExtension = fileExtension.lower()
        if fileExtension in ['.mha', '.mhd']:
            reader = vtk.vtkMetaImageReader()
            reader.SetFileName(inputFileName)
            reader.Update()
        elif fileExtension in ['.png']:
            reader = vtk.vtkPNGReader()
            reader.SetFileName(inputFileName)
            reader.Update()
        else:
            raise Exception("Unknown extension - update this program")
        imgData = reader.GetOutput()
        dataType = vtk.vtkImageData
    elif type(inputFileName) == vtk.vtkImageData:
        imgData = inputFileName
        dataType = vtk.vtkImageData
    elif type(inputFileName) == vtk.vtkPolyData:
        imgData = inputFileName
        dataType = vtk.vtkPolyData

    if dataType == vtk.vtkImageData:
        low, high = imgData.GetPointData().GetScalars().GetRange()
        print("low: %f, high: %f" % (low, high))
        print(imgData.GetDimensions())
        image = vtk.vtkImageActor()
        image.GetMapper().SetInputData(imgData)

        image.GetProperty().SetColorWindow(high - low)
        image.GetProperty().SetColorLevel(0.5 * (low + high))
        renderer.AddActor(image)
        style = vtk.vtkInteractorStyleImage()
    else:
        style = vtk.vtkInteractorStyleSwitch()
        surfActor = vtk.vtkActor()
        surfMapper = vtk.vtkPolyDataMapper()
        surfMapper.SetInputData(imgData)
        surfActor.SetMapper(surfMapper)
        renderer.AddActor(surfActor)

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

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

    interactor.SetInteractorStyle(style)

    #print(image.GetMapper().GetInput())
    interactor.Start()
    def __init_vtk(self):
        actor = vtk.vtkImageActor()
        self.actor = actor

        text_image_size = vtku.Text()
        text_image_size.SetPosition(const.TEXT_POS_LEFT_UP)
        text_image_size.SetValue("")
        text_image_size.SetSize(const.TEXT_SIZE_SMALL)
        self.text_image_size = text_image_size

        text_image_location = vtku.Text()
        text_image_location.SetVerticalJustificationToBottom()
        text_image_location.SetPosition(const.TEXT_POS_LEFT_DOWN)
        text_image_location.SetValue("")
        text_image_location.SetSize(const.TEXT_SIZE_SMALL)
        self.text_image_location = text_image_location

        text_patient = vtku.Text()
        text_patient.SetJustificationToRight()
        text_patient.SetPosition(const.TEXT_POS_RIGHT_UP)
        text_patient.SetValue("")
        text_patient.SetSize(const.TEXT_SIZE_SMALL)
        self.text_patient = text_patient

        text_acquisition = vtku.Text()
        text_acquisition.SetJustificationToRight()
        text_acquisition.SetVerticalJustificationToBottom()
        text_acquisition.SetPosition(const.TEXT_POS_RIGHT_DOWN)
        text_acquisition.SetValue("")
        text_acquisition.SetSize(const.TEXT_SIZE_SMALL)
        self.text_acquisition = text_acquisition

        renderer = vtk.vtkRenderer()
        renderer.AddActor(actor)
        renderer.AddActor(text_image_size.actor)
        renderer.AddActor(text_image_location.actor)
        renderer.AddActor(text_patient.actor)
        renderer.AddActor(text_acquisition.actor)
        self.renderer = renderer

        style = vtk.vtkInteractorStyleImage()

        interactor = wxVTKRenderWindowInteractor(self.panel,
                                                 -1,
                                                 size=wx.Size(340, 340))
        interactor.GetRenderWindow().AddRenderer(renderer)
        interactor.SetInteractorStyle(style)
        interactor.Render()
        self.interactor = interactor

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(interactor, 1, wx.GROW | wx.EXPAND)
        sizer.Fit(self.panel)
        self.panel.SetSizer(sizer)
        self.Layout()
        self.Update()
Example #22
0
    def Start(self):
        istyle = vtk.vtkInteractorStyleImage()
        istyle.AddObserver("LeftButtonPressEvent", self.Left)
        istyle.AddObserver("RightButtonPressEvent", self.Right)
        iren = Globals.renWin.GetInteractor()
        iren.SetInteractorStyle(istyle)

        self.spline = Spline.PlaneSpline()
        self.renSpline = Spline.RenderSpline(1)
        self.splineExists = 0
Example #23
0
    def Start(self):
        istyle = vtk.vtkInteractorStyleImage()
        istyle.AddObserver("LeftButtonPressEvent",self.Left)
        istyle.AddObserver("RightButtonPressEvent", self.Right)
        iren = Globals.renWin.GetInteractor()
        iren.SetInteractorStyle(istyle)

        self.spline = Spline.PlaneSpline()
        self.renSpline = Spline.RenderSpline(1)
        self.splineExists = 0
    def __init_vtk(self):
        actor = vtk.vtkImageActor()
        self.actor = actor

        text_image_size = vtku.Text()
        text_image_size.SetPosition(const.TEXT_POS_LEFT_UP)
        text_image_size.SetValue("")
        text_image_size.SetSize(const.TEXT_SIZE_SMALL)
        self.text_image_size = text_image_size

        text_image_location = vtku.Text()
        text_image_location.SetVerticalJustificationToBottom()
        text_image_location.SetPosition(const.TEXT_POS_LEFT_DOWN)
        text_image_location.SetValue("")
        text_image_location.SetSize(const.TEXT_SIZE_SMALL)
        self.text_image_location = text_image_location

        text_patient = vtku.Text()
        text_patient.SetJustificationToRight()
        text_patient.SetPosition(const.TEXT_POS_RIGHT_UP)
        text_patient.SetValue("")
        text_patient.SetSize(const.TEXT_SIZE_SMALL)
        self.text_patient = text_patient

        text_acquisition = vtku.Text()
        text_acquisition.SetJustificationToRight()
        text_acquisition.SetVerticalJustificationToBottom()
        text_acquisition.SetPosition(const.TEXT_POS_RIGHT_DOWN)
        text_acquisition.SetValue("")
        text_acquisition.SetSize(const.TEXT_SIZE_SMALL)
        self.text_acquisition = text_acquisition

        renderer = vtk.vtkRenderer()
        renderer.AddActor(actor)
        renderer.AddActor(text_image_size.actor)
        renderer.AddActor(text_image_location.actor)
        renderer.AddActor(text_patient.actor)
        renderer.AddActor(text_acquisition.actor)
        self.renderer = renderer

        style = vtk.vtkInteractorStyleImage()

        interactor = wxVTKRenderWindowInteractor(self.panel, -1,
                                    size=wx.Size(340,340))
        interactor.GetRenderWindow().AddRenderer(renderer)
        interactor.SetInteractorStyle(style)
        interactor.Render()
        self.interactor = interactor

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(interactor, 1, wx.GROW|wx.EXPAND)
        sizer.Fit(self.panel)
        self.panel.SetSizer(sizer)
        self.Layout()
        self.Update()
    def start_render(self):
        # initiate slider
        self._init_slider()

        # set InteractorStyle
        interactor_style = vtk.vtkInteractorStyleImage()
        self.vtkWidget.SetInteractorStyle(interactor_style)

        # start render and interactor
        self.vtkWidget.Initialize()
        self.vtkWidget.Start()
        # set camera
        self.viewer.GetRenderer().ResetCamera()
Example #26
0
    def Start(self):
        istyle = vtk.vtkInteractorStyleImage()
        istyle.AddObserver("LeftButtonPressEvent", self.AddPoint)
        iren = Globals.renWin.GetInteractor()
        iren.SetInteractorStyle(istyle)

        self.dlg = DlgRegionAddInfo(Globals.root, self.Next, self.Reset,
                                    self.Del)
        self.dlg.SetRegionInformation(Globals.imagePipeline.GetSliceIndex(),
                                      Globals.imagePipeline.GetOrientation())

        # define a state list
        self.stateChain = [self.AddZeroCurve, self.AddOneCurve]
        self.stateIndex = 0
Example #27
0
    def Render(self, actors, force3D=False):
        """Render the plot."""
        self.ren = vtk.vtkRenderer()
        self.force3D = force3D

        self.ren.SetBackground(1, 1, 1)
        for a in actors:
            self.ren.AddActor(a)
        # self.ren.AddActor2D(self.scalarbar)
        self.renWin = self.widget.GetRenderWindow()
        self.renWin.AddRenderer(self.ren)

        # depth peeling
        self.renWin.SetAlphaBitPlanes(True)
        self.renWin.SetMultiSamples(0)
        self.ren.UseDepthPeelingOn()
        self.ren.SetMaximumNumberOfPeels(10)
        self.ren.SetOcclusionRatio(0.1)

        # set camera
        # z-axis pointing up in 3D
        if self.dim == 3:
            self.ren.GetActiveCamera().SetViewUp((0.0, 0.0, 1.0))
            self.ren.GetActiveCamera().SetPosition((100.0, 50.0, 50.0))
        else:
            self.ren.GetActiveCamera().SetParallelProjection(True)
        self.ren.ResetCamera()
        self.initview = self.getView()

        # use saved camera view if plot is 3D
        if self.view is not None and (force3D or self.dim == 3):
            self.setView(self.view)

        # self.renWin.SetWindowName(self.title)
        self.iren = self.renWin.GetInteractor()
        if self.mesh.topology().dim() == 3 or force3D:
            style = vtk.vtkInteractorStyleTrackballCamera()
        else:
            style = vtk.vtkInteractorStyleImage()
        # style = vtk.vtkInteractorStyleUnicam()
        self.iren.SetInteractorStyle(style)
        self.iren.RemoveObservers("CharEvent")
        self.iren.RemoveObservers("KeyPressEvent")
        self.iren.AddObserver("KeyPressEvent", self.key_press_methods)
        self.iren.Initialize()
        self.simple_axis(self.ren)
        if self.hideAxes:
            self.axes.SetVisibility(not self.axes.GetVisibility())

        self.renWin.Render()
Example #28
0
	def SetInteractorStyleToImage(self):
		self.interactor = self.window.GetInteractor()
		self.interactorStyle = vtk.vtkInteractorStyleImage()
		self.window.GetInteractor().SetInteractorStyle(self.interactorStyle)
		self.interactorStyle.AddObserver("MouseMoveEvent", self.MouseMoveCallback)
		self.interactorStyle.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
		self.interactorStyle.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback)

		self.sliderWidget.SetInteractor(self.interactor)
		self.sliderWidget.SetRepresentation(self.sliderRep)
		self.sliderWidget.SetAnimationModeToAnimate()
		self.sliderWidget.EnabledOn()

		self.sliderWidget.AddObserver("InteractionEvent", self.sliderCallback)
		self.sliderWidget.AddObserver("EndInteractionEvent", self.endSliderCallback)
Example #29
0
    def SetInteractor(self, interactor):
        
        self.interactor = interactor
        self.render = interactor.GetRenderWindow().GetRenderers().GetFirstRenderer()          

        istyle = vtk.vtkInteractorStyleImage()
        istyle.SetInteractor(interactor)
        istyle.AutoAdjustCameraClippingRangeOn()
        interactor.SetInteractorStyle(istyle)
        
        istyle.AddObserver("LeftButtonPressEvent", self.Click)
        istyle.AddObserver("LeftButtonReleaseEvent", self.Release)
        istyle.AddObserver("MouseMoveEvent",self.Moved)

        pick = self.pick = vtk.vtkCellPicker()
Example #30
0
    def __init__(self, parent=None):
        logging.debug("In VTKImageView::__init__()")
        super(VTKImageView, self).__init__(parent)
        self.setWindowTitle(constant.TITLE_PROGRAM)

        self.actor = vtk.vtkImageActor()
        self.textActors = []

        self.render = vtk.vtkRenderer()
        self.render.AddActor(self.actor)

        self.interactorStyle = vtk.vtkInteractorStyleImage()
        self.SetInteractorStyle(self.interactorStyle)

        self.window = self.GetRenderWindow()
        self.window.AddRenderer(self.render)
Example #31
0
def main():
    filename = get_program_parameters()
    colors = vtk.vtkNamedColors()

    # Read the file
    reader = vtk.vtkDEMReader()
    reader.SetFileName(filename)
    reader.Update()

    lut = vtk.vtkLookupTable()
    lut.SetHueRange(0.6, 0)
    lut.SetSaturationRange(1.0, 0)
    lut.SetValueRange(0.5, 1.0)
    lut.SetTableRange(reader.GetOutput().GetScalarRange())

    # Visualize
    map_colors = vtk.vtkImageMapToColors()
    map_colors.SetLookupTable(lut)
    map_colors.SetInputConnection(reader.GetOutputPort())

    # Create an actor
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(map_colors.GetOutputPort())

    # Setup renderer
    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.ResetCamera()
    renderer.SetBackground(colors.GetColor3d("Azure"))

    # Setup render window
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    # Setup render window interactor
    render_window_interactor = vtk.vtkRenderWindowInteractor()

    style = vtk.vtkInteractorStyleImage()

    render_window_interactor.SetInteractorStyle(style)

    # Render and start interaction
    render_window_interactor.SetRenderWindow(render_window)
    render_window.Render()
    render_window_interactor.Initialize()

    render_window_interactor.Start()
def DisplayComponent(source):
    renderer = vtk.vtkRenderer()
    win = vtk.vtkRenderWindow()
    win.AddRenderer(renderer)
    style = vtk.vtkInteractorStyleImage()
    intact = vtk.vtkRenderWindowInteractor()
    intact.SetInteractorStyle(style)
    intact.SetRenderWindow(win)
    planeX = vtk.vtkImagePlaneWidget()
    planeY = vtk.vtkImagePlaneWidget()
    planeZ = vtk.vtkImagePlaneWidget()

    planeX.SetInteractor(intact)
    planeY.SetInteractor(intact)
    planeZ.SetInteractor(intact)

    planeX.SetInputData(source)
    planeY.SetInputData(source)
    planeZ.SetInputData(source)

    planeX.SetPlaneOrientationToXAxes()
    planeY.SetPlaneOrientationToYAxes()
    planeZ.SetPlaneOrientationToZAxes()

    planeX.On()
    planeY.On()
    planeZ.On()

    global pos
    pos = 1

    def myCallback(obj, event):
        global pos
        #print obj.__class__.__name__," called"
        key = obj.GetKeySym()
        if key == "Up":
            pos = pos + 1
            planeX.SetSliceIndex(pos)
            print pos
            win.Render()
        else:
            pass

    intact.AddObserver(vtk.vtkCommand.KeyPressEvent, myCallback)

    intact.Start()
Example #33
0
 def _configRen(self):
     """
     Configura o VTK para renderizar a cena
     """
     # janela de rendericação
     self.renWin = vtk.vtkRenderWindow()
     self.renWin.AddRenderer(self.ren)
     self.renWin.SetSize(600, 600)
     self.renWin.SetWindowName(self.nome)
     # interação mouse-janela
     self.iren = vtk.vtkRenderWindowInteractor()
     self.iren.SetRenderWindow(self.renWin)
     # estilo de visualização de imagem
     # scroll da zoom, e arrastar com scroll move a cena
     self.iren.SetInteractorStyle(vtk.vtkInteractorStyleImage())
     self.iren.AddObserver('ExitEvent', self.hide)
     self.iren.Initialize()
    def Display(self):

        wholeExtent = self.Image.GetWholeExtent()

        self.SliceVOI[0] = wholeExtent[0]
        self.SliceVOI[1] = wholeExtent[1]
        self.SliceVOI[2] = wholeExtent[2]
        self.SliceVOI[3] = wholeExtent[3]
        self.SliceVOI[4] = wholeExtent[4]
        self.SliceVOI[5] = wholeExtent[5]

        self.SliceVOI[self.Axis * 2] = wholeExtent[self.Axis * 2]
        self.SliceVOI[self.Axis * 2 + 1] = wholeExtent[self.Axis * 2]

        range = self.Image.GetScalarRange()

        imageShifter = vtk.vtkImageShiftScale()
        imageShifter.SetInput(self.Image)
        imageShifter.SetShift(-1.0 * range[0])
        imageShifter.SetScale(255.0 / (range[1] - range[0]))
        imageShifter.SetOutputScalarTypeToUnsignedChar()

        widgetImage = imageShifter.GetOutput()

        self.ImageActor.SetInput(widgetImage)
        self.ImageActor.SetDisplayExtent(self.SliceVOI)
        self.vmtkRenderer.Renderer.AddActor(self.ImageActor)

        self.ImageTracerWidget.SetCaptureRadius(1.5)
        self.ImageTracerWidget.SetViewProp(self.ImageActor)
        self.ImageTracerWidget.SetInput(widgetImage)
        self.ImageTracerWidget.ProjectToPlaneOn()
        self.ImageTracerWidget.SetProjectionNormal(self.Axis)
        self.ImageTracerWidget.PlaceWidget()
        self.ImageTracerWidget.SetAutoClose(self.AutoClose)
        self.ImageTracerWidget.AddObserver("StartInteractionEvent",
                                           self.SetWidgetProjectionPosition)
        self.ImageTracerWidget.AddObserver("EndInteractionEvent",
                                           self.GetLineFromWidget)

        interactorStyle = vtk.vtkInteractorStyleImage()
        self.vmtkRenderer.RenderWindowInteractor.SetInteractorStyle(
            interactorStyle)

        self.vmtkRenderer.Render()
Example #35
0
def viewVtk(mat):
    import vtk

    imageData = vtk.vtkImageData()
    imageData.SetDimensions(mat.shape[0], mat.shape[1], 1)
    imageData.SetScalarTypeToUnsignedShort()
    imageData.SetNumberOfScalarComponents(1)
    imageData.AllocateScalars()

    viewer = vtk.vtkImageViewer()
    viewer.SetInput(imageData)
    viewer.SetZSlice(0)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(viewer.GetRenderWindow())

    iren.Initialize()
    iren.Start()

    imageData = vtk.vtkImageSinusoidSource()
    imageData.SetWholeExtent(0, 300, 0, 300, 0, 10)
    imageData.SetAmplitude(63)
    imageData.SetDirection(1, 1, 0)
    imageData.SetPeriod(25)

    viewer = vtk.vtkImageViewer()
    viewer.SetInput(imageData.GetOutput())
    viewer.SetColorWindow(126)
    viewer.SetColorLevel(0)
    viewer.SetZSlice(0)

    def hamschti(obj, event):
        print 'Haam:'
        print obj
        print event

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(viewer.GetRenderWindow())
    iren.Initialize()

    interactor = vtk.vtkInteractorStyleImage()
    ##interactor.AddObserver('LeftButtonPressEvent', hamschti)
    iren.SetInteractorStyle(interactor)

    iren.Start()
def DisplayComponent(source):
    renderer = vtk.vtkRenderer()
    win = vtk.vtkRenderWindow()
    win.AddRenderer(renderer)
    style = vtk.vtkInteractorStyleImage()
    intact = vtk.vtkRenderWindowInteractor()
    intact.SetInteractorStyle(style)
    intact.SetRenderWindow(win)
    planeX = vtk.vtkImagePlaneWidget()
    planeY = vtk.vtkImagePlaneWidget()
    planeZ = vtk.vtkImagePlaneWidget()

    planeX.SetInteractor(intact)
    planeY.SetInteractor(intact)
    planeZ.SetInteractor(intact)

    planeX.SetInputData(source)
    planeY.SetInputData(source)
    planeZ.SetInputData(source)

    planeX.SetPlaneOrientationToXAxes()
    planeY.SetPlaneOrientationToYAxes()
    planeZ.SetPlaneOrientationToZAxes()

    planeX.On()
    planeY.On()
    planeZ.On()

    global pos
    pos = 1

    def myCallback(obj,event):
        global pos
        #print obj.__class__.__name__," called"
        key = obj.GetKeySym() 
        if key=="Up":
            pos = pos+1
            planeX.SetSliceIndex(pos)
            print pos
            win.Render()
        else:
            pass
    intact.AddObserver(vtk.vtkCommand.KeyPressEvent,myCallback)

    intact.Start()
Example #37
0
def viewVtk(mat):
    import vtk

    imageData = vtk.vtkImageData()
    imageData.SetDimensions(mat.shape[0], mat.shape[1], 1)
    imageData.SetScalarTypeToUnsignedShort()
    imageData.SetNumberOfScalarComponents(1)
    imageData.AllocateScalars()

    viewer = vtk.vtkImageViewer()
    viewer.SetInput(imageData)
    viewer.SetZSlice(0)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(viewer.GetRenderWindow())

    iren.Initialize()
    iren.Start()

    imageData = vtk.vtkImageSinusoidSource()
    imageData.SetWholeExtent(0, 300, 0, 300, 0, 10)
    imageData.SetAmplitude(63)
    imageData.SetDirection(1, 1, 0)
    imageData.SetPeriod(25)

    viewer = vtk.vtkImageViewer()
    viewer.SetInput(imageData.GetOutput())
    viewer.SetColorWindow(126)
    viewer.SetColorLevel(0)
    viewer.SetZSlice(0)

    def hamschti(obj, event):
        print "Haam:"
        print obj
        print event

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(viewer.GetRenderWindow())
    iren.Initialize()

    interactor = vtk.vtkInteractorStyleImage()
    ##interactor.AddObserver('LeftButtonPressEvent', hamschti)
    iren.SetInteractorStyle(interactor)

    iren.Start()
Example #38
0
    def Start(self):
        istyle = vtk.vtkInteractorStyleImage()
        istyle.AddObserver("LeftButtonPressEvent",self.AddPoint)
        iren = Globals.renWin.GetInteractor()
        iren.SetInteractorStyle(istyle)

        self.dlg = DlgRegionAddInfo(Globals.root,
                                    self.Next,
                                    self.Reset,
                                    self.Del)
        self.dlg.SetRegionInformation(Globals.imagePipeline.GetSliceIndex(),
                                      Globals.imagePipeline.GetOrientation()
                                      )

        # define a state list
        self.stateChain = [ self.AddZeroCurve,
                            self.AddOneCurve
                            ]
        self.stateIndex = 0
Example #39
0
    def __init__(self,win_w,win_h):
        QMainWindow.__init__(self)
        self.setupUi(self)
        
        self.setWindowTitle("AEM GUI")
        self.setWindowIcon(QIcon('PreStruct.ico'))
        self.BlockDlg=AddBlockDlg()
        self.SteelDlg=AddSteelDlg()
        self.AEMmodel=AEMmodel()

        self.DisplayMode='Simple'

        #fix window dimensions
        self.win_w=win_w
        self.win_h=win_h
        self.setFixedSize(int(0.9*win_w),int(0.9*win_h))
        self.verticalLayoutWidget.setGeometry(QRect(int(0.11*win_w), 10, int(0.8*win_w), int(0.9*win_h)))
        self.menubar.setGeometry(QRect(0, 0, 700, 22))
        self.splitter.setGeometry(QRect(11, 10, int(0.1*win_w), int(0.25*win_h)))

        # assign push button 
        self.pushButton_block.pressed.connect(self.OpenAddElementBlockDlg)
        self.pushButton_bc.pressed.connect(self.OpenAddBoundaryDlg)
        self.pushButton_steel.pressed.connect(self.OpenAddSteelDlg)

        #checkbox
        self.checkBox_eleno.stateChanged.connect(lambda:self.btnstate(self.checkBox_eleno))
        self.checkBox_steel.stateChanged.connect(lambda:self.btnstate(self.checkBox_steel))
        self.checkBox_bc.stateChanged.connect(lambda:self.btnstate(self.checkBox_bc))
        self.checkBox_load.stateChanged.connect(lambda:self.btnstate(self.checkBox_load))

        self.renderer = vtk.vtkRenderer()
        self.frame = QFrame()
        self.renWinInteract = QVTKRenderWindowInteractor(self.frame)  
        self.verticalLayout.addWidget(self.renWinInteract)    
        self.renWin=self.renWinInteract.GetRenderWindow()
        self.renWin.SetSize(200,100)
        self.renWin.AddRenderer(self.renderer)   

        interactor = vtk.vtkInteractorStyleImage()
        self.renWinInteract.SetInteractorStyle(interactor)   
        
        self.renWinInteract.Initialize()
Example #40
0
def main():
    colors = vtk.vtkNamedColors()

    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(1, 1, 0)
    points.InsertNextPoint(2, 2, 0)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    # Create anything you want here, we will use a polygon for the demo.
    polygonSource = vtk.vtkRegularPolygonSource()  # default is 6 sides

    glyph2D = vtk.vtkGlyph2D()
    glyph2D.SetSourceConnection(polygonSource.GetOutputPort())
    glyph2D.SetInputData(polydata)
    glyph2D.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph2D.GetOutputPort())
    mapper.Update()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('Salmon'))

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

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    style = vtk.vtkInteractorStyleImage()
    renderWindowInteractor.SetInteractorStyle(style)

    renderWindow.SetWindowName('Glyph2D')
    renderWindow.Render()
    renderWindowInteractor.Start()
def main():
    # Parse input arguments
    inputFilename = 'Bunny.jpg'
    #IMREAD_COLOR sets to BGR mode
    img = cv.imread(inputFilename, cv.IMREAD_COLOR)

    # Read the image
    reader = vtk.vtkJPEGReader()
    reader.SetFileName(inputFilename)
    reader.Update()

    otherreader = vtk.vtkImageData()

    #fromMat2Vtk (input, otherreader)

    # Create an actor
    actor = vtk.vtkImageActor()
    #actor.GetMapper().SetInputConnection(reader.GetOutputPort())
    actor.GetMapper().SetInputData(fromMat2Vtk(img))

    # Setup renderer
    colors = vtk.vtkNamedColors()

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.ResetCamera()
    #renderer.SetBackground(colors.GetColor3d("Burlywood").GetData())

    # Setup render window
    window = vtk.vtkRenderWindow()
    window.AddRenderer(renderer)

    # Setup render window interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(window)

    # Setup interactor style (this is what implements the zooming, panning and brightness adjustment functionality)
    style = vtk.vtkInteractorStyleImage()
    interactor.SetInteractorStyle(style)

    # Render and start interaction
    interactor.Start()
    def Display(self):

        wholeExtent = self.Image.GetWholeExtent()

        self.SliceVOI[0] = wholeExtent[0]
        self.SliceVOI[1] = wholeExtent[1]
        self.SliceVOI[2] = wholeExtent[2]
        self.SliceVOI[3] = wholeExtent[3]
        self.SliceVOI[4] = wholeExtent[4]
        self.SliceVOI[5] = wholeExtent[5]

        self.SliceVOI[self.Axis*2] = wholeExtent[self.Axis*2]
        self.SliceVOI[self.Axis*2+1] = wholeExtent[self.Axis*2]

        range = self.Image.GetScalarRange()

        imageShifter = vtk.vtkImageShiftScale()
        imageShifter.SetInput(self.Image)
        imageShifter.SetShift(-1.0*range[0])
        imageShifter.SetScale(255.0/(range[1]-range[0]))
        imageShifter.SetOutputScalarTypeToUnsignedChar()

        widgetImage = imageShifter.GetOutput()

        self.ImageActor.SetInput(widgetImage)
        self.ImageActor.SetDisplayExtent(self.SliceVOI)
        self.vmtkRenderer.Renderer.AddActor(self.ImageActor)

        self.ImageTracerWidget.SetCaptureRadius(1.5)
        self.ImageTracerWidget.SetViewProp(self.ImageActor)
        self.ImageTracerWidget.SetInput(widgetImage)
        self.ImageTracerWidget.ProjectToPlaneOn()
        self.ImageTracerWidget.SetProjectionNormal(self.Axis)
        self.ImageTracerWidget.PlaceWidget()
        self.ImageTracerWidget.SetAutoClose(self.AutoClose)
        self.ImageTracerWidget.AddObserver("StartInteractionEvent",self.SetWidgetProjectionPosition)
        self.ImageTracerWidget.AddObserver("EndInteractionEvent",self.GetLineFromWidget)

        interactorStyle = vtk.vtkInteractorStyleImage()
        self.vmtkRenderer.RenderWindowInteractor.SetInteractorStyle(interactorStyle)

        self.vmtkRenderer.Render()
    def setupUi(self, ReadDICOMSeriesQt):
        ReadDICOMSeriesQt.setObjectName(_fromUtf8("ReadDICOMSeriesQt"))
        ReadDICOMSeriesQt.resize(541, 531)
        self.centralWidget = QtGui.QWidget(ReadDICOMSeriesQt)
        self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
        self.buttonOpenFolder = QtGui.QPushButton(self.centralWidget)
        self.buttonOpenFolder.setGeometry(QtCore.QRect(10, 430, 121, 24))
        self.buttonOpenFolder.setObjectName(_fromUtf8("buttonOpenFolder"))
        self.sliderSlices = QtGui.QSlider(self.centralWidget)
        self.sliderSlices.setGeometry(QtCore.QRect(140, 430, 381, 23))
        self.sliderSlices.setOrientation(QtCore.Qt.Horizontal)
        self.sliderSlices.setObjectName(_fromUtf8("sliderSlices"))
        self.labelFolderName = QtGui.QLabel(self.centralWidget)
        self.labelFolderName.setGeometry(QtCore.QRect(140, 470, 381, 15))
        self.labelFolderName.setObjectName(_fromUtf8("labelFolderName"))
        self.labelSlicesNumber = QtGui.QLabel(self.centralWidget)
        self.labelSlicesNumber.setGeometry(QtCore.QRect(140, 500, 381, 15))
        self.labelSlicesNumber.setObjectName(_fromUtf8("labelSlicesNumber"))
        self.labelSlicesNumberTitle = QtGui.QLabel(self.centralWidget)
        self.labelSlicesNumberTitle.setGeometry(QtCore.QRect(20, 500, 59, 15))
        self.labelSlicesNumberTitle.setObjectName(
            _fromUtf8("labelSlicesNumberTitle"))
        self.labelFolderNameTitle = QtGui.QLabel(self.centralWidget)
        self.labelFolderNameTitle.setGeometry(QtCore.QRect(20, 470, 59, 15))
        self.labelFolderNameTitle.setObjectName(
            _fromUtf8("labelFolderNameTitle"))
        self.qvtkWidget = QVTKRenderWindowInteractor(self.centralWidget)
        self.qvtkWidget.setGeometry(QtCore.QRect(10, 10, 521, 411))
        self.qvtkWidget.setObjectName(_fromUtf8("qvtkWidget"))
        ReadDICOMSeriesQt.setCentralWidget(self.centralWidget)

        self.reader = vtk.vtkDICOMImageReader()
        self.imageViewer = vtk.vtkImageViewer()
        self.interactor = vtk.vtkInteractorStyleImage()
        self.renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        self.minSlice = 0
        self.maxSlice = 0
        self.fname = ""
        self.dicomfiles = []

        self.retranslateUi(ReadDICOMSeriesQt)
        QtCore.QMetaObject.connectSlotsByName(ReadDICOMSeriesQt)
def main():
    rwi = vtk.vtkRenderWindowInteractor()

    istyle = vtk.vtkInteractorStyleImage()
    rwi.SetInteractorStyle(istyle)

    rw = vtk.vtkRenderWindow()
    rwi.SetRenderWindow(rw)

    ren = vtk.vtkRenderer()
    ren.SetBackground(1,1,1)
    ren.GetActiveCamera().SetParallelProjection(1)
    rw.AddRenderer(ren)

    rwi.Initialize()


    ta1 = make_glyph(ren, (0,0), 'Hello thereTTT\nHoo you too')

    ta2 = make_glyph(ren, (0,100), 'What ghte')

    ta3 = make_glyph(ren, (-100, -100), 'To the left and below')

    ren.ResetCamera()
    rw.Render()

    b = ta1.GetBounds()
    b = [0,0,0,0]
    ta1.GetBoundingBox(b)
    print b

    ss = vtk.vtkSphereSource()
    ss.SetRadius(32)
    sm = vtk.vtkPolyDataMapper()
    sm.SetInput(ss.GetOutput())
    sa = vtk.vtkActor()
    sa.SetMapper(sm)
    sa.SetPosition((b[1] - b[0],b[3] - b[2],0))
    ren.AddActor(sa)

    rwi.Start()
    def Visualize(self):
        renderSize = 300;
        numberOfImages = 1;   #implement only one image visulization

        # Setup the render window and interactor
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.SetSize(renderSize * numberOfImages, renderSize)

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

        style = vtk.vtkInteractorStyleImage()
        interactor.SetInteractorStyle(style)

        # Render all of the images
        background = [0.4,0.5,0.6]

        sharedCamera = vtk.vtkCamera()
        actor = vtk.vtkImageActor()

        #connect itk image to vtk image
        connector = self.i2vConnector.New()
        connector.SetInput(self.m_Image)

        actor.SetInput(connector.GetOutput())

        renderer = vtk.vtkRenderer()
        renderWindow.AddRenderer(renderer)
        #renderer.SetViewpint()
        renderer.SetBackground(background)


        # start visualization
        renderer.AddActor(actor)
        renderer.ResetCamera()

        renderWindow.Render()

        # start interactor
        interactor.Start()
Example #46
0
    def createOrthoView(self):
        """Create an accompanying orthographic view of the sliceDirection
        encapsulated by this object.
        """

        # there can be only one orthoPipeline
        if not self._orthoPipeline:

            import modules.resources.python.slice3dVWRFrames            
            # import our wxGlade-generated frame
            ovf = modules.resources.python.slice3dVWRFrames.orthoViewFrame
            self._orthoViewFrame = ovf(
                self.sliceDirections.slice3dVWR.threedFrame, id=-1,
                title='dummy')

            self._orthoViewFrame.SetIcon(module_utils.get_module_icon())

            self._renderer = vtk.vtkRenderer()
            self._renderer.SetBackground(0.5, 0.5, 0.5)
            self._orthoViewFrame.RWI.GetRenderWindow().AddRenderer(
                self._renderer)
            istyle = vtk.vtkInteractorStyleImage()
            self._orthoViewFrame.RWI.SetInteractorStyle(istyle)

            wx.EVT_CLOSE(self._orthoViewFrame,
                         lambda e, s=self: s.destroyOrthoView)

            wx.EVT_BUTTON(self._orthoViewFrame,
                          self._orthoViewFrame.closeButtonId,
                          lambda e, s=self: s.destroyOrthoView)

            for ipw in self._ipws:
                self._createOrthoPipelineForNewIPW(ipw)

            if self._ipws:
                self._resetOrthoView()

            self._orthoViewFrame.Show(True)
Example #47
0
 def set_interactor_style_image(self):
     self.vtkWidget.set_interactor_style(vtkInteractorStyleImage())
Example #48
0
def TestDisplay(file1):
    """Display the output"""

    inpath = os.path.join(str(VTK_DATA_ROOT), "Data", file1)

    reader = vtk.vtkNIFTIImageReader()
    reader.SetFileName(inpath)
    reader.Update()

    size = reader.GetOutput().GetDimensions()
    center = reader.GetOutput().GetCenter()
    spacing = reader.GetOutput().GetSpacing()
    center1 = (center[0], center[1], center[2])
    center2 = (center[0], center[1], center[2])
    if size[2] % 2 == 1:
        center1 = (center[0], center[1], center[2] + 0.5*spacing[2])
    if size[0] % 2 == 1:
        center2 = (center[0] + 0.5*spacing[0], center[1], center[2])
    vrange = reader.GetOutput().GetScalarRange()

    map1 = vtk.vtkImageSliceMapper()
    map1.BorderOn()
    map1.SliceAtFocalPointOn()
    map1.SliceFacesCameraOn()
    map1.SetInputConnection(reader.GetOutputPort())
    map2 = vtk.vtkImageSliceMapper()
    map2.BorderOn()
    map2.SliceAtFocalPointOn()
    map2.SliceFacesCameraOn()
    map2.SetInputConnection(reader.GetOutputPort())

    slice1 = vtk.vtkImageSlice()
    slice1.SetMapper(map1)
    slice1.GetProperty().SetColorWindow(vrange[1]-vrange[0])
    slice1.GetProperty().SetColorLevel(0.5*(vrange[0]+vrange[1]))
    slice2 = vtk.vtkImageSlice()
    slice2.SetMapper(map2)
    slice2.GetProperty().SetColorWindow(vrange[1]-vrange[0])
    slice2.GetProperty().SetColorLevel(0.5*(vrange[0]+vrange[1]))

    ratio = size[0]*1.0/(size[0]+size[2])

    ren1 = vtk.vtkRenderer()
    ren1.SetViewport(0,0,ratio,1.0)
    ren2 = vtk.vtkRenderer()
    ren2.SetViewport(ratio,0.0,1.0,1.0)
    ren1.AddViewProp(slice1)
    ren2.AddViewProp(slice2)

    cam1 = ren1.GetActiveCamera()
    cam1.ParallelProjectionOn()
    cam1.SetParallelScale(0.5*spacing[1]*size[1])
    cam1.SetFocalPoint(center1[0], center1[1], center1[2])
    cam1.SetPosition(center1[0], center1[1], center1[2] - 100.0)

    cam2 = ren2.GetActiveCamera()
    cam2.ParallelProjectionOn()
    cam2.SetParallelScale(0.5*spacing[1]*size[1])
    cam2.SetFocalPoint(center2[0], center2[1], center2[2])
    cam2.SetPosition(center2[0] + 100.0, center2[1], center2[2])

    if "-I" in sys.argv:
        style = vtk.vtkInteractorStyleImage()
        style.SetInteractionModeToImageSlicing()

        iren = vtk.vtkRenderWindowInteractor()
        iren.SetInteractorStyle(style)

    renwin = vtk.vtkRenderWindow()
    renwin.SetSize(size[0] + size[2], size[1])
    renwin.AddRenderer(ren1)
    renwin.AddRenderer(ren2)

    renwin.Render()

    if "-I" in sys.argv:
        renwin.SetInteractor(iren)
        iren.Initialize()
        iren.Start()

    return renwin
Example #49
0
	def __init__(self, data_source, input_link):
		"""Parallel coordinates view constructor needs a valid DataSource plus
		and external annotation link (from the icicle view).
		"""		
		
		self.ds = data_source
		self.input_link = input_link
		
		# Set up callback to listen for changes in IcicleView selections
		self.input_link.AddObserver("AnnotationChangedEvent", self.InputSelectionCallback)
		
		# Set up an annotation link for other views to monitor selected image
		self.output_link = vtk.vtkAnnotationLink()
		# If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
		# See vtkSelectionNode doc for field and content type enum values
		self.output_link.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		# The chart seems to force INDEX selection, so I'm using vtkConvertSelection below to get
		# out PedigreeIds...
		self.output_link.GetCurrentSelection().GetNode(0).SetContentType(2)   # 2 = PedigreeIds, 4 = Indices
		# Going to manually create output_link selection list, so not setting up callback for it...
		
		if os.path.isfile(os.path.abspath('BlankImage.png')):
			blank_file = 'BlankImage.png'
		else:
			# For use in app bundles
			blank_file = os.path.join(sys.path[0],'BlankImage.png')
			
		self.blankImageReader = vtk.vtkPNGReader()
		self.blankImageReader.SetFileName(blank_file)
		self.blankImageReader.Update()
		
		tmp = self.blankImageReader.GetOutput().GetBounds()
		self.flowSpacing = float(tmp[1]-tmp[0])*1.1

		# Create a greyscale lookup table
		self.lut = self.ds.GetGrayscaleLUT('gray')
		self.lut.SetRange(self.blankImageReader.GetOutput().GetPointData().GetArray('PNGImage').GetRange()) # image intensity range
		
		# Map the image through the lookup table
		self.color = vtk.vtkImageMapToColors()
		self.color.SetLookupTable(self.lut)
		self.color.SetInput(self.blankImageReader.GetOutput())
		
		self.resliceList = []
		self.actorList = []
		self.numImages = 1

		# Map between indices of images and their Pedigree ID
		self.pedigree_id_dict = {}
		
		blankImageActor = vtk.vtkImageActor()
		blankImageActor.SetInput(self.color.GetOutput())
		blankImageActor.SetPickable(False)
		blankImageActor.SetOpacity(0.1)
		
		self.actorList.append(blankImageActor)

		self.expSpread = 0.5
		self.maxAngle = 80.0
		
		self.renderer = vtk.vtkRenderer()
		self.cam = self.renderer.GetActiveCamera()

		# renderer.SetBackground(0.15, 0.12, 0.1)
		# cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [68,57,53]]
		# self.renderer.SetBackground(cc0,cc1,cc2)
		# cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [60,60,60]]
		cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [160, 160, 160]]
		self.renderer.SetBackground(cc0,cc1,cc2)

		self.renderer.AddActor(self.actorList[0])
				
		self.highlightRect = vtk.vtkOutlineSource()
		self.highlightRect.SetBounds(self.actorList[0].GetBounds())
		self.highlightMapper = vtk.vtkPolyDataMapper()
		self.highlightMapper.SetInputConnection(self.highlightRect.GetOutputPort(0))
		self.highlightActor = vtk.vtkActor()
		self.highlightActor.SetMapper(self.highlightMapper)
		self.highlightActor.GetProperty().SetColor(0,0.5,1.0)
		self.highlightActor.GetProperty().SetLineWidth(6.0)
		self.highlightActor.GetProperty().SetOpacity(0.5)
		self.highlightActor.SetOrientation(self.actorList[0].GetOrientation())
		tmpPos = self.actorList[0].GetPosition()
		usePos = (tmpPos[0],tmpPos[1],tmpPos[2]+0.01)
		self.highlightActor.SetPosition(usePos)
		# Setting as if nothing picked even though initialized position & orientation to actor0
		self.highlightIndex = -1
		self.highlightActor.SetPickable(False)
		self.highlightActor.SetVisibility(False)
		self.renderer.AddActor(self.highlightActor)

		# Create the slider which will control the image positions
		self.sliderRep = vtk.vtkSliderRepresentation2D()
		self.sliderRep.SetMinimumValue(0)
		self.sliderRep.SetMaximumValue(self.numImages-1)
		self.sliderRep.SetValue(0)
		
		self.window = vtk.vtkRenderWindow()
		self.window.SetSize(600,300)

		self.window.AddRenderer(self.renderer)
				
		# Set up the interaction
		self.interactorStyle = vtk.vtkInteractorStyleImage()
		self.interactor = vtk.vtkRenderWindowInteractor()
		self.interactor.SetInteractorStyle(self.interactorStyle)
		self.window.SetInteractor(self.interactor)
				
		self.sliderWidget = vtk.vtkSliderWidget()
		self.sliderWidget.SetInteractor(self.interactor)
		self.sliderWidget.SetRepresentation(self.sliderRep)
		self.sliderWidget.SetAnimationModeToAnimate()
		self.sliderWidget.EnabledOn()
		
		self.sliderWidget.AddObserver("InteractionEvent", self.sliderCallback)
		self.sliderWidget.AddObserver("EndInteractionEvent", self.endSliderCallback)
		
		# Default flow direction Horizontal
		self.FlowDirection = Direction.Horizontal
		self.SetFlowDirection(self.FlowDirection)
				
		# Set up callback to toggle between inspect modes (manip axes & select data)
		# self.interactorStyle.AddObserver("SelectionChangedEvent", self.selectImage)

		# Create callbacks for mouse events
		self.mouseActions = {}
		self.mouseActions["LeftButtonDown"] = 0
		self.mouseActions["Picking"] = 0
		
		self.interactorStyle.AddObserver("MouseMoveEvent", self.MouseMoveCallback)
		self.interactorStyle.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
		self.interactorStyle.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback)

		self.cam.ParallelProjectionOn()
		self.renderer.ResetCamera(self.actorList[0].GetBounds())
		self.cam.Elevation(10)
		self.renderer.ResetCameraClippingRange()
Example #50
0
    def __config_interactor(self):
        style = vtk.vtkInteractorStyleImage()

        interactor = self.interactor
        interactor.SetInteractorStyle(style)
Example #51
0
 def Start(self):
     istyle = vtk.vtkInteractorStyleImage()
     istyle.AddObserver("RightButtonPressEvent",self.PlacePointer)
     iren = Globals.renWin.GetInteractor()
     iren.SetInteractorStyle(istyle)
Example #52
0
 def createInteractorStyle(self):
     return vtk.vtkInteractorStyleImage()
Example #53
0
    def initView(self, data, widget):
        super(SingleDataView, self).initView(data, widget)
        
        shapeList = data.getData().shape
        y, x = shapeList[-2], shapeList[-1]
        self.dimension = len(shapeList) == 2
        
        self.reslice_mapper = vtk.vtkImageResliceMapper()
        self.reslice_mapper.SetInput(self.image_resample.GetOutput())
        self.reslice_mapper.SliceFacesCameraOn()
        self.reslice_mapper.SliceAtFocalPointOn()
        self.reslice_mapper.JumpToNearestSliceOn()
        self.reslice_mapper.BorderOff()
        self.reslice_mapper.BackgroundOn()
        
        array = data.getData()
        self.minI = array.min()
        self.maxI = array.max()
#        self.minI = 0
#        self.maxI = 255
        image_property = vtk.vtkImageProperty()
        image_property.SetColorWindow(self.maxI - self.minI)
        image_property.SetColorLevel((self.maxI + self.minI) / 2.0)
        image_property.SetAmbient(0.0)
        image_property.SetDiffuse(1.0)
        image_property.SetOpacity(1.0)
        image_property.SetInterpolationTypeToLinear()
        
        self.image_slice = vtk.vtkImageSlice()
        self.image_slice.SetMapper(self.reslice_mapper)
        self.image_slice.SetProperty(image_property)
        
        self.renderer.AddViewProp(self.image_slice)
        
        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.interactor_style = vtk.vtkInteractorStyleImage()
        self.interactor_style.SetInteractionModeToImage3D()
        self.window_interactor.SetInteractorStyle(self.interactor_style)
        self.render_window.SetInteractor(self.window_interactor)
        point_picker = vtk.vtkPointPicker()
        self.window_interactor.SetPicker(point_picker)
        
        self.render_window.GlobalWarningDisplayOff()
        self.render_window.Render()
        self.camera = self.renderer.GetActiveCamera()
        self.camera.ParallelProjectionOn()
        w, h = self.window_interactor.GetSize()
        if h * x * self.space[0] < w * y * self.space[1]:
            scale = y / 2.0 * self.space[1]
        else:
            scale = h * x  * self.space[0] / 2.0 / w
        self.camera.SetParallelScale(scale)
        point = self.camera.GetFocalPoint()
        dis = self.camera.GetDistance()
        self.camera.SetViewUp(0, -1, 0)
        self.camera.SetPosition(point[0], point[1], point[2] - dis)
        self.renderer.ResetCameraClippingRange()
        
        # View of image
        self.view = 2
                
        self.interactor_style.AddObserver("MouseMoveEvent", self.MouseMoveCallback)
        self.interactor_style.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback)
        self.interactor_style.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
        self.interactor_style.AddObserver("MiddleButtonPressEvent", self.MiddleButtonPressCallback)
        self.interactor_style.AddObserver("RightButtonPressEvent", self.RightButtonPressCallback)
        self.interactor_style.AddObserver("RightButtonReleaseEvent", self.RightButtonReleaseCallback)
        self.interactor_style.AddObserver("KeyPressEvent", self.KeyPressCallback)
        self.interactor_style.AddObserver("CharEvent", self.CharCallback)
        
        #self.plugin[0].enable(self)
        self.updateAfter()
        
        self.render_window.Render()
Example #54
0
    def Display(self):

        wholeExtent = self.Image.GetExtent()

        self.SliceVOI[0] = wholeExtent[0]
        self.SliceVOI[1] = wholeExtent[1]
        self.SliceVOI[2] = wholeExtent[2]
        self.SliceVOI[3] = wholeExtent[3]
        self.SliceVOI[4] = wholeExtent[4]
        self.SliceVOI[5] = wholeExtent[5]

        self.SliceVOI[self.Axis * 2] = wholeExtent[self.Axis * 2]
        self.SliceVOI[self.Axis * 2 + 1] = wholeExtent[self.Axis * 2]

        range = self.Image.GetScalarRange()

        imageShifter = vtk.vtkImageShiftScale()
        imageShifter.SetInput(self.Image)
        imageShifter.SetShift(-1.0 * range[0])
        imageShifter.SetScale(255.0 / (range[1] - range[0]))
        imageShifter.SetOutputScalarTypeToUnsignedChar()

        widgetImage = imageShifter.GetOutput()

        self.ImageActor.SetInput(widgetImage)
        self.ImageActor.SetDisplayExtent(self.SliceVOI)
        self.vmtkRenderer.Renderer.AddActor(self.ImageActor)

        if self.Type == "freehand":
            self.ImageTracerWidget.SetCaptureRadius(1.5)
            self.ImageTracerWidget.SetViewProp(self.ImageActor)
            self.ImageTracerWidget.SetInput(widgetImage)
            self.ImageTracerWidget.ProjectToPlaneOn()
            self.ImageTracerWidget.SetProjectionNormal(self.Axis)
            self.ImageTracerWidget.PlaceWidget()
            self.ImageTracerWidget.SetAutoClose(self.AutoClose)
            self.ImageTracerWidget.AddObserver("StartInteractionEvent", self.SetWidgetProjectionPosition)
            self.ImageTracerWidget.AddObserver("EndInteractionEvent", self.GetLineFromWidget)
        elif self.Type == "contour":
            self.ImageTracerWidget.AddObserver("EndInteractionEvent", self.GetLineFromWidget)
            self.ImageTracerWidget.ContinuousDrawOff()

        sliderRep = vtk.vtkSliderRepresentation2D()
        sliderRep.SetValue(0.5 * (wholeExtent[self.Axis * 2] + wholeExtent[self.Axis * 2 + 1]))
        sliderRep.SetMinimumValue(wholeExtent[self.Axis * 2])
        sliderRep.SetMaximumValue(wholeExtent[self.Axis * 2 + 1])
        sliderRep.SetTitleText("Slice")
        sliderRep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
        sliderRep.GetPoint1Coordinate().SetValue(0.2, 0.9)
        sliderRep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
        sliderRep.GetPoint2Coordinate().SetValue(0.8, 0.9)
        sliderRep.SetSliderLength(0.02)
        sliderRep.SetSliderWidth(0.03)
        sliderRep.SetEndCapLength(0.01)
        sliderRep.SetEndCapWidth(0.03)
        sliderRep.SetTubeWidth(0.005)
        sliderRep.SetLabelFormat("%.0f")

        self.SliderWidget.AddObserver("InteractionEvent", self.ChangeSlice)
        self.SliderWidget.SetRepresentation(sliderRep)
        self.SliderWidget.EnabledOn()

        interactorStyle = vtk.vtkInteractorStyleImage()
        self.vmtkRenderer.RenderWindowInteractor.SetInteractorStyle(interactorStyle)

        self.vmtkRenderer.Render()
# This example shows how to load a 3D image into VTK and then reformat
# that image into a different orientation for viewing.  It uses
# vtkImageReslice for reformatting the image, and uses vtkImageActor
# and vtkInteractorStyleImage to display the image.  This InteractorStyle
# forces the camera to stay perpendicular to the XY plane.

import vtk

# these globals are needed for this to work. perhaps create a class
# later.  the below code was modified from a vtk example, to create a
# function to call for rendering.
reslice = vtk.vtkImageReslice()
window = vtk.vtkRenderWindow()
interactorStyle = vtk.vtkInteractorStyleImage()
interactor = vtk.vtkRenderWindowInteractor()
table = vtk.vtkLookupTable()
color = vtk.vtkImageMapToColors()
actor = vtk.vtkImageActor()
renderer = vtk.vtkRenderer()
actions = {}
    
def ButtonCallback(obj, event):
    #print "button"
    if event == "LeftButtonPressEvent":
        actions["Slicing"] = 1
    else:
        actions["Slicing"] = 0

def MouseMoveCallback(obj, event):
    #print "mouse move"
    (lastX, lastY) = interactor.GetLastEventPosition()
Example #56
0
def display(image, image_pos_pat, image_ori_pat):
	global xMin, xMax, yMin, yMax, zMin, zMax, xSpacing, ySpacing, zSpacing, interactor, actions, reslice, interactorStyle
	# The box widget observes the events invoked by the render window
	# interactor.  These events come from user interaction in the render
	# window.
	# boxWidget = vtk.vtkBoxWidget()
	# boxWidget.SetInteractor(iren1)
	# boxWidget.SetPlaceFactor(1)
	
	# Initialize Image orienation
	IO = matrix(	[[0, 0,-1, 0],
			[1, 0, 0, 0],
			[0,-1, 0, 0],
			[0, 0, 0, 1]])
	# Assign the 6-Image orientation patient coordinates (from Dicomtags)
	IO[0,0] = image_ori_pat[0]; IO[1,0] = image_ori_pat[1]; IO[2,0] = image_ori_pat[2]; 
	IO[0,1] = image_ori_pat[3]; IO[1,1] = image_ori_pat[4]; IO[2,1] = image_ori_pat[5]; 
	
	# obtain thrid column as the cross product of column 1 y 2
	IO_col1 = [image_ori_pat[0], image_ori_pat[1], image_ori_pat[2]]
	IO_col2 = [image_ori_pat[3], image_ori_pat[4], image_ori_pat[5]]
	IO_col3 = cross(IO_col1, IO_col2)
	
	# assign column 3	
	IO[0,2] = IO_col3[0]; IO[1,2] = IO_col3[1]; IO[2,2] = IO_col3[2]; 
	
	IP =  array([0, 0, 0, 1]) # Initialization Image Position
	IP[0] = image_pos_pat[0]; IP[1] = image_pos_pat[1]; IP[2] = image_pos_pat[2];  
	IO[0,3] = image_pos_pat[0]; IO[1,3] = image_pos_pat[1]; IO[2,3] = image_pos_pat[2]
	
	print "image_pos_pat :"
	print image_pos_pat
	print "image_ori_pat:"
	print image_ori_pat
	
	origin = IP*IO.I
	print "Volume Origin:"
	print origin[0,0], origin[0,1], origin[0,2]
	
	# Create matrix 4x4
	DICOM_mat = vtk.vtkMatrix4x4();
	DICOM_mat.SetElement(0, 0, IO[0,0])
	DICOM_mat.SetElement(0, 1, IO[0,1])
	DICOM_mat.SetElement(0, 2, IO[0,2])
	DICOM_mat.SetElement(0, 3, IO[0,3])
	
	DICOM_mat.SetElement(1, 0, IO[1,0])
	DICOM_mat.SetElement(1, 1, IO[1,1])
	DICOM_mat.SetElement(1, 2, IO[1,2])
	DICOM_mat.SetElement(1, 3, IO[1,3])
	
	DICOM_mat.SetElement(2, 0, IO[2,0])
	DICOM_mat.SetElement(2, 1, IO[2,1])
	DICOM_mat.SetElement(2, 2, IO[2,2])
	DICOM_mat.SetElement(2, 3, IO[2,3])
	
	DICOM_mat.SetElement(3, 0, IO[3,0])
	DICOM_mat.SetElement(3, 1, IO[3,1])
	DICOM_mat.SetElement(3, 2, IO[3,2])
	DICOM_mat.SetElement(3, 3, IO[3,3])
	#DICOM_mat.Invert()
	
	# Set up the axes	
	transform = vtk.vtkTransform()
	transform.Concatenate(DICOM_mat)
	transform.Update()
	
	# Set up the cube (set up the translation back to zero	
	DICOM_mat_cube = vtk.vtkMatrix4x4();
	DICOM_mat_cube.DeepCopy(DICOM_mat)
	DICOM_mat_cube.SetElement(0, 3, 0)
	DICOM_mat_cube.SetElement(1, 3, 0)
	DICOM_mat_cube.SetElement(2, 3, 0)
		
	transform_cube = vtk.vtkTransform()
	transform_cube.Concatenate(DICOM_mat_cube)
	transform_cube.Update()
	
	##########################
	# Calculate the center of the volume
	(xMin, xMax, yMin, yMax, zMin, zMax) = image.GetWholeExtent()
	(xSpacing, ySpacing, zSpacing) = image.GetSpacing()
	(x0, y0, z0) = image.GetOrigin()
	
	center = [x0 + xSpacing * 0.5 * (xMin + xMax),
		  y0 + ySpacing * 0.5 * (yMin + yMax),
		  z0 + zSpacing * 0.5 * (zMin + zMax)]
	
	# Matrices for axial, coronal, sagittal, oblique view orientations
	axial = vtk.vtkMatrix4x4()
	axial.DeepCopy((1, 0, 0, center[0],
			0, 1, 0, center[1],
			0, 0, 1, center[2],
			0, 0, 0, 1))
	
	coronal = vtk.vtkMatrix4x4()
	coronal.DeepCopy((1, 0, 0, center[0],
			  0, 0, 1, center[1],
			  0,-1, 0, center[2],
			  0, 0, 0, 1))
	
	sagittal = vtk.vtkMatrix4x4()
	sagittal.DeepCopy((0, 0,-1, center[0],
			   1, 0, 0, center[1],
			   0,-1, 0, center[2],
			   0, 0, 0, 1))
	
	oblique = vtk.vtkMatrix4x4()
	oblique.DeepCopy((1, 0, 0, center[0],
			  0, 0.866025, -0.5, center[1],
			  0, 0.5, 0.866025, center[2],
			  0, 0, 0, 1))
	
	# Extract a slice in the desired orientation
	reslice = vtk.vtkImageReslice()
	reslice.SetInput(image)
	reslice.SetOutputDimensionality(2)
	reslice.SetResliceAxes(sagittal)
	reslice.SetInterpolationModeToLinear()
	
	# Create a greyscale lookup table
	table = vtk.vtkLookupTable()
	table.SetRange(0, 2000) # image intensity range
	table.SetValueRange(0.0, 1.0) # from black to white
	table.SetSaturationRange(0.0, 0.0) # no color saturation
	table.SetRampToLinear()
	table.Build()
	
	# Map the image through the lookup table
	color = vtk.vtkImageMapToColors()
	color.SetLookupTable(table)
	color.SetInputConnection(reslice.GetOutputPort())

	# Display the image
	actor = vtk.vtkImageActor()
	actor.GetMapper().SetInputConnection(color.GetOutputPort())

	renderer1 = vtk.vtkRenderer()
	renderer1.AddActor(actor)
	################
	    
	
	# set up cube actor with Orientation(R-L, A-P, S-O) using transform_cube
	# Set up to ALS (+X=A, +Y=S, +Z=L) source:
	cube = vtk.vtkAnnotatedCubeActor()
	cube.SetXPlusFaceText( "S" );
	cube.SetXMinusFaceText( "I" );
	cube.SetYPlusFaceText( "L" );
	cube.SetYMinusFaceText( "R" );
	cube.SetZPlusFaceText( "A" );
	cube.SetZMinusFaceText( "P" );
	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( iren1 );
	widget.SetViewport( 0.0, 0.0, 0.4, 0.4 );
	widget.SetEnabled( 1 );
	widget.InteractiveOff();
			
	# Set Up Camera view
	renderer1.SetBackground(0.0, 0.0, 0.0)
	camera = renderer1.GetActiveCamera()

	# bounds and initialize camera
	b = image.GetBounds()
	renderer1.ResetCamera(b)	
	renderer1.ResetCameraClippingRange()
	camera.SetViewUp(0.0,-1.0,0.0)
	camera.Azimuth(315)
	
	# 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(image)
	axes.SetCamera(renderer1.GetActiveCamera())
	axes.SetLabelFormat("%6.4g")
	axes.SetFlyModeToOuterEdges()
	axes.SetFontFactor(1.2)
	axes.SetAxisTitleTextProperty(tprop)
	axes.SetAxisLabelTextProperty(tprop)      
	renderer1.AddViewProp(axes)
	
	############
	# Place the interactor initially. The input to a 3D widget is used to
	# initially position and scale the widget. The "EndInteractionEvent" is
  	# observed which invokes the SelectPolygons callback.
    	# boxWidget.SetInput(image)
	# boxWidget.PlaceWidget()
	# boxWidget.AddObserver("InteractionEvent", SelectPolygons)
	# boxWidget.On()
	# Initizalize
	# Set up the interaction
	interactorStyle = vtk.vtkInteractorStyleImage()
	interactor = vtk.vtkRenderWindowInteractor()
	interactor.SetInteractorStyle(interactorStyle)
	renWin1.SetInteractor(interactor)
	renWin1.Render()
	
	renderer1.Render()
	interactor.Start()
	renderer1.RemoveViewProp(axes)
						
	return transform_cube, zImagePlaneWidget.GetSliceIndex()
Example #57
0
 def initView(self, data, widget):
     image_type = data.getITKImageType()
     self.image = data.getITKImage()
     self.space = data.getResolution().tolist()
     
     if len(self.space) == 3:
         self.space = [float(x) / self.space[-1] for x in self.space]
     
     self.image.SetSpacing(self.space)
     self.rescale_filter = itk.RescaleIntensityImageFilter[image_type, image_type].New()
     self.rescale_filter.SetOutputMinimum(0)
     self.rescale_filter.SetOutputMaximum(255)
     self.rescale_filter.SetInput(self.image)
     self.itk_vtk_converter = itk.ImageToVTKImageFilter[image_type].New()
     self.itk_vtk_converter.SetInput(self.rescale_filter.GetOutput())
     self.image_resample = vtk.vtkImageResample()
     self.image_resample.SetInput(self.itk_vtk_converter.GetOutput())
     
     data = self.parent.getData()
     image_type = data.getITKImageType()
     self.image2 = data.getITKImage()
     self.space2 = data.getResolution().tolist()
     
     if len(self.space2) == 3:
         self.space2 = [float(x) / self.space2[-1] for x in self.space2]
     self.image2.SetSpacing(self.space2)
     shapeList = data.getData().shape
     y, x = shapeList[-2], shapeList[-1]
     self.dimension = len(shapeList) == 2
     
     self.rescale_filter2 = itk.RescaleIntensityImageFilter[image_type, image_type].New()
     self.rescale_filter2.SetOutputMinimum(0)
     self.rescale_filter2.SetOutputMaximum(255)
     self.rescale_filter2.SetInput(self.image2)
     self.itk_vtk_converter2 = itk.ImageToVTKImageFilter[image_type].New()
     self.itk_vtk_converter2.SetInput(self.rescale_filter2.GetOutput())
     self.image_resample2 = vtk.vtkImageResample()
     self.image_resample2.SetInput(self.itk_vtk_converter2.GetOutput())
     
     self.checkers = vtk.vtkImageCheckerboard()
     self.checkers.SetInput1(self.image_resample.GetOutput())
     self.checkers.SetInput2(self.image_resample2.GetOutput())
     self.division = 3
     self.checkers.SetNumberOfDivisions(self.division, self.division, 0)
     
     self.renderer = vtk.vtkRenderer()
     self.render_window = widget.GetRenderWindow()
     self.render_window.AddRenderer(self.renderer)
     
     self.reslice_mapper = vtk.vtkImageResliceMapper()
     self.reslice_mapper.SetInput(self.checkers.GetOutput())
     self.reslice_mapper.SliceFacesCameraOn()
     self.reslice_mapper.SliceAtFocalPointOn()
     self.reslice_mapper.JumpToNearestSliceOn()
     self.reslice_mapper.BorderOff()
     self.reslice_mapper.BackgroundOn()
     
     array = data.getData()
     self.minI = 0
     self.maxI = 255
     image_property = vtk.vtkImageProperty()
     image_property.SetColorWindow(self.maxI - self.minI)
     image_property.SetColorLevel((self.maxI + self.minI) / 2.0)
     image_property.SetAmbient(0.0)
     image_property.SetDiffuse(1.0)
     image_property.SetOpacity(1.0)
     image_property.SetInterpolationTypeToLinear()
     
     self.image_slice = vtk.vtkImageSlice()
     self.image_slice.SetMapper(self.reslice_mapper)
     self.image_slice.SetProperty(image_property)
     
     self.renderer.AddViewProp(self.image_slice)
     
     self.window_interactor = vtk.vtkRenderWindowInteractor()
     self.interactor_style = vtk.vtkInteractorStyleImage()
     self.interactor_style.SetInteractionModeToImage3D()
     self.window_interactor.SetInteractorStyle(self.interactor_style)
     self.render_window.SetInteractor(self.window_interactor)
     point_picker = vtk.vtkPointPicker()
     self.window_interactor.SetPicker(point_picker)
     
     self.render_window.GlobalWarningDisplayOff()
     self.render_window.Render()
     self.camera = self.renderer.GetActiveCamera()
     self.camera.ParallelProjectionOn()
     w, h = self.window_interactor.GetSize()
     if h * x * self.space[0] < w * y * self.space[1]:
         scale = y / 2.0 * self.space[1]
     else:
         scale = h * x  * self.space[0] / 2.0 / w
     self.camera.SetParallelScale(scale)
     point = self.camera.GetFocalPoint()
     dis = self.camera.GetDistance()
     self.camera.SetViewUp(0, -1, 0)
     self.camera.SetPosition(point[0], point[1], point[2] - dis)
     self.renderer.ResetCameraClippingRange()
     
     # View of image
     self.view = 2
             
     self.interactor_style.AddObserver("MouseMoveEvent", self.MouseMoveCallback)
     self.interactor_style.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback)
     self.interactor_style.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
     self.interactor_style.AddObserver("MiddleButtonPressEvent", self.MiddleButtonPressCallback)
     self.interactor_style.AddObserver("RightButtonPressEvent", self.RightButtonPressCallback)
     self.interactor_style.AddObserver("RightButtonReleaseEvent", self.RightButtonReleaseCallback)
     self.interactor_style.AddObserver("KeyPressEvent", self.KeyPressCallback)
     self.interactor_style.AddObserver("CharEvent", self.CharCallback)
     
     self.updateAfter()
     self.render_window.Render()
  def display_and_query(self):

    # Convert images to VTK data structures
    fixedVTKImage = self.fixedCL.toVTKImage()
    movingVTKImage = self.movingCL.toVTKImage()

    # Viewing parameters
    fixedFrame = self.get_frame(self.fixedCL.clarray.get())
    movingFrame = self.get_frame(self.movingCL.clarray.get())

    N = self.panelSize

    fixedShape = self.fixedCL.shape

    XC = [0, 0, 0]
    for d in range(3):
      XC[d] = fixedShape[d] / 2.0

    #
    # Create panel of views for fixed and moving image, with likely optimal
    # orientations
    #
    fixedArray = np.zeros((N*3, N*3), np.single)
    movingArray = np.zeros((N*3, N*3), np.single)

    for r in range(3):
      for c in range(3):
        V = self.get_slicing_matrix(fixedFrame[:,r], movingFrame[:,c])

        A = np.zeros((4,4))
        A[0:3,0] = V[:,0]
        A[0:3,1] = V[:,1]
        A[0:3,2] = V[:,2]
        A[0,3] = XC[0]
        A[1,3] = XC[1]
        A[2,3] = XC[2]
        A[3,3] = 1.0

        resliceAxes = vtk.vtkMatrix4x4()
        resliceAxes.DeepCopy(A.ravel().tolist())

        reslicef = vtk.vtkImageReslice()
        reslicef.SetInput(fixedVTKImage)
        reslicef.SetInformationInput(fixedVTKImage)
        reslicef.SetOutputExtent(0, N-1, 0, N-1, 0, 0)
        reslicef.SetOutputDimensionality(2)
        reslicef.SetResliceAxes(resliceAxes)
        reslicef.SetInterpolationModeToLinear()
        reslicef.Update()

        fixedSlice = vtk.util.numpy_support.vtk_to_numpy(
          reslicef.GetOutput().GetPointData().GetScalars() ).reshape(N, N)
        fixedSlice = np.transpose(fixedSlice)

        fixedArray[r*N:(r+1)*N, c*N:(c+1)*N] = fixedSlice

        resliceAxes = vtk.vtkMatrix4x4()
        resliceAxes.DeepCopy(A.ravel().tolist())

        reslicef = vtk.vtkImageReslice()
        reslicef.SetInput(movingVTKImage)
        reslicef.SetInformationInput(movingVTKImage)
        reslicef.SetOutputExtent(0, N-1, 0, N-1, 0, 0)
        reslicef.SetOutputDimensionality(2)
        reslicef.SetResliceAxes(resliceAxes)
        reslicef.SetInterpolationModeToLinear()
        reslicef.Update()

        movingSlice = vtk.util.numpy_support.vtk_to_numpy(
          reslicef.GetOutput().GetPointData().GetScalars() ).reshape(N, N)
        movingSlice = np.transpose(movingSlice)

        movingArray[r*N:(r+1)*N, c*N:(c+1)*N] = movingSlice

    #
    # Display panel of views with blending slider
    #

    def normalize(arr):
      minv = arr.min()
      maxv = arr.max()
      rangev = maxv - minv
      if rangev <= 0.0:
        return arr
      return (arr - minv) / rangev

    fixedArray = normalize(fixedArray)
    movingArray = normalize(movingArray)

    ren = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    renWin.SetWindowName("Image Alignment Query")
    renWin.SetSize(800, 800)

    renWin.AddRenderer(ren)

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

    dataImporter = vtk.vtkImageImport()
    fixedArray_vtkorder = np.asfortranarray(fixedArray)
    fixedArray_vtkorder = fixedArray.transpose()
    ##dataImporter.CopyImportVoidPointer(fixedArray_vtkorder, fixedArray_vtkorder.nbytes)
    #dataImporter.CopyImportVoidPointer(fixedArray, fixedArray.nbytes)
    displayArray = np.uint8(fixedArray * 255)
    dataImporter.CopyImportVoidPointer(displayArray, displayArray.nbytes)
    #dataImporter.SetDataScalarTypeToFloat()
    dataImporter.SetDataScalarTypeToUnsignedChar()
    dataImporter.SetNumberOfScalarComponents(1)
    dataImporter.SetDataExtent(0, N*3-1, 0, N*3-1, 0, 0)
    dataImporter.SetWholeExtent(0, N*3-1, 0, N*3-1, 0, 0)
    dataImporter.Update()

    imageActor = vtk.vtkImageActor()
    imageActor.SetInput(dataImporter.GetOutput())
    imageActor.SetPosition(100.0, 100.0, 0.0)
    imageActor.SetZSlice(0)
    imageActor.PickableOn()

    imageStyle = vtk.vtkInteractorStyleImage()
    iren.SetInteractorStyle(imageStyle)

    ren.AddActor(imageActor)

    def slider_callback(obj, event):
      # Get slider value
      alpha = obj.GetRepresentation().GetValue()

      displayArray = fixedArray * alpha + movingArray * (1.0 - alpha)

      #minI = displayArray.min()
      #maxI = displayArray.max()
      #displayArray = (displayArray - minI) / (maxI - minI) * 255
      #displayArray = np.uint8(displayArray)
      #displayArray = np.uint8(normalize(displayArray) * 255)
      displayArray = np.uint8(displayArray * 255)

      dataImporter.CopyImportVoidPointer(displayArray, displayArray.nbytes)

    sliderRep  = vtk.vtkSliderRepresentation2D()
    sliderRep.SetMinimumValue(0.0)
    sliderRep.SetMaximumValue(1.0)
    sliderRep.SetValue(1.0)
    #sliderRep.SetTitleText("Fixed vs moving")
    sliderRep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    sliderRep.GetPoint1Coordinate().SetValue(0.2, 0.1)
    sliderRep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    sliderRep.GetPoint2Coordinate().SetValue(0.8, 0.1)

    sliderWidget = vtk.vtkSliderWidget()
    sliderWidget.SetInteractor(iren)
    sliderWidget.SetRepresentation(sliderRep)
    sliderWidget.AddObserver("InteractionEvent", slider_callback)
    sliderWidget.EnabledOn()

    #ren.InteractiveOff()
    renWin.AddRenderer(ren)

    picker = vtk.vtkPropPicker()
    #picker = vtk.vtkWorldPointPicker()
    picker.PickFromListOn()
    picker.AddPickList(imageActor)

    self.queryRowColumn = (0, 0)

    def pick_callback(obj, event):
      mousePos = obj.GetEventPosition()

      picker.PickProp(mousePos[0], mousePos[1], ren)

      p = picker.GetPickPosition()
      c = round( (p[0]-100) / (3*N) * 2 )
      r = round( (p[1]-100) / (3*N) * 2 )

      if r < 0 or r >= 3 or c < 0 or c >= 3:
        print "Outside"
        return

      print "Image row", r, "col", c

      self.queryRowColumn = (r, c)

      iren.GetRenderWindow().Finalize()
      iren.TerminateApp()

    iren.SetPicker(picker)
    iren.AddObserver("LeftButtonPressEvent", pick_callback)

    renWin.Render()
    iren.Start()

    # Return selection of a view in panel
    r, c = self.queryRowColumn

    fixedSlice = fixedArray[r*N:(r+1)*N, c*N:(c+1)*N]
    movingSlice = movingArray[r*N:(r+1)*N, c*N:(c+1)*N]

    return fixedSlice, movingSlice, fixedFrame[:,r], movingFrame[:,c]