Example #1
0
    def __init__(self):

        self.interactor = None
        self.image_original = None
        self.image_threshold = None
        self.render = None

        self.lut = vtkLookupTable()
        self.lut_original = vtkLookupTable()
        self.image_color = vtkImageMapToColors()
        self.blend = blend = vtkImageBlend()
        self.map = map = vtkImageMapper()

        self.actor = actor = vtkImageActor()
        self.actor2 = actor2 = vtkImageActor()
        self.actor3 = actor3 = vtkImageActor()

        self.image_color_o = vtkImageMapToColors()

        self.operation_type = 0
        self.w = None

        self.slice = 0
        self.clicked = 0
        self.orientation = AXIAL

        self.w = (200, 1200)
    def ShowSlice(self, index = 0):
        bitmap = self.bitmap_list[index]

        # UPDATE GUI
        ## Text related to size
        value = STR_SIZE %(bitmap[3], bitmap[4])
        self.text_image_size.SetValue(value)

        value1 = ''
        value2 = ''

        value = "%s\n%s" %(value1, value2)
        self.text_image_location.SetValue(value)


        #self.text_patient.SetValue(value)
        self.text_patient.SetValue('')

        #self.text_acquisition.SetValue(value)
        self.text_acquisition.SetValue('')



        n_array = bitmap_reader.ReadBitmap(bitmap[0])
        
        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")


        # ADJUST CONTRAST
        window_level = n_array.max()/2
        window_width = n_array.max()
        
        colorer = vtkImageMapToWindowLevelColors()
        colorer.SetInputData(image)
        colorer.SetWindow(float(window_width))
        colorer.SetLevel(float(window_level))
        colorer.Update()

        if self.actor is None:
            self.actor = vtkImageActor()
            self.renderer.AddActor(self.actor)

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(colorer.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(index)
Example #3
0
    def map_img(self, ):  # greyscale lookup table
        self.img_table = vtkLookupTable()
        self.img_color = vtkImageMapToColors()
        self.img_table.SetRange(0, 2000)  # image intensity range
        self.img_table.SetValueRange(0.0, 1.0)  # from black to white
        self.img_table.SetSaturationRange(0.0, 0.0)  # no color saturation
        self.img_table.SetRampToSQRT()
        self.img_table.Build()

        self.connect_window_level()

        img_actor = vtkImageActor()
        img_actor.GetMapper().SetInputConnection(
            self.img_color.GetOutputPort())
        return img_actor
Example #4
0
    def map_roi(self):  # colored lookup table
        self.roi_table.SetNumberOfTableValues(2)
        self.roi_table.SetRange(0.0, 1.0)
        self.roi_table.SetTableValue(0, 0.0, 0.0, 0.0, 0.0)
        self.roi_table.SetTableValue(1, 0.0, 1.0, 0.0,
                                     1.0)  # value, r, g, b, a
        self.roi_table.Build()

        self.roi_color.SetLookupTable(self.roi_table)
        self.roi_color.SetInputConnection(self.roi_reslice.GetOutputPort())

        roi_actor = vtkImageActor()
        roi_actor.GetMapper().SetInputConnection(
            self.roi_color.GetOutputPort())

        return roi_actor
Example #5
0
 def __init__(self):
     self.colour = (0.0, 0.0, 1.0)
     self.opacity = 1
     self.size = 15.0
     self.orientation = "AXIAL"
     self.spacing = (1, 1, 1)
     self.position = (0, 0, 0)
     if vtkVersion().GetVTKVersion() > '5.8.0':
         self.mapper = vtkImageSliceMapper()
         cursor_property = vtkImageProperty()
         cursor_property.SetInterpolationTypeToNearest()
         self.actor = vtkImageSlice()
         self.actor.SetMapper(self.mapper)
         self.actor.SetProperty(cursor_property)
     else:
         self.actor = vtkImageActor()
         self.mapper = None
     self._build_actor()
     self._calculate_area_pixels()
    def ShowBlackSlice(self, pub_sub):
        n_array = numpy.zeros((100,100))
       
        self.text_image_size.SetValue('')

        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")

        colorer = vtkImageMapToWindowLevelColors()
        colorer.SetInputData(image)
        colorer.Update()

        if self.actor is None:
            self.actor = vtkImageActor()
            self.renderer.AddActor(self.actor)

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(colorer.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(0)
Example #7
0
    def ShowSlice(self, index=0):
        try:
            dicom = self.dicom_list[index]
        except IndexError:
            dicom = self.dicom_list[0]

        if self.actor is None:
            self.__init_vtk()

        # UPDATE GUI
        ## Text related to size
        value = STR_SIZE % (dicom.image.size[0], dicom.image.size[1])
        self.text_image_size.SetValue(value)

        ## Text related to slice position
        if not (dicom.image.spacing):
            value1 = ''
        else:
            value1 = STR_SPC % (dicom.image.spacing[2])

        if dicom.image.orientation_label == 'AXIAL':
            value2 = STR_LOCAL % (dicom.image.position[2])
        elif dicom.image.orientation_label == 'CORONAL':
            value2 = STR_LOCAL % (dicom.image.position[1])
        elif dicom.image.orientation_label == 'SAGITTAL':
            value2 = STR_LOCAL % (dicom.image.position[0])
        else:
            value2 = ''

        value = "%s\n%s" % (value1, value2)
        self.text_image_location.SetValue(value)

        ## Text related to patient/ acquisiiton data
        value = STR_PATIENT %(dicom.patient.id,\
                              dicom.acquisition.protocol_name)
        self.text_patient.SetValue(value)

        ## Text related to acquisition date and time
        value = STR_ACQ % (dicom.acquisition.date, dicom.acquisition.time)
        self.text_acquisition.SetValue(value)

        if isinstance(dicom.image.thumbnail_path, list):
            reader = vtkPNGReader()
            if _has_win32api:
                reader.SetFileName(
                    win32api.GetShortPathName(
                        dicom.image.thumbnail_path[index]).encode(
                            const.FS_ENCODE))
            else:
                reader.SetFileName(dicom.image.thumbnail_path[index])
            reader.Update()

            image = reader.GetOutput()
        else:
            filename = dicom.image.file
            if _has_win32api:
                filename = win32api.GetShortPathName(filename).encode(
                    const.FS_ENCODE)

            np_image = imagedata_utils.read_dcm_slice_as_np2(filename)
            vtk_image = converters.to_vtk(np_image, dicom.image.spacing, 0,
                                          'AXIAL')

            # ADJUST CONTRAST
            window_level = dicom.image.level
            window_width = dicom.image.window
            colorer = vtkImageMapToWindowLevelColors()
            colorer.SetInputData(vtk_image)
            colorer.SetWindow(float(window_width))
            colorer.SetLevel(float(window_level))
            colorer.Update()

            image = colorer.GetOutput()

        flip = vtkImageFlip()
        flip.SetInputData(image)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        flip.ReleaseDataFlagOn()
        flip.Update()

        if self.actor is None:
            self.actor = vtkImageActor()
            self.renderer.AddActor(self.actor)

        self.canvas.modified = True

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(flip.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(index)
Example #8
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()
Example #9
0
# Map the image through the lookup table
print("mapping colors...")

windowLevel = vtkImageMapToWindowLevelColors()
windowLevel.SetInputConnection(reslice2.GetOutputPort())

color = vtkImageMapToColors()
color.SetLookupTable(table)
color.SetInputConnection(reslice.GetOutputPort())

color2 = vtkImageMapToColors()
color2.SetLookupTable(table2)
color2.SetInputConnection(windowLevel.GetOutputPort())

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

original = vtkImageActor()
original.GetMapper().SetInputConnection(color2.GetOutputPort())

print(actor.GetInput().GetExtent())

# ADD TEXT PROPS
coordTextProp = vtkTextProperty()
coordTextProp.SetFontFamilyToCourier()
coordTextProp.SetFontSize(20)
coordTextProp.SetVerticalJustificationToBottom()
coordTextProp.SetJustificationToLeft()

coordTextMapper = vtkTextMapper()