Пример #1
0
    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 = vtkRenderer()
        self.renderer.SetLayer(0)

        cam = self.renderer.GetActiveCamera()

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

        style = 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)
Пример #2
0
    def SetInteractor(self, interactor):

        self.interactor = interactor
        self.render = interactor.GetRenderWindow().GetRenderers(
        ).GetFirstRenderer()

        istyle = 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 = vtkCellPicker()
Пример #3
0
    def __init__(self, *args, **kwargs):
        super(PyView2D, self).__init__(*args, **kwargs)
        self.block_signal = False
        self.reader = vtkDICOMImageReader()
        self.reader2 = vtkDICOMImageReader()
        self.window = self.GetRenderWindow()
        self.window.BordersOff(
        )  #attempt to remove imageactor borders, can remove
        self.center = [0, 0, 0]
        self.current_image = vtk.vtkImageData()
        self.viewer_id = "default"
        self.viewer_setup()  # flexible for future
        self.image_loaded = False
        self.viewer_initialized = False
        # self.read_image(image_path=None, orientation="axial")            # flexible for future

        self.window_level = vtkImageMapToWindowLevelColors()

        self.img = self.map_img()
        self.roi = self.map_roi()

        self.px_coord_text_prop = vtkTextProperty()
        self.px_coord_text_mapper = vtkTextMapper()
        self.px_coord_text_actor = vtkActor2D()
        self.world_coord_text_prop = vtkTextProperty()
        self.world_coord_text_mapper = vtkTextMapper()
        self.world_coord_text_actor = vtkActor2D()
        self.usage_text_prop = vtkTextProperty()
        self.usage_text_mapper = vtkTextMapper()
        self.usage_text_actor = vtkActor2D()

        self.renderer = vtkRenderer()  #
        self.add_text()
        self.renderer.AddActor(self.img)  #
        self.renderer.AddActor(self.roi)  #

        self.renderer.SetBackground(0.2, 0.3, 0.4)  #

        ### Wasil added ###
        #QVTKRenderWindowInteractor relays Qt events to VTK
        # self.frame = Qt.QFrame()    # do i need this
        # self.vtkWidget = QVTKRenderWindowInteractor(self.frame)

        # miu_viewer = PyView2D()
        # vtkWidget has its own RenderWindow
        # self.ren = vtk.vtkRenderer()
        # or
        # self.ren = miu_viewer.renderer # should have the actors already
        # self.vtkWidget.GetRenderWindow().AddRenderer(self.renderer)

        # self.vtkWidget.GetRenderWindow().SetSize(1000, 1000)

        # miu_viewer.window.Render()
        # or
        # self.vtkWidget.GetRenderWindow().Render()
        ##########################

        # have vtkRenderWindow
        # add VTKrenderer
        # self.window = vtkRenderWindow()
        self.window.AddRenderer(self.renderer)  #

        # self.window.SetSize(1000, 1000)
        self.window.SetSize(300, 300)

        self.interactor_style = vtkInteractorStyleImage()
        self.interactor_style.SetInteractionModeToImageSlicing()

        # self.interactor = vtkRenderWindowInteractor()   #
        # self.iren is the interactor (also from RenderWindow)
        self.interactor = self.GetRenderWindow().GetInteractor()
        self.interactor.SetInteractorStyle(self.interactor_style)  #
        self.window.SetInteractor(self.interactor)  #

        self.window_level.SetWindow(1000)
        self.window_level.SetLevel(200)
        self.window_level.Update()

        self.window.Render()

        ### moved this down to after image is loaded
        # self.interactor_style.AddObserver("MouseWheelForwardEvent", self.scroll_forward_callback)
        # self.interactor_style.AddObserver("MouseWheelBackwardEvent", self.scroll_backward_callback)
        # self.interactor_style.AddObserver("MouseMoveEvent", self.mouse_move_callback)
        # self.interactor_style.AddObserver("KeyPressEvent", self.key_press_callback)
        # self.interactor_style.AddObserver("LeftButtonPressEvent", self.left_press_callback)
        # self.window.AddObserver("ModifiedEvent", self.window_mod_callback)

        self.actions = {
            "Slicing": 0,
            "Cursor": 0,
            "CurrentPos": -1,
            "LastPos": -1,
            "DoubleClick": 0
        }
Пример #4
0
def main():
    VTK_DATA_ROOT = vtkGetDataRoot()
    folder = "/Users/nandana/Downloads/image_ex"

    #read dicom files from specified directory
    reader = vtkDICOMImageReader()
    reader.SetDirectoryName(folder)
    reader.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")

    reader.SetDataExtent(0, 63, 0, 63, 1, 93)
    reader.SetDataSpacing(3.2, 3.2, 1.5)
    reader.SetDataOrigin(-150.0, 150.0, 3.0)
    reader.SetDataScalarTypeToUnsignedShort()
    reader.UpdateWholeExtent()

    # Calculate the center of the volume
    reader.Update()

    (xMin, xMax, yMin, yMax, zMin,
     zMax) = reader.GetExecutive().GetWholeExtent(
         reader.GetOutputInformation(0))
    (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing()
    (x0, y0, z0) = reader.GetOutput().GetOrigin()

    center = [
        x0 + xSpacing * 0.5 * (xMin + xMax),
        y0 + ySpacing * 0.5 * (yMin + yMax),
        z0 + zSpacing * 0.5 * (zMin + zMax)
    ]
    yd = ((yMax - yMin) + 1) * ySpacing
    """
    # Matrices for axial, coronal, sagittal, oblique view orientations
    axial = vtkMatrix4x4()
    axial.DeepCopy((1, 0, 0, center[0],
                    0, 1, 0, center[1],
                    0, 0, 1, center[2],
                    0, 0, 0, 1))

    coronal = vtkMatrix4x4()
    coronal.DeepCopy((1, 0, 0, center[0],
                      0, 0, 1, center[1],
                      0,-1, 0, center[2],
                      0, 0, 0, 1))

    sagittal = vtkMatrix4x4
    sagittal.DeepCopy((0, 0,-1, center[0],
                       1, 0, 0, center[1],
                       0,-1, 0, center[2],
                       0, 0, 0, 1))

    oblique = 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))
    
    reslice = vtkImageReslice()
    outputPort = reader.GetOutputPort()
    #reslice.SetInputConnection(reader.GetOutputPort())
    reslice.SetInputConnection(0, reader.GetOutputPort())
    print(reader.GetOutput().GetExtent())
    reslice.SetOutputExtent(reader.GetOutput().GetExtent())
    reslice.SetOutputDimensionality(2)
    reslice.SetResliceAxes(coronal)
    reslice.SetInterpolationModeToLinear()
    
    """
    # Visualize
    imageViewer = vtkResliceImageViewer()
    imageViewer.SetSliceOrientationToXY()
    #imageViewer.SetSlice(9)

    imageViewer.SetResliceModeToAxisAligned()
    imageViewer.SliceScrollOnMouseWheelOff()
    imageViewer.SetInputData(reader.GetOutput())

    #imageViewer.Render()
    camera = imageViewer.GetRenderer().GetActiveCamera()

    print(camera.GetOrientationWXYZ())

    # slice status message
    sliceTextProp = vtkTextProperty()
    sliceTextProp.SetFontFamilyToCourier()
    sliceTextProp.SetFontSize(20)
    sliceTextProp.SetVerticalJustificationToBottom()
    sliceTextProp.SetJustificationToLeft()
    sliceTextMapper = vtkTextMapper()
    msg = "Slice {} out of {}".format(imageViewer.GetSlice() + 1, \
                                     imageViewer.GetSliceMax() + 1)
    sliceTextMapper.SetInput(msg)
    sliceTextMapper.SetTextProperty(sliceTextProp)

    sliceTextActor = vtkActor2D()
    sliceTextActor.SetMapper(sliceTextMapper)
    sliceTextActor.SetPosition(100, 10)

    # coordinate display
    coordTextProp = vtkTextProperty()
    coordTextProp.SetFontFamilyToCourier()
    coordTextProp.SetFontSize(20)
    coordTextProp.SetVerticalJustificationToBottom()
    coordTextProp.SetJustificationToLeft()

    coordTextMapper = vtkTextMapper()
    coordTextMapper.SetInput("Pixel Coordinates: (--, --)")
    coordTextMapper.SetTextProperty(coordTextProp)

    coordTextActor = vtkActor2D()
    coordTextActor.SetMapper(coordTextMapper)
    coordTextActor.SetPosition(500, 10)

    worldCoordTextProp = vtkTextProperty()
    worldCoordTextProp.SetFontFamilyToCourier()
    worldCoordTextProp.SetFontSize(20)
    worldCoordTextProp.SetVerticalJustificationToBottom()
    worldCoordTextProp.SetJustificationToLeft()

    worldCoordTextMapper = vtkTextMapper()
    worldCoordTextMapper.SetInput("World Coordinates: (--, --)")
    worldCoordTextMapper.SetTextProperty(worldCoordTextProp)

    worldCoordTextActor = vtkActor2D()
    worldCoordTextActor.SetMapper(worldCoordTextMapper)
    worldCoordTextActor.SetPosition(500, 30)

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

    usageTextMapper = vtkTextMapper()
    usageTextMapper.SetInput(
        "- Slice with mouse wheel\n- Zoom with pressed right\n  mouse button while dragging\n- Press i to toggle cursor line on/off"
    )
    usageTextMapper.SetTextProperty(usageTextProp)

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

    actor = imageViewer.GetImageActor()
    #image = vtkImageActor()
    #actor.GetMapper().SetInputData(reader.GetOutput())

    image = imageViewer.GetInput()

    roiData = vtkImageData()
    roiImage = vtkImageActor()

    roiData.DeepCopy(image)
    extent = roiData.GetExtent()

    for i in range(extent[0], extent[1]):
        for j in range(extent[2], extent[3]):
            for k in range(extent[4], extent[5]):
                if image.GetScalarComponentAsDouble(i, j, k, 0) > -100:
                    roiData.SetScalarComponentFromDouble(i, j, k, 0, 1)
                    #roiData.SetScalarComponentFromDouble(0, i, j, k, 1)

                else:  #just in case
                    roiData.SetScalarComponentFromDouble(i, j, k, 0, 0.0)
                    #roiData.SetScalarComponentFromDouble(0, i, j, k, 0.0)
    """            
    for i in range(extent[0], extent[1]):
        for j in range(extent[2], extent[3]):
            #for k in range(extent[4], extent[5]):
            #k = 0
            roiData.SetScalarComponentFromDouble(i, j, k, 0, 0.0)
            #roiData.SetScalarComponentFromDouble(0, i, j, k, 0.0)
    """

    print(extent)

    table = vtkLookupTable()
    table.SetNumberOfTableValues(2)
    table.SetRange(0.0, 1.0)
    table.SetTableValue(0, 0.0, 0.0, 0.0, 0.0)
    table.SetTableValue(1, 0.0, 1.0, 0.0, 1.0)
    table.Build()

    mapToColor = vtkImageMapToColors()
    mapToColor.SetLookupTable(table)
    mapToColor.PassAlphaToOutputOn()

    mapToColor.SetInputData(roiData)

    #actor.GetMapper().SetInputConnection(mapToColor.GetOutputPort())
    roiImage.GetMapper().SetInputConnection(mapToColor.GetOutputPort())

    imageViewer.SetInputData(image)

    interactorStyle = vtkInteractorStyleImage()
    interactor = vtkRenderWindowInteractor()

    imageViewer.SetupInteractor(interactor)
    interactor.SetInteractorStyle(interactorStyle)

    # add slice status message and usage hint message to the renderer
    imageViewer.GetRenderer().AddActor2D(coordTextActor)
    imageViewer.GetRenderer().AddActor2D(sliceTextActor)
    imageViewer.GetRenderer().AddActor2D(usageTextActor)
    imageViewer.GetRenderer().AddActor2D(worldCoordTextActor)

    imageViewer.GetRenderer().AddActor(roiImage)
    #imageViewer.GetRenderer().AddViewProp(stack)

    # initialize rendering and interaction

    #imageViewer.SetSlice(35)

    imageViewer.GetRenderWindow().SetSize(1000, 1000)
    imageViewer.GetRenderer().SetBackground(0.2, 0.3, 0.4)

    imageViewer.GetWindowLevel().SetWindow(1000)
    imageViewer.GetWindowLevel().SetLevel(-1000)

    imageViewer.Render()

    yd = (yMax - yMin + 1) * ySpacing
    xd = (xMax - xMin + 1) * xSpacing

    d = camera.GetDistance()
    camera.SetParallelScale(0.5 * xd)
    camera.SetFocalPoint(center[0], center[1], 0)
    camera.SetPosition(center[0], center[1], +d)

    actions = {}
    actions["Dolly"] = -1
    actions["Cursor"] = 0

    def middlePressCallback(obj, event):
        # if middle + ctrl pressed, zoom in/out
        # otherwise slice through image (handled by mouseMoveCallback)

        if (interactor.GetControlKey()):
            actions["Dolly"] = 0
            interactorStyle.OnRightButtonDown()
        else:
            actions["Dolly"] = 1

    def middleReleaseCallback(obj, event):
        if (actions["Dolly"] == 0):
            interactorStyle.OnRightButtonUp()
        elif (actions["Dolly"] == 1):
            actions["Dolly"] = 0

    def mouseMoveCallback(obj, event):
        # if the middle button is pressed + mouse is moved, slice through image
        # otherwise, update world/pixel coords as mouse is moved

        if (actions["Dolly"] == 1):
            (lastX, lastY) = interactor.GetLastEventPosition()
            (curX, curY) = interactor.GetEventPosition()
            deltaY = curY - lastY

            if (deltaY > 0):
                imageViewer.IncrementSlice(1)
            elif (deltaY < 0):
                imageViewer.IncrementSlice(-1)

            msg = "Slice {} out of {}".format(imageViewer.GetSlice() + 1, \
                                     imageViewer.GetSliceMax() + 1)
            sliceTextMapper.SetInput(msg)
            imageViewer.Render()

        else:

            (mouseX, mouseY) = interactor.GetEventPosition()
            bounds = actor.GetMapper().GetInput().GetBounds()

            testCoord = vtkCoordinate()
            testCoord.SetCoordinateSystemToDisplay()
            testCoord.SetValue(mouseX, mouseY, 0)

            (posX, posY,
             posZ) = testCoord.GetComputedWorldValue(imageViewer.GetRenderer())

            inBounds = True
            if posX < bounds[0] or posX > bounds[1] or posY < bounds[
                    2] or posY > bounds[3]:
                inBounds = False

            if inBounds:
                wMousePos = "World Coordinates: (" + "{:.2f}".format(
                    posX) + ", " + "{:.2f}".format(
                        posY) + ", " + "{:.2f}".format(posZ) + ")"
                pMousePos = "Pixel Coordinates: (" + "{:.2f}".format(
                    mouseX) + ", " + "{:.2f}".format(mouseY) + ")"
                worldCoordTextMapper.SetInput(wMousePos)
                coordTextMapper.SetInput(pMousePos)

                imageViewer.Render()

            interactorStyle.OnMouseMove()

    def scrollForwardCallback(obj, event):
        # slice through image on scroll, update slice text

        imageViewer.IncrementSlice(1)

        msg = "Slice {} out of {}".format(imageViewer.GetSlice() + 1, \
                                     imageViewer.GetSliceMax() + 1)
        sliceTextMapper.SetInput(msg)
        imageViewer.Render()

    def scrollBackwardCallback(obj, event):
        imageViewer.IncrementSlice(-1)

        msg = "Slice {} out of {}".format(imageViewer.GetSlice() + 1, \
                                     imageViewer.GetSliceMax() + 1)
        sliceTextMapper.SetInput(msg)
        imageViewer.Render()

    def windowModifiedCallback(obj, event):
        # track render window width so coordinate text aligns itself
        # to the right side of the screen

        width = imageViewer.GetRenderWindow().GetSize()[0]
        coordTextActor.SetPosition(width - 550, 10)
        worldCoordTextActor.SetPosition(width - 550, 30)

        imageViewer.Render()

    def keyPressCallback(obj, event):
        # toggle cursor on/off when t key is pressed

        key = interactor.GetKeySym()
        if (key == "t"):
            if (actions["Cursor"] == 0):
                imageViewer.GetRenderWindow().HideCursor()
                actions["Cursor"] = 1
            elif (actions["Cursor"] == 1):
                imageViewer.GetRenderWindow().ShowCursor()
                actions["Cursor"] = 0

    interactorStyle.AddObserver("MiddleButtonPressEvent", middlePressCallback)
    interactorStyle.AddObserver("MiddleButtonReleaseEvent",
                                middleReleaseCallback)
    interactorStyle.AddObserver("MouseMoveEvent", mouseMoveCallback)
    interactorStyle.AddObserver("MouseWheelForwardEvent",
                                scrollForwardCallback)
    interactorStyle.AddObserver("MouseWheelBackwardEvent",
                                scrollBackwardCallback)
    interactorStyle.AddObserver("KeyPressEvent", keyPressCallback)
    imageViewer.GetRenderWindow().AddObserver("ModifiedEvent",
                                              windowModifiedCallback)

    interactor.Start()
Пример #5
0
    def __init__(self, parent=None, dcm_dir='', view_plane='Transverse'):
        """
        建立DICOM VTK 畫布
        :param dcm_dir: 影像路徑
        :param view_plane: 切面:預設'Transverse',可選'Coronal','Sagittal'
        """
        QtWidgets.QMainWindow.__init__(self, parent)
        self.frame = QtWidgets.QFrame()
        self.vl = QtWidgets.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.vl.addWidget(self.vtkWidget)

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

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

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

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

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

        self.renderer.ResetCamera()
        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)
        self.show()
        self.inter.Initialize()
Пример #6
0
renderer = vtkRenderer()
renderer.AddActor(original)
renderer.AddActor(actor)
renderer.AddActor2D(coordTextActor)
renderer.AddActor2D(usageTextActor)
renderer.AddActor2D(worldCoordTextActor)

renderer.SetBackground(0.2, 0.3, 0.4)

window = vtkRenderWindow()
window.AddRenderer(renderer)
window.SetSize(1000, 1000)

# Set up the interaction
interactorStyle = vtkInteractorStyleImage()
interactorStyle.SetInteractionModeToImageSlicing()

interactor = vtkRenderWindowInteractor()
interactor.SetInteractorStyle(interactorStyle)
window.SetInteractor(interactor)

windowLevel.SetWindow(1000)
windowLevel.SetLevel(200)
windowLevel.Update()

window.Render()


# window size should be a "constant"
def load(img, roi, alpha, window_size, window_val, level_val, n_center):
Пример #7
0
    def __init__(self):
        VTK_DATA_ROOT = vtkGetDataRoot()
        self.reader = vtkDICOMImageReader()
        self.folder = "/Users/nandana/Downloads/image_ex"

        self.reader.SetDirectoryName(self.folder)
        self.reader.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
        self.reader.SetDataExtent(0, 63, 0, 63, 1, 93)
        self.reader.SetDataSpacing(3.2, 3.2, 1.5)
        self.reader.SetDataOrigin(0.0, 0.0, 0.0)
        self.reader.SetDataScalarTypeToUnsignedShort()
        self.reader.UpdateWholeExtent()
        self.reader.Update()

        self.center = self.calculate_center()

        self.axial = vtkMatrix4x4()
        self.axial.DeepCopy((1, 0, 0, self.center[0], 0, 1, 0, self.center[1],
                             0, 0, 1, self.center[2], 0, 0, 0, 1))

        self.coronal = vtkMatrix4x4()
        self.coronal.DeepCopy(
            (1, 0, 0, self.center[0], 0, 0, 1, self.center[1], 0, -1, 0,
             self.center[2], 0, 0, 0, 1))

        self.sagittal = vtkMatrix4x4()
        self.sagittal.DeepCopy(
            (0, 0, -1, self.center[0], 1, 0, 0, self.center[1], 0, -1, 0,
             self.center[2], 0, 0, 0, 1))

        self.oblique = vtkMatrix4x4()
        self.oblique.DeepCopy(
            (1, 0, 0, self.center[0], 0, 0.866025, -0.5, self.center[1], 0,
             0.5, 0.866025, self.center[2], 0, 0, 0, 1))

        self.img_reslice = vtkImageReslice()
        self.roi_reslice = vtkImageReslice()

        self.img_reslice.SetInputConnection(0, self.reader.GetOutputPort())
        self.img_reslice.SetOutputDimensionality(2)
        self.img_reslice.SetInterpolationModeToLinear()

        self.roi_reslice.SetInputConnection(0, self.reader.GetOutputPort())
        self.roi_reslice.SetOutputDimensionality(2)
        self.roi_reslice.SetInterpolationModeToLinear()

        self.set_orientation(self.axial)

        self.img_table = vtkLookupTable()
        self.roi_table = vtkLookupTable()
        self.window_level = vtkImageMapToWindowLevelColors()
        self.img_color = vtkImageMapToColors()
        self.roi_color = vtkImageMapToColors()

        self.img = self.map_img()
        self.roi = self.map_roi()

        self.px_coord_text_prop = vtkTextProperty()
        self.px_coord_text_mapper = vtkTextMapper()
        self.px_coord_text_actor = vtkActor2D()
        self.world_coord_text_prop = vtkTextProperty()
        self.world_coord_text_mapper = vtkTextMapper()
        self.world_coord_text_actor = vtkActor2D()
        self.usage_text_prop = vtkTextProperty()
        self.usage_text_mapper = vtkTextMapper()
        self.usage_text_actor = vtkActor2D()

        self.renderer = vtkRenderer()
        self.add_text()
        self.renderer.AddActor(self.img)
        self.renderer.AddActor(self.roi)

        self.renderer.SetBackground(0.2, 0.3, 0.4)

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

        self.window.SetSize(1000, 1000)

        self.interactor_style = vtkInteractorStyleImage()
        self.interactor_style.SetInteractionModeToImageSlicing()

        self.interactor = vtkRenderWindowInteractor()
        self.interactor.SetInteractorStyle(self.interactor_style)
        self.window.SetInteractor(self.interactor)

        self.window_level.SetWindow(1000)
        self.window_level.SetLevel(200)
        self.window_level.Update()

        self.window.Render()

        self.interactor_style.AddObserver("MouseWheelForwardEvent",
                                          self.scroll_forward_callback)
        self.interactor_style.AddObserver("MouseWheelBackwardEvent",
                                          self.scroll_backward_callback)
        self.interactor_style.AddObserver("MouseMoveEvent",
                                          self.mouse_move_callback)
        self.interactor_style.AddObserver("KeyPressEvent",
                                          self.key_press_callback)
        self.interactor_style.AddObserver("LeftButtonPressEvent",
                                          self.left_press_callback)
        self.window.AddObserver("ModifiedEvent", self.window_mod_callback)

        self.actions = {
            "Slicing": 0,
            "Cursor": 0,
            "CurrentPos": -1,
            "LastPos": -1,
            "DoubleClick": 0
        }
Пример #8
0
    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 = vtkRenderer()
        self.renderer.SetLayer(0)

        cam = self.renderer.GetActiveCamera()

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

        style = vtkInteractorStyleImage()

        self.interactor = wxVTKRenderWindowInteractor(self.panel, -1,
                                                      size=wx.Size(340,340))
        self.interactor.SetRenderWhenDisabled(True)
        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)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.interactor, 1, wx.GROW|wx.EXPAND)
        sizer.Fit(self.panel)
        self.panel.SetSizer(sizer)
        self.Layout()
        self.Update()