def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.reader = vtk.vtkDICOMImageReader()

        #self.viewerL = vtk.vtkImageViewer2()
        #self.viewerR = vtk.vtkImageViewer2()

        self.renL = vtk.vtkRenderer()
        self.ui.leftVtk.GetRenderWindow().AddRenderer(self.renL)
        self.renR = vtk.vtkRenderer()
        self.ui.rightVtk.GetRenderWindow().AddRenderer(self.renR)

        self.mapperL = vtk.vtkImageMapper()
        self.mapperL.SetInputConnection(self.reader.GetOutputPort())
        self.mapperR = vtk.vtkImageMapper()

        self.actorL = vtk.vtkActor2D()
        self.actorL.SetMapper(self.mapperL)
        self.actorR = vtk.vtkActor2D()
        self.actorR.SetMapper(self.mapperR)

        self.renL.AddActor2D(self.actorL)
        self.renR.AddActor2D(self.actorR)

        self.importer = vtk.vtkImageImport()
        self.mapperR.SetInputConnection(self.importer.GetOutputPort())

        self.loadImage(os.path.join(STARTINGPATH, FILENAME))
        self.setWindowingAlg()
    def __init__(self):
        self.lookupTable = vtk.vtkLookupTable()
        self.lookupTable.SetRampToLinear()
        self.lookupTable.SetNumberOfTableValues(2)
        self.lookupTable.SetTableRange(0, 1)
        self.lookupTable.SetTableValue(0, 0, 0, 0, 0)
        self.colorMapper = vtk.vtkImageMapToRGBA()
        self.colorMapper.SetOutputFormatToRGBA()
        self.colorMapper.SetLookupTable(self.lookupTable)
        self.thresholdFilter = vtk.vtkImageThreshold()
        self.thresholdFilter.SetInValue(1)
        self.thresholdFilter.SetOutValue(0)
        self.thresholdFilter.SetOutputScalarTypeToUnsignedChar()

        # Feedback actor
        self.mapper = vtk.vtkImageMapper()
        self.dummyImage = vtk.vtkImageData()
        self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
        self.mapper.SetInputData(self.dummyImage)
        self.actor = vtk.vtkActor2D()
        self.actor.VisibilityOff()
        self.actor.SetMapper(self.mapper)
        self.mapper.SetColorWindow(255)
        self.mapper.SetColorLevel(128)

        # Setup pipeline
        self.colorMapper.SetInputConnection(
            self.thresholdFilter.GetOutputPort())
        self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())
    def __init__(self, sliceWidget):
        super(ThresholdEffectTool, self).__init__(sliceWidget)

        # create a logic instance to do the non-gui work
        self.logic = ThresholdEffectLogic(self.sliceWidget.sliceLogic())
        self.logic.undoRedo = self.undoRedo

        # interaction state variables
        self.min = 0
        self.max = 0

        # class instances
        self.lut = None
        self.thresh = None
        self.map = None

        # feedback actor
        self.cursorMapper = vtk.vtkImageMapper()
        self.cursorDummyImage = vtk.vtkImageData()
        self.cursorDummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
        self.cursorMapper.SetInputData(self.cursorDummyImage)
        self.cursorActor = vtk.vtkActor2D()
        self.cursorActor.VisibilityOff()
        self.cursorActor.SetMapper(self.cursorMapper)
        self.cursorMapper.SetColorWindow(255)
        self.cursorMapper.SetColorLevel(128)

        self.actors.append(self.cursorActor)

        self.renderer.AddActor2D(self.cursorActor)
Exemple #4
0
    def __init__(self):
        
        self.interactor = None
        self.image_original = None
        self.image_threshold = None
        self.render = None
    
        self.lut = vtk.vtkLookupTable()
        self.lut_original = vtk.vtkLookupTable()
        self.image_color = vtk.vtkImageMapToColors()
        self.blend = blend = vtk.vtkImageBlend()
        self.map = map = vtk.vtkImageMapper()
        
        self.actor = actor = vtk.vtkImageActor()
        self.actor2 = actor2 = vtk.vtkImageActor()
        self.actor3 = actor3 = vtk.vtkImageActor()
        
        self.image_color_o = vtk.vtkImageMapToColors()
        
        self.operation_type = 0
        self.w = None
   
        self.slice = 0
        self.clicked = 0
        self.orientation = AXIAL

        self.w = (200, 1200)
    def _init_canvas(self):
        w, h = self._size
        self._array = np.zeros((h, w, 4), dtype=np.uint8)

        self._cv_image = converters.np_rgba_to_vtk(self._array)

        self.mapper = vtk.vtkImageMapper()
        self.mapper.SetInputData(self._cv_image)
        self.mapper.SetColorWindow(255)
        self.mapper.SetColorLevel(128)

        self.actor = vtk.vtkActor2D()
        self.actor.SetPosition(0, 0)
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetOpacity(0.99)

        self.canvas_renderer.AddActor2D(self.actor)

        self.rgb = np.zeros((h, w, 3), dtype=np.uint8)
        self.alpha = np.zeros((h, w, 1), dtype=np.uint8)

        self.bitmap = wx.EmptyBitmapRGBA(w, h)
        try:
            self.image = wx.Image(w, h, self.rgb, self.alpha)
        except TypeError:
            self.image = wx.ImageFromBuffer(w, h, self.rgb, self.alpha)
Exemple #6
0
  def __init__(self, sliceWidget):
    super(ThresholdEffectTool,self).__init__(sliceWidget)

    # create a logic instance to do the non-gui work
    self.logic = ThresholdEffectLogic(self.sliceWidget.sliceLogic())
    self.logic.undoRedo = self.undoRedo

    # interaction state variables
    self.min = 0
    self.max = 0

    # class instances
    self.lut = None
    self.thresh = None
    self.map = None

    # feedback actor
    self.cursorMapper = vtk.vtkImageMapper()
    self.cursorDummyImage = vtk.vtkImageData()
    self.cursorDummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
    self.cursorMapper.SetInputData( self.cursorDummyImage )
    self.cursorActor = vtk.vtkActor2D()
    self.cursorActor.VisibilityOff()
    self.cursorActor.SetMapper( self.cursorMapper )
    self.cursorMapper.SetColorWindow( 255 )
    self.cursorMapper.SetColorLevel( 128 )

    self.actors.append( self.cursorActor )

    self.renderer.AddActor2D( self.cursorActor )
Exemple #7
0
    def __init__(self):
        
        self.interactor = None
        self.image_original = None
        self.image_threshold = None
        self.render = None
    
        self.lut = vtk.vtkLookupTable()
        self.lut_original = vtk.vtkLookupTable()
        self.image_color = vtk.vtkImageMapToColors()
        self.blend = blend = vtk.vtkImageBlend()
        self.map = map = vtk.vtkImageMapper()
        
        self.actor = actor = vtk.vtkImageActor()
        self.actor2 = actor2 = vtk.vtkImageActor()
        self.actor3 = actor3 = vtk.vtkImageActor()
        
        self.image_color_o = vtk.vtkImageMapToColors()
        
        self.operation_type = 0
        self.w = None
   
        self.slice = 0
        self.clicked = 0
        self.orientation = AXIAL

        self.w = (200, 1200)
Exemple #8
0
    def _init_canvas(self):
        w, h = self._size
        self._array = np.zeros((h, w, 4), dtype=np.uint8)

        self._cv_image = converters.np_rgba_to_vtk(self._array)

        self.mapper = vtk.vtkImageMapper()
        self.mapper.SetInputData(self._cv_image)
        self.mapper.SetColorWindow(255)
        self.mapper.SetColorLevel(128)

        self.actor = vtk.vtkActor2D()
        self.actor.SetPosition(0, 0)
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetOpacity(0.99)

        self.canvas_renderer.AddActor2D(self.actor)

        self.rgb = np.zeros((h, w, 3), dtype=np.uint8)
        self.alpha = np.zeros((h, w, 1), dtype=np.uint8)

        self.bitmap = wx.EmptyBitmapRGBA(w, h)
        try:
            self.image = wx.Image(w, h, self.rgb, self.alpha)
        except TypeError:
            self.image = wx.ImageFromBuffer(w, h, self.rgb, self.alpha)
  def __init__(self):
    self.lookupTable = vtk.vtkLookupTable()
    self.lookupTable.SetRampToLinear()
    self.lookupTable.SetNumberOfTableValues(2)
    self.lookupTable.SetTableRange(0, 1)
    self.lookupTable.SetTableValue(0,  0, 0, 0,  0)
    self.colorMapper = vtk.vtkImageMapToRGBA()
    self.colorMapper.SetOutputFormatToRGBA()
    self.colorMapper.SetLookupTable(self.lookupTable)
    self.thresholdFilter = vtk.vtkImageThreshold()
    self.thresholdFilter.SetInValue(1)
    self.thresholdFilter.SetOutValue(0)
    self.thresholdFilter.SetOutputScalarTypeToUnsignedChar()

    # Feedback actor
    self.mapper = vtk.vtkImageMapper()
    self.dummyImage = vtk.vtkImageData()
    self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
    self.mapper.SetInputData(self.dummyImage)
    self.actor = vtk.vtkActor2D()
    self.actor.VisibilityOff()
    self.actor.SetMapper(self.mapper)
    self.mapper.SetColorWindow(255)
    self.mapper.SetColorLevel(128)

    # Setup pipeline
    self.colorMapper.SetInputConnection(self.thresholdFilter.GetOutputPort())
    self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())
    def get2DMapper(self, data, **kwargs):

        # Set up mapper according to input arguments
        mapper = vtk.vtkImageMapper()
        mapper.SetInputData(data.GetOutput())

        if 'zslice' in kwargs:
            mapper.SetZSlice(kwargs['zslice'])
        if 'window' in kwargs:
            mapper.SetColorWindow(kwargs['window'])
        if 'level' in kwargs:
            mapper.SetColorLevel(kwargs['level'])

        return mapper
 def add_image(self, image):
     img_mapper = vtk.vtkImageMapper()
     img_actor = vtk.vtkActor2D()
     img_data = vtk.vtkImageData()
     img_data.SetDimensions(image.shape[0], image.shape[1], 1)
     img_data.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 3)
     for x in range(0, image.shape[0]):
         for y in range(0, image.shape[1]):
             pixel = img_data.GetScalarPointer(x, y, 0)
             pixel = np.array(image[x, y, :])
     img_mapper.SetInputData(img_data)
     img_mapper.SetColorWindow(255)
     img_mapper.SetColorLevel(127.5)
     img_actor.SetMapper(img_mapper)
     self.renderer.AddActor(img_actor)
Exemple #12
0
    def __init__(self,
                 parent=None,
                 width=400,
                 height=400,
                 showWidget=False,
                 scale=False):
        super(LayerReveal, self).__init__()
        self.width = width
        self.height = height
        self.showWidget = showWidget
        self.scale = scale
        self.renderer = None

        # utility Qt instances for use in methods
        self.gray = qt.QColor()
        self.gray.setRedF(0.5)
        self.gray.setGreenF(0.5)
        self.gray.setBlueF(0.5)
        # a painter to use for various jobs
        self.painter = qt.QPainter()

        # make a qwidget display
        if self.showWidget:
            self.frame = qt.QFrame(parent)
            mw = slicer.util.mainWindow()
            self.frame.setGeometry(mw.x, mw.y, self.width, self.height)
            self.frameLayout = qt.QVBoxLayout(self.frame)
            self.label = qt.QLabel()
            self.frameLayout.addWidget(self.label)
            self.frame.show()

        # make an image actor in the slice view
        self.vtkImage = vtk.vtkImageData()

        self.mrmlUtils = slicer.qMRMLUtils()
        self.imageMapper = vtk.vtkImageMapper()
        self.imageMapper.SetColorLevel(128)
        self.imageMapper.SetColorWindow(255)
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.imageMapper.SetInput(self.vtkImage)
        else:
            self.imageMapper.SetInputData(self.vtkImage)
        self.actor2D = vtk.vtkActor2D()
        self.actor2D.SetMapper(self.imageMapper)
Exemple #13
0
def render(im, dim):

    #Definition for lookup table required for mapper
    ul = 127
    ll = 0
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfColors(256)
    lut.SetTableRange(ll, ul)

    colorMap = vtk.vtkImageMapToColors()
    colorMap.SetInput(im)
    colorMap.SetLookupTable(lut)

    mapper = vtk.vtkImageMapper()
    mapper.SetInput(colorMap.GetOutput())
    mapper.SetColorWindow(ul - ll)
    mapper.SetColorLevel((ul - ll) / 2)

    actor = vtk.vtkActor2D()
    actor.SetMapper(mapper)

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    #ren.SetBackground(.8,.8,.8)

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(800, 800)
    renWin.SetWindowName("Bone Imaging Laboratory")
    renWin.SetSize(dim.GetDimension()[0], dim.GetDimension()[1])
    renWin.SetPosition(50, 50)

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

    for i in range(dim.GetDimension()[2]):
        mapper.SetZSlice(i)
        renWin.Render()

    iren.Initialize()
    renWin.Render()
    iren.Start()
Exemple #14
0
def ImageActor(img):
    reader = vtkImageImportFromArray()
    reader.SetArray(img)

    ImageDataGeometryFilter = vtk.vtkImageDataGeometryFilter()
    ImageDataGeometryFilter.SetInputConnection(reader.GetOutputPort())
    ImageDataGeometryFilter.Update()

    # textureCoordinates = vtk.vtkFloatArray()
    # textureCoordinates.SetNumberOfComponents(2)
    # textureCoordinates.InsertNextTuple2(0.0, 1.0)
    # textureCoordinates.InsertNextTuple2(1.0, 1.0)
    # textureCoordinates.InsertNextTuple2(1.0, 0.0)
    # textureCoordinates.InsertNextTuple2(0.0, 0.0)

    mag = vtk.vtkImageMagnify()
    mag.SetMagnificationFactors(512, 512, 1)
    mag.InterpolateOff()
    mag.SetInputConnection(reader.GetOutputPort())

    mapper = vtk.vtkImageMapper()
    # mapper.SetInputConnection(reader.GetOutputPort())
    # mapper.SetColorWindow(4)
    # mapper.SetColorLevel(255)
    # mapper.SetZSlice(0)
    mapper.SetInputConnection(mag.GetOutputPort())
    # mapper.SetColorlevel(1000)

    viewer = vtk.vtkImageViewer()
    viewer.SetInputConnection(reader.GetOutputPort())
    viewer.SetColorWindow(4)
    viewer.SetColorLevel(255)
    # viewer.SetZSlice(0)
    viewer.Render()

    actor = vtk.vtkActor2D()
    actor.SetMapper(mapper.GetOutputPort())
    # actor=vtk.vtkImageActor()
    # actor.SetMapper(mapper)
    # actor.SetInputData(reader.GetOutput())

    return actor, viewer
  def __init__(self,parent=None,width=400,height=400,showWidget=False,scale=False):
    super(LayerReveal,self).__init__()
    self.width = width
    self.height = height
    self.showWidget = showWidget
    self.scale = scale
    self.renderer = None

    # utility Qt instances for use in methods
    self.gray = qt.QColor()
    self.gray.setRedF(0.5)
    self.gray.setGreenF(0.5)
    self.gray.setBlueF(0.5)
    # a painter to use for various jobs
    self.painter = qt.QPainter()


    # make a qwidget display
    if self.showWidget:
      self.frame = qt.QFrame(parent)
      mw = slicer.util.mainWindow()
      self.frame.setGeometry(mw.x, mw.y, self.width, self.height)
      self.frameLayout = qt.QVBoxLayout(self.frame)
      self.label = qt.QLabel()
      self.frameLayout.addWidget(self.label)
      self.frame.show()

    # make an image actor in the slice view
    self.vtkImage = vtk.vtkImageData()

    self.mrmlUtils = slicer.qMRMLUtils()
    self.imageMapper = vtk.vtkImageMapper()
    self.imageMapper.SetColorLevel(128)
    self.imageMapper.SetColorWindow(255)
    if vtk.VTK_MAJOR_VERSION <= 5:
      self.imageMapper.SetInput(self.vtkImage)
    else:
      self.imageMapper.SetInputData(self.vtkImage)
    self.actor2D = vtk.vtkActor2D()
    self.actor2D.SetMapper(self.imageMapper)
Exemple #16
0
    def testWipe(self):

        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        image1 = vtk.vtkImageCanvasSource2D()
        image1.SetNumberOfScalarComponents(3)
        image1.SetScalarTypeToUnsignedChar()
        image1.SetExtent(0, 79, 0, 79, 0, 0)
        image1.SetDrawColor(255, 255, 0)
        image1.FillBox(0, 79, 0, 79)
        image1.Update()

        image2 = vtk.vtkImageCanvasSource2D()
        image2.SetNumberOfScalarComponents(3)
        image2.SetScalarTypeToUnsignedChar()
        image2.SetExtent(0, 79, 0, 79, 0, 0)
        image2.SetDrawColor(0, 255, 255)
        image2.FillBox(0, 79, 0, 79)
        image2.Update()

        mapper = vtk.vtkImageMapper()
        mapper.SetInputConnection(image1.GetOutputPort())
        mapper.SetColorWindow(255)
        mapper.SetColorLevel(127.5)
        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        imager = vtk.vtkRenderer()
        imager.AddActor2D(actor)

        renWin.AddRenderer(imager)

        wipes = ["Quad", "Horizontal", "Vertical", "LowerLeft", "LowerRight", "UpperLeft", "UpperRight"]

        wiper = dict()
        mapper = dict()
        actor = dict()
        imagers = dict()

        for wipe in wipes:
            wiper.update({wipe:vtk.vtkImageRectilinearWipe()})
            wiper[wipe].SetInput1Data(image1.GetOutput())
            wiper[wipe].SetInput2Data(image2.GetOutput())
            wiper[wipe].SetPosition(20, 20)
            eval('wiper[wipe].SetWipeTo' + wipe + '()')

            mapper.update({wipe:vtk.vtkImageMapper()})
            mapper[wipe].SetInputConnection(wiper[wipe].GetOutputPort())
            mapper[wipe].SetColorWindow(255)
            mapper[wipe].SetColorLevel(127.5)

            actor.update({wipe:vtk.vtkActor2D()})
            actor[wipe].SetMapper(mapper[wipe])

            imagers.update({wipe:vtk.vtkRenderer()})
            imagers[wipe].AddActor2D(actor[wipe])

            renWin.AddRenderer(imagers[wipe])

        imagers["Quad"].SetViewport(0, .5, .25, 1)
        imagers["Horizontal"].SetViewport(.25, .5, .5, 1)
        imagers["Vertical"].SetViewport(.5, .5, .75, 1)
        imagers["LowerLeft"].SetViewport(.75, .5, 1, 1)
        imagers["LowerRight"].SetViewport(0, 0, .25, .5)
        imagers["UpperLeft"].SetViewport(.25, 0, .5, .5)
        imagers["UpperRight"].SetViewport(.5, 0, .75, .5)
        imager.SetViewport(.75, 0, 1, .5)

        renWin.SetSize(400, 200)

        # render and interact with data

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

        img_file = "TestWipe.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
    def testAllMathematics(self):

        # append multiple displaced spheres into an RGB image.


        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        sphere1 = vtk.vtkImageEllipsoidSource()
        sphere1.SetCenter(40, 20, 0)
        sphere1.SetRadius(30, 30, 0)
        sphere1.SetInValue(.75)
        sphere1.SetOutValue(.3)
        sphere1.SetOutputScalarTypeToFloat()
        sphere1.SetWholeExtent(0, 99, 0, 74, 0, 0)
        sphere1.Update()

        sphere2 = vtk.vtkImageEllipsoidSource()
        sphere2.SetCenter(60, 30, 0)
        sphere2.SetRadius(20, 20, 20)
        sphere2.SetInValue(.2)
        sphere2.SetOutValue(.5)
        sphere2.SetOutputScalarTypeToFloat()
        sphere2.SetWholeExtent(0, 99, 0, 74, 0, 0)
        sphere2.Update()

        mathematics = [ "Add", "Subtract", "Multiply", "Divide", "Invert", "Sin", "Cos",
                        "Exp", "Log", "AbsoluteValue", "Square", "SquareRoot", "Min",
                        "Max", "ATAN", "ATAN2", "MultiplyByK", "ReplaceCByK", "AddConstant"]

        mathematic = list()
        mapper = list()
        actor = list()
        imager = list()

        for idx, operator in enumerate(mathematics):
            mathematic.append(vtk.vtkImageMathematics())
            mathematic[idx].SetInput1Data(sphere1.GetOutput())
            mathematic[idx].SetInput2Data(sphere2.GetOutput())
            eval('mathematic[idx].SetOperationTo' + operator + '()')
            mathematic[idx].SetConstantK(.3)
            mathematic[idx].SetConstantC(.75)
            mapper.append(vtk.vtkImageMapper())
            mapper[idx].SetInputConnection(mathematic[idx].GetOutputPort())
            mapper[idx].SetColorWindow(2.0)
            mapper[idx].SetColorLevel(.75)
            actor.append(vtk.vtkActor2D())
            actor[idx].SetMapper(mapper[idx])
            imager.append(vtk.vtkRenderer())
            imager[idx].AddActor2D(actor[idx])
            renWin.AddRenderer(imager[idx])

        column = 1
        row = 1
        deltaX = 1.0 / 6.0
        deltaY = 1.0 / 4.0

        for idx, operator in enumerate(mathematics):
            imager[idx].SetViewport((column - 1) * deltaX, (row - 1) * deltaY, column * deltaX, row * deltaY)
            column += 1
            if column > 6:
                column = 1
                row += 1

        # Make the last operator finish the row
        vp = imager[len(mathematics) - 1].GetViewport()
        imager[len(mathematics) - 1].SetViewport(vp[0], vp[1], 1, 1)

        renWin.SetSize(600, 300)

        # render and interact with data

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

        img_file = "TestAllMathematics.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #18
0
def Navigate2D():
    print(
        "---------------------------Navigating 2D---------------------------")
    print("Please, choose the navigation axis")
    print("1 Axial")
    print("2 Coronal")
    print("3 Sagittal")
    optionUser = input("?: ")
    print("Use up and down arrows to navigate")

    global orientation
    global zSlice
    zSlice = 0

    if (optionUser == "1"):
        orientation = "axial"
    if (optionUser == "2"):
        orientation = "coronal"
    if (optionUser == "3"):
        orientation = "sagittal"

    imageNavigate2D = orientImage(dicomImage, orientation)

    global mapperNavigate2D
    mapperNavigate2D = vtk.vtkImageMapper()
    mapperNavigate2D.SetInputData(imageNavigate2D)
    mapperNavigate2D.SetZSlice(zSlice)
    # window and level have to be adjusted for better visualization
    mapperNavigate2D.SetColorWindow(1000)
    mapperNavigate2D.SetColorLevel(0)

    actorNavigate2D = vtk.vtkActor2D()
    actorNavigate2D.SetMapper(mapperNavigate2D)

    global renderWindowNavigate2D
    rendererNavigate2D = vtk.vtkRenderer()
    rendererNavigate2D.AddActor(actorNavigate2D)

    renderWindowNavigate2D = vtk.vtkRenderWindow()
    renderWindowNavigate2D.AddRenderer(rendererNavigate2D)

    if (orientation == "axial"):
        renderWindowNavigate2D.SetSize(dicomImage.GetDimensions()[0],
                                       dicomImage.GetDimensions()[1])
    if (orientation == "coronal"):
        renderWindowNavigate2D.SetSize(dicomImage.GetDimensions()[0],
                                       dicomImage.GetDimensions()[2])
    if (orientation == "sagittal"):
        renderWindowNavigate2D.SetSize(dicomImage.GetDimensions()[1],
                                       dicomImage.GetDimensions()[2])

    windowInteractorN2D = vtk.vtkRenderWindowInteractor()
    windowInteractorN2D.SetRenderWindow(renderWindowNavigate2D)

    #Note here how the event is added to the observer. The name of the event is fixed, the name
    #of the function that handles the event is user defined.
    windowInteractorN2D.AddObserver("KeyPressEvent", KeyPressNavigate2D, 1.0)

    windowInteractorN2D.Initialize()
    renderWindowNavigate2D.Render()
    windowInteractorN2D.Start()

    del renderWindowNavigate2D, windowInteractorN2D
Exemple #19
0
    def testAllLogic(self):

        # append multiple displaced spheres into an RGB image.


        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        logics = ["And", "Or", "Xor", "Nand", "Nor", "Not"]
        types = ["Float", "Double", "UnsignedInt", "UnsignedLong", "UnsignedShort", "UnsignedChar"]

        sphere1 = list()
        sphere2 = list()
        logic = list()
        mapper = list()
        actor = list()
        imager = list()

        for idx, operator in enumerate(logics):
            ScalarType = types[idx]

            sphere1.append(vtk.vtkImageEllipsoidSource())
            sphere1[idx].SetCenter(95, 100, 0)
            sphere1[idx].SetRadius(70, 70, 70)
            eval('sphere1[idx].SetOutputScalarTypeTo' + ScalarType + '()')
            sphere1[idx].Update()

            sphere2.append(vtk.vtkImageEllipsoidSource())
            sphere2[idx].SetCenter(161, 100, 0)
            sphere2[idx].SetRadius(70, 70, 70)
            eval('sphere2[idx].SetOutputScalarTypeTo' + ScalarType + '()')
            sphere2[idx].Update()

            logic.append(vtk.vtkImageLogic())
            logic[idx].SetInput1Data(sphere1[idx].GetOutput())
            if operator != "Not":
                logic[idx].SetInput2Data(sphere2[idx].GetOutput())

            logic[idx].SetOutputTrueValue(150)
            eval('logic[idx].SetOperationTo' + operator + '()')

            mapper.append(vtk.vtkImageMapper())
            mapper[idx].SetInputConnection(logic[idx].GetOutputPort())
            mapper[idx].SetColorWindow(255)
            mapper[idx].SetColorLevel(127.5)

            actor.append(vtk.vtkActor2D())
            actor[idx].SetMapper(mapper[idx])

            imager.append(vtk.vtkRenderer())
            imager[idx].AddActor2D(actor[idx])

            renWin.AddRenderer(imager[idx])



        imager[0].SetViewport(0, .5, .33, 1)
        imager[1].SetViewport(.33, .5, .66, 1)
        imager[2].SetViewport(.66, .5, 1, 1)
        imager[3].SetViewport(0, 0, .33, .5)
        imager[4].SetViewport(.33, 0, .66, .5)
        imager[5].SetViewport(.66, 0, 1, .5)

        renWin.SetSize(768, 512)

        # render and interact with data

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

        img_file = "TestAllLogic.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #20
0
    def _CreateLabel(self):
        borderwidth = self._Config['borderwidth']
        width, height = self._DisplaySize
        x, y = self._DisplayOrigin
        x0, y0 = self._Renderer.GetOrigin()

        image = self._Config['bitmap']

        # set up the border
        self._Points = vtk.vtkPoints()
        self._SetPoints()

        cells = vtk.vtkCellArray()
        cells.InsertNextCell(4)
        cells.InsertCellPoint(1)
        cells.InsertCellPoint(3)
        cells.InsertCellPoint(5)
        cells.InsertCellPoint(7)

        if borderwidth > 0:
            cells.InsertNextCell(4)
            cells.InsertCellPoint(0)
            cells.InsertCellPoint(1)
            cells.InsertCellPoint(3)
            cells.InsertCellPoint(2)
            cells.InsertNextCell(4)
            cells.InsertCellPoint(2)
            cells.InsertCellPoint(3)
            cells.InsertCellPoint(5)
            cells.InsertCellPoint(4)
            cells.InsertNextCell(4)
            cells.InsertCellPoint(4)
            cells.InsertCellPoint(5)
            cells.InsertCellPoint(7)
            cells.InsertCellPoint(6)
            cells.InsertNextCell(4)
            cells.InsertCellPoint(6)
            cells.InsertCellPoint(7)
            cells.InsertCellPoint(1)
            cells.InsertCellPoint(0)

        try:  # for VTK 3.x
            scalars = vtk.vtkScalars()
            scalars.SetDataTypeToUnsignedChar()
            scalars.InsertScalar(0, 0)
            scalars.InsertScalar(1, 2)
            scalars.InsertScalar(2, 2)
            scalars.InsertScalar(3, 3)
            scalars.InsertScalar(4, 3)
        except (NameError, AttributeError):
            scalars = vtk.vtkUnsignedCharArray()
            scalars.InsertTuple1(0, 0)
            scalars.InsertTuple1(1, 2)
            scalars.InsertTuple1(2, 2)
            scalars.InsertTuple1(3, 3)
            scalars.InsertTuple1(4, 3)

        data = vtk.vtkPolyData()
        data.SetPoints(self._Points)
        data.SetPolys(cells)
        data.GetCellData().SetScalars(scalars)

        mapper = vtk.vtkPolyDataMapper2D()
        mapper.SetInput(data)
        mapper.SetLookupTable(self._LookupTable)
        mapper.SetColorModeToMapScalars()
        mapper.SetScalarRange(0, 3)

        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.SetPosition(x - x0, y - y0)

        self._Scalars = scalars
        self._Actors.append(actor)
        if self._Renderer:
            self._Renderer.AddActor2D(actor)

        # if there is a bitmap
        if image:
            image.UpdateInformation()
            extent = image.GetWholeExtent()
            spacing = image.GetSpacing()
            origin = image.GetOrigin()

            newextent = (0, width - 1 - borderwidth * 2,
                         0, height - 1 - borderwidth * 2,
                         extent[4], extent[5])
            newspacing = (spacing[0] * float(extent[1] - extent[0]) /
                          float(newextent[1] - newextent[0]),
                          spacing[1] * float(extent[3] - extent[2]) /
                          float(newextent[3] - newextent[2]),
                          spacing[2])
            neworigin = (origin[0] + extent[0] * spacing[0] -
                         newextent[0] * newspacing[0],
                         origin[1] + extent[2] * spacing[1] -
                         newextent[2] * newspacing[1],
                         origin[2])

            reslice = vtk.vtkImageReslice()
            reslice.SetInput(image)
            reslice.SetInterpolationModeToCubic()
            reslice.SetOutputExtent(newextent)
            reslice.SetOutputSpacing(newspacing)
            reslice.SetOutputOrigin(neworigin)
            self._BitmapReslice = reslice

            mapper = vtk.vtkImageMapper()
            mapper.SetInput(reslice.GetOutput())
            mapper.SetColorWindow(255.0)
            mapper.SetColorLevel(127.5)

            actor = vtk.vtkActor2D()
            actor.SetMapper(mapper)
            actor.SetPosition(x - x0, y - y0)

            self._Actors.append(actor)
            if self._Renderer:
                self._Renderer.AddActor2D(actor)

        mapper = vtk.vtkTextMapper()
        mapper.SetInput(self._Config['text'])
        try:
            property = mapper.GetTextProperty()
        except AttributeError:
            property = mapper
        property.SetFontSize(self._Config['fontsize'])
        if self._Config['font'] in ('courier', 'Courier'):
            property.SetFontFamilyToCourier()
        elif self._Config['font'] in ('arial', 'Arial'):
            property.SetFontFamilyToArial()
        elif self._Config['font'] in ('times', 'Times'):
            property.SetFontFamilyToTimes()
        property.SetJustificationToCentered()
        property.SetVerticalJustificationToCentered()
        property.BoldOn()
        self._TextMapper = mapper

        actor = vtk.vtkActor2D()
        apply(actor.GetProperty().SetColor, self._Config['foreground'])
        actor.SetMapper(mapper)
        if "FreeType" in mapper.GetClassName():
            actor.SetPosition(x + width / 2 - x0,
                              y + height / 2 - y0)
        else:  # not a FreeType font, needs position correction
            actor.SetPosition(x + width / 2 - x0 + 1,
                              y + height / 2 - y0 + 1)

        self._Actors.append(actor)
        if self._Renderer:
            self._Renderer.AddActor2D(actor)
    def testImageThresholdConnectivity(self):

        # This script is for testing the 3D flood fill filter.

        # Image pipeline

        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(192, 256)

        reader = vtk.vtkImageReader()
        reader.ReleaseDataFlagOff()
        reader.SetDataByteOrderToLittleEndian()
        reader.SetDataExtent(0, 63, 0, 63, 2, 5)
        reader.SetDataSpacing(3.2, 3.2, 1.5)
        reader.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
        reader.SetDataMask(0x7fff)

        seeds = vtk.vtkPoints()
        seeds.InsertNextPoint(0, 0, 0)
        seeds.InsertNextPoint(100.8, 100.8, 0)

        replacein = ["ReplaceInOn", "ReplaceInOff"]
        replaceout = ["ReplaceOutOn", "ReplaceOutOff"]
        thresholds = [
            "ThresholdByLower(800)", "ThresholdByUpper(1200)",
            "ThresholdBetween(800, 1200)"
        ]

        thresh = list()
        map = list()
        act = list()
        ren = list()

        k = 0
        for rin in replacein:
            for rout in replaceout:
                for t in thresholds:

                    thresh.append(vtk.vtkImageThresholdConnectivity())
                    thresh[k].SetSeedPoints(seeds)
                    thresh[k].SetInValue(2000)
                    thresh[k].SetOutValue(0)
                    eval('thresh[k].' + rin + '()')
                    eval('thresh[k].' + rout + '()')
                    thresh[k].SetInputConnection(reader.GetOutputPort())
                    eval('thresh[k].' + t)

                    map.append(vtk.vtkImageMapper())
                    map[k].SetInputConnection(thresh[k].GetOutputPort())
                    if k < 3:
                        map[k].SetColorWindow(255)
                        map[k].SetColorLevel(127.5)
                    else:
                        map[k].SetColorWindow(2000)
                        map[k].SetColorLevel(1000)

                    act.append(vtk.vtkActor2D())
                    act[k].SetMapper(map[k])

                    ren.append(vtk.vtkRenderer())
                    ren[k].AddActor2D(act[k])

                    renWin.AddRenderer(ren[k])

                    k += 1

        ren[0].SetViewport(0, 0, .33333, .25)
        ren[1].SetViewport(.33333, 0, .66667, .25)
        ren[2].SetViewport(.66667, 0, 1, .25)
        ren[3].SetViewport(0, .25, .33333, .5)
        ren[4].SetViewport(.33333, .25, .66667, .5)
        ren[5].SetViewport(.66667, .25, 1, .5)
        ren[6].SetViewport(0, .5, .33333, .75)
        ren[7].SetViewport(.33333, .5, .66667, .75)
        ren[8].SetViewport(.66667, .5, 1, .75)
        ren[9].SetViewport(0, .75, .33333, 1)
        ren[10].SetViewport(.33333, .75, .66667, 1)
        ren[11].SetViewport(.66667, .75, 1, 1)

        # render and interact with data

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

        img_file = "TestImageThresholdConnectivity.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
Exemple #22
0
    def __init__(self,
                 parent=None,
                 width=400,
                 height=400,
                 showWidget=False,
                 scale=False):
        super(ROIManager, self).__init__()
        self.width = width
        self.height = height
        self.showWidget = showWidget
        self.scale = scale
        self.renderer = None
        self.ROIRadius = 20.0
        self.minValueBG = 0
        self.maxValueBG = 0
        self.minValueFG = 0
        self.maxValueFG = 0
        self.probeWidget = None
        self.drawOverlay = 0

        # utility Qt instances for use in methods
        self.gray = qt.QColor()
        self.gray.setRedF(0.5)
        self.gray.setGreenF(0.5)
        self.gray.setBlueF(0.5)
        # a painter to use for various jobs
        self.painter = qt.QPainter()

        # make a qwidget display
        if self.showWidget:
            self.frame = qt.QFrame(parent)
            mw = slicer.util.mainWindow()
            self.frame.setGeometry(mw.x, mw.y, self.width, self.height)
            self.frameLayout = qt.QVBoxLayout(self.frame)
            self.label = qt.QLabel()
            self.frameLayout.addWidget(self.label)
            self.frame.show()

        # make an image actor in the slice view
        self.vtkImage = vtk.vtkImageData()

        self.mrmlUtils = slicer.qMRMLUtils()
        self.imageMapper = vtk.vtkImageMapper()
        self.imageMapper.SetColorLevel(128)
        self.imageMapper.SetColorWindow(255)
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.imageMapper.SetInput(self.vtkImage)
        else:
            self.imageMapper.SetInputData(self.vtkImage)
        self.actor2D = vtk.vtkActor2D()
        self.actor2D.SetMapper(self.imageMapper)

        # make a circle actor
        self.circle = vtk.vtkRegularPolygonSource()
        self.circle.SetNumberOfSides(50)
        self.circle.SetRadius(5)
        self.circle.SetCenter(0, 0, 0)
        self.circle.GeneratePolylineOn()
        self.circle.GeneratePolygonOff()
        self.circle.Update()
        self.mapper = vtk.vtkPolyDataMapper2D()
        self.actor = vtk.vtkActor2D()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.mapper.SetInput(self.circle.GetOutput())
        else:
            self.mapper.SetInputConnection(self.circle.GetOutputPort())
        self.actor.SetMapper(self.mapper)
        property_ = self.actor.GetProperty()
        property_.SetColor(1, 1, 0)
        property_.SetLineWidth(1)
  def __init__(self,
               input_file,
               gaussian,
               radius,
               thresh,
               zoom,
               zSlice,
               brightness,
               window_size,
               *args, **kwargs):
    """MainWindow constructor"""
    super().__init__(*args, **kwargs)

    # Window setup
    self.resize(window_size[0],window_size[1])
    self.title = "Qt Viewer for Lesion Augmentation"

    self.statusBar().showMessage("Welcome.",8000)

    # Capture defaults
    self.gaussian = gaussian
    self.radius = radius
    self.thresh = thresh
    self.zoom = zoom
    self.brightness = brightness
    self.shape_dic = None
    self.lesion_dic = {}
    self.thresholdArray = None
    self.imageArray = None
    self.zSlice = 100
    self.shape = None
    self.crop = None
    self.colorWindow = 1000
    self.colorLevel = 500
    # Initialize the window
    self.initUI()

    # Set up some VTK pipeline classes
    self.reader = None
    self.gauss = vtk.vtkImageGaussianSmooth()
    self.lesion = vtk.vtkImageData()
    self.threshold = vtk.vtkImageThreshold()
    self.mapToColors = vtk.vtkImageMapToColors()

    self.imageViewer = vtk.vtkImageViewer2()

    self.resizeImage = vtk.vtkImageResize()
    self.resizeSeg = vtk.vtkImageResize()

    self.contourRep = vtk.vtkOrientedGlyphContourRepresentation()
    self.contourWidget = vtk.vtkContourWidget()
    self.placer = vtk.vtkImageActorPointPlacer()

    self.polyData = None

    self.origmapper = vtk.vtkImageMapper()#vtkImageSliceMapper()#
    self.mapper = vtk.vtkImageMapper()
    self.stencilmapper = vtk.vtkPolyDataMapper()

    self.origactor = vtk.vtkActor2D() #vtkImageActor()
    self.actor = vtk.vtkActor2D()
    self.stencilactor = vtk.vtkActor()
    # Take inputs from command line. Only use these if there is an input file specified
    if (input_file != None):
      if (not os.path.exists(input_file)):
        qtw.QMessageBox.warning(self, "Error", "Invalid input file.")
        return

      self.createPipeline(input_file)
      self.statusBar().showMessage("Loading file " + input_file,4000)
      self.changeSigma(gaussian)
      self.changeRadius(radius)
      self.changeThreshold(thresh)
      self.changeBrightness(brightness)
      self.changeSlice(zSlice)
Exemple #24
0
print(dataBounds)

midx = int(dataBounds[0] / 2)
midy = int(dataBounds[1] / 2)
midz = int(dataBounds[2] / 2)

WindowX = dataBounds[0]
WindowY = dataBounds[1]

# midx = WindowX/2
# midy = WindowY/2
# midz = 100

# initialise the mapper
mapper = vtk.vtkImageMapper()
mapper.SetInputConnection(reader.GetOutputPort())
mapper.SetZSlice(midz)
mapper.SetColorWindow(1000)
mapper.SetColorLevel(0)

# create the actor
actor = vtk.vtkActor2D()
actor.SetMapper(mapper)
# actor.SetPosition(midx, midy)

# create the renderer
ren = vtk.vtkRenderer()

# create the render window
renWin = vtk.vtkRenderWindow()
Exemple #25
0
def displayImages(reader):

    # Gets all image data
    imageData = reader.GetOutput()

    # Extracting the dimensions of the image
    coordBounds = imageData.GetDimensions(
    )  # this gives maxx, maxy, maxz coordinate numbers

    # assigning dimension variables in case want to use for sizing and positioning actors and windows
    # in the future, would want to assign location and sizing of objects by local screen resolution
    xdim = int(coordBounds[0])
    ydim = int(coordBounds[1])
    zdim = int(coordBounds[2])

    # initialise the mapper. The image displayed will be the middle image in the image set
    mapper = vtk.vtkImageMapper()
    mapper.SetInputConnection(reader.GetOutputPort())
    mapper.SetZSlice(int(zdim / 2))
    mapper.SetColorWindow(1000)
    mapper.SetColorLevel(600)

    # create the actor
    actor = vtk.vtkActor2D()
    actor.SetMapper(mapper)
    actor.SetPosition(100, 170)

    # assign text to display: current slice and window level and color level
    outputText1 = ("Current slice: " + str(mapper.GetZSlice() + 1) + " of " +
                   str(zdim) + '\n'
                   'Window level: ' + str(int(mapper.GetColorWindow())) +
                   ' Color level: ' + str(int(mapper.GetColorLevel())) + '\n')

    # create text actor
    txt = vtk.vtkTextActor()
    txt.SetInput(outputText1)
    txtprop = txt.GetTextProperty()
    txtprop.SetFontFamilyToArial()
    txtprop.SetFontSize(30)
    txtprop.SetColor(1, 1, 1)
    txt.SetDisplayPosition(10, 30)

    # create second text actor
    infoText = vtk.vtkTextActor()
    infoText.SetInput("Scroll up or down to navigate through the slices. \n")
    infotxtprop = infoText.GetTextProperty()
    infotxtprop.SetFontFamilyToArial()
    infotxtprop.SetFontSize(20)
    infotxtprop.SetColor(1, 1, 1)
    infoText.SetDisplayPosition(10, 15)

    # create the renderer
    ren = vtk.vtkRenderer()

    # create the render window
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(800, 700)

    # Connect an interactor to the image viewer
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.SetInteractorStyle(vtk.vtkInteractorStyleImage())

    # function to change projected image slice with key press
    # Add observers for mouse wheel events to scroll through slices
    def wheelForward(obj, event):
        zSlice = mapper.GetZSlice()

        if (zSlice < mapper.GetWholeZMax()):
            mapper.SetZSlice(zSlice + 1)

        # update displayed text
        outputText1 = ("Current slice: " + str(mapper.GetZSlice() + 1) +
                       " of " + str(zdim) + '\n'
                       'Window level: ' + str(int(mapper.GetColorWindow())) +
                       ' Color level: ' + str(int(mapper.GetColorLevel())) +
                       '\n')
        txt.SetInput(outputText1)

    def wheelBackward(obj, event):
        zSlice = mapper.GetZSlice()

        if (zSlice > mapper.GetWholeZMin()):
            mapper.SetZSlice(zSlice - 1)

        # update displayed text
        outputText1 = ("Current slice: " + str(mapper.GetZSlice() + 1) +
                       " of " + str(zdim) + '\n'
                       'Window level: ' + str(int(mapper.GetColorWindow())) +
                       ' Color level: ' + str(int(mapper.GetColorLevel())) +
                       '\n')
        txt.SetInput(outputText1)

    # add the scrolling events to move through slices
    iren.AddObserver("MouseWheelForwardEvent", wheelForward)
    iren.AddObserver("MouseWheelBackwardEvent", wheelBackward)

    # add the actors to the renderer
    ren.AddActor(actor)
    ren.AddActor(txt)
    ren.AddActor(infoText)

    # initialise the interactor
    iren.Initialize()

    # render the scene with all actors in it
    renWin.Render()

    # Start the event loop for the interactor
    iren.Start()

    return ()
Exemple #26
0
    def testAllMaskBits(self):

        # This script calculates the luminance of an image

        renWin = vtk.vtkRenderWindow()


        # Image pipeline

        image1 = vtk.vtkTIFFReader()
        image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")

        # "beach.tif" image contains ORIENTATION tag which is
        # ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
        # reader parses this tag and sets the internal TIFF image
        # orientation accordingly.  To overwrite this orientation with a vtk
        # convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
        # SetOrientationType method with parameter value of 4.
        image1.SetOrientationType(4)

        shrink = vtk.vtkImageShrink3D()
        shrink.SetInputConnection(image1.GetOutputPort())
        shrink.SetShrinkFactors(2, 2, 1)

        operators = ["ByPass", "And", "Nand", "Xor", "Or", "Nor"]

        operator = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for idx, op in enumerate(operators):
            if op != "ByPass":
                operator.update({idx: vtk.vtkImageMaskBits()})
                operator[idx].SetInputConnection(shrink.GetOutputPort())
                eval('operator[' + str(idx) + '].SetOperationTo' + op + '()')
                operator[idx].SetMasks(255, 255, 0)

            mapper.update({idx: vtk.vtkImageMapper()})
            if op != "ByPass":
                mapper[idx].SetInputConnection(operator[idx].GetOutputPort())
            else:
                mapper[idx].SetInputConnection(shrink.GetOutputPort())
            mapper[idx].SetColorWindow(255)
            mapper[idx].SetColorLevel(127.5)

            actor.update({idx: vtk.vtkActor2D()})
            actor[idx].SetMapper(mapper[idx])

            imager.update({idx: vtk.vtkRenderer()})
            imager[idx].AddActor2D(actor[idx])

            renWin.AddRenderer(imager[idx])


        column = 0
        row = 0
        deltaX = 1.0 / 3.0
        deltaY = 1.0 / 2.0

        for idx in range(len(operators)):
            imager[idx].SetViewport(column * deltaX, row * deltaY, (column + 1) * deltaX, (row + 1) * deltaY)
            column += 1
            if column > 2:
                column = 0
                row += 1

        renWin.SetSize(384, 256)

        # render and interact with data

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

        img_file = "TestAllMaskBits.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #27
0
    def get_vtkobjects(self, opacity=None):

        if self.data is None:
            raise Exception('No image data loaded!')

        ImageImporter = vtk.vtkImageImport()

        # Create a temporary floating point copy of the data, for scaling.
        # Also flip the data (vtk addresses y from bottom right) and put in display coords.
        Data = np.float32(
            np.flipud(self.transform.original_to_display_image(self.data)))
        clim = np.float32(self.clim)

        # Scale to colour limits and convert to uint8 for displaying.
        Data -= clim[0]
        Data /= (clim[1] - clim[0])
        Data *= 255.
        Data = np.uint8(Data)

        if self.postprocessor is not None:
            Data = self.postprocessor(Data)

        if opacity is not None:
            Alpha = np.uint8(np.ones(Data.shape[:2]) * opacity * 255)
            Data = np.dstack([Data, Alpha])
        if self.alpha is not None:
            Alpha = np.flipud(
                self.transform.original_to_display_image(self.alpha))
            Data = np.dstack([Data, Alpha])

        DataString = Data.tostring()
        ImageImporter.CopyImportVoidPointer(DataString, len(DataString))
        ImageImporter.SetDataScalarTypeToUnsignedChar()

        if len(self.data.shape) == 2:
            ImageImporter.SetNumberOfScalarComponents(1)
        else:
            ImageImporter.SetNumberOfScalarComponents(Data.shape[2])

        ImageImporter.SetDataExtent(0, Data.shape[1] - 1, 0, Data.shape[0] - 1,
                                    0, 0)
        ImageImporter.SetWholeExtent(0, Data.shape[1] - 1, 0,
                                     Data.shape[0] - 1, 0, 0)

        Resizer = vtk.vtkImageResize()
        Resizer.SetInputConnection(ImageImporter.GetOutputPort())
        Resizer.SetResizeMethodToOutputDimensions()
        Resizer.SetOutputDimensions((Data.shape[1], Data.shape[0], 1))
        # jrh mod begin
        Resizer.InterpolateOff()

        mapper = vtk.vtkImageMapper()
        mapper.SetInputConnection(Resizer.GetOutputPort())
        mapper.SetColorWindow(255)
        mapper.SetColorLevel(127.5)

        Actor = vtk.vtkActor2D()
        Actor.SetMapper(mapper)
        Actor.GetProperty().SetDisplayLocationToBackground()

        return Actor, Resizer
Exemple #28
0
    def testAllShrinks(self):

        prefix = VTK_DATA_ROOT + "/Data/headsq/quarter"

        renWin = vtk.vtkRenderWindow()

        # Image pipeline
        reader = vtk.vtkImageReader()
        reader.SetDataExtent(0, 63, 0, 63, 1, 93)
        reader.SetFilePrefix(prefix)
        reader.SetDataByteOrderToLittleEndian()
        reader.SetDataMask(0x7fff)

        factor = 4
        magFactor = 8

        ops = ["Minimum", "Maximum", "Mean", "Median", "NoOp"]

        shrink = dict()
        mag = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for operator in ops:
            shrink.update({operator: vtk.vtkImageShrink3D()})
            shrink[operator].SetMean(0)
            if operator != "NoOp":
                eval('shrink[operator].' + operator + 'On()')
            shrink[operator].SetShrinkFactors(factor, factor, factor)
            shrink[operator].SetInputConnection(reader.GetOutputPort())
            mag.update({operator: vtk.vtkImageMagnify()})
            mag[operator].SetMagnificationFactors(magFactor, magFactor,
                                                  magFactor)
            mag[operator].InterpolateOff()
            mag[operator].SetInputConnection(shrink[operator].GetOutputPort())
            mapper.update({operator: vtk.vtkImageMapper()})
            mapper[operator].SetInputConnection(mag[operator].GetOutputPort())
            mapper[operator].SetColorWindow(2000)
            mapper[operator].SetColorLevel(1000)
            mapper[operator].SetZSlice(45)
            actor.update({operator: vtk.vtkActor2D()})
            actor[operator].SetMapper(mapper[operator])
            imager.update({operator: vtk.vtkRenderer()})
            imager[operator].AddActor2D(actor[operator])
            renWin.AddRenderer(imager[operator])

        shrink["Minimum"].Update
        shrink["Maximum"].Update
        shrink["Mean"].Update
        shrink["Median"].Update

        imager["Minimum"].SetViewport(0, 0, .5, .33)
        imager["Maximum"].SetViewport(0, .33, .5, .667)
        imager["Mean"].SetViewport(.5, 0, 1, .33)
        imager["Median"].SetViewport(.5, .33, 1, .667)
        imager["NoOp"].SetViewport(0, .667, 1, 1)

        renWin.SetSize(256, 384)

        # render and interact with data

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

        img_file = "TestAllShrinks.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
Exemple #29
0
def get_image_actor(image_array, clim=None, actortype='vtkImageActor'):

    image = image_array.copy()

    if clim is None:
        if image.min() != image.max():
            clim = [image.min(), image.max()]
        else:
            clim = [0, 255]

    clim = np.array(clim)

    # If the array isn't already 8-bit int, make it 8-bit int...
    if image.dtype != np.uint8:
        # If we're given a higher bit-depth integer, it's easy to downcast it.
        if image.dtype == np.uint16 or image.dtype == np.int16:
            image = np.uint8(image / 2**8)
            clim = np.uint8(clim / 2**8)
        elif image.dtype == np.uint32 or image.dtype == np.int32:
            image = np.uint8(image / 2**24)
            clim = np.uint8(clim / 2**24)
        elif image.dtype == np.uint64 or image.dtype == np.int64:
            image = np.uint8(image / 2**56)
            clim = np.uint8(clim / 2**24)
        # Otherwise, scale it in a floating point way to its own max & min
        # and strip out any transparency info (since we can't be sure of the scale used for transparency)
        else:

            if image.min() < 0:
                image = image - image.min()
                clim = clim - image.min()

            if len(image.shape) == 3:
                if image.shape[2] == 4:
                    image = image[:, :, :-1]

            image = np.uint8(255. * (image - image.min()) /
                             (image.max() - image.min()))

    vtk_im_importer = vtk.vtkImageImport()

    # Create a temporary floating point copy of the data, for scaling.
    # Also flip the data (vtk addresses y from bottom right) and put in display coords.
    image = np.float32(np.flipud(image))
    clim = np.float32(clim)

    # Scale to colour limits and convert to uint8 for displaying.
    image -= clim[0]
    image /= (clim[1] - clim[0])
    image *= 255.
    image = np.uint8(image)

    im_data_string = image.tostring()
    vtk_im_importer.CopyImportVoidPointer(im_data_string, len(im_data_string))
    vtk_im_importer.SetDataScalarTypeToUnsignedChar()

    if len(image.shape) == 2:
        vtk_im_importer.SetNumberOfScalarComponents(1)
    else:
        vtk_im_importer.SetNumberOfScalarComponents(image.shape[2])

    vtk_im_importer.SetDataExtent(0, image.shape[1] - 1, 0, image.shape[0] - 1,
                                  0, 0)
    vtk_im_importer.SetWholeExtent(0, image.shape[1] - 1, 0,
                                   image.shape[0] - 1, 0, 0)

    if actortype == 'vtkImageActor':
        actor = vtk.vtkImageActor()
        actor.InterpolateOff()
        mapper = actor.GetMapper()
        mapper.SetInputConnection(vtk_im_importer.GetOutputPort())

        return actor

    elif actortype == 'vtkActor2D':
        resizer = vtk.vtkImageResize()
        resizer.SetInputConnection(vtk_im_importer.GetOutputPort())
        resizer.SetResizeMethodToOutputDimensions()
        resizer.SetOutputDimensions(
            (image_array.shape[1], image_array.shape[0], 1))
        resizer.InterpolateOff()

        mapper = vtk.vtkImageMapper()
        mapper.SetInputConnection(resizer.GetOutputPort())
        mapper.SetColorWindow(255)
        mapper.SetColorLevel(127.5)

        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.GetProperty().SetDisplayLocationToForeground()

        return actor, resizer
    def _CreateLabel(self):
        borderwidth = self._Config['borderwidth']
        width, height = self._DisplaySize
        x, y = self._DisplayOrigin
        x0, y0 = self._Renderer.GetOrigin()

        image = self._Config['bitmap']

        # set up the border
        self._Points = vtk.vtkPoints()
        self._SetPoints()

        cells = vtk.vtkCellArray()
        cells.InsertNextCell(4)
        cells.InsertCellPoint(1)
        cells.InsertCellPoint(3)
        cells.InsertCellPoint(5)
        cells.InsertCellPoint(7)

        if borderwidth > 0:
            cells.InsertNextCell(4)
            cells.InsertCellPoint(0)
            cells.InsertCellPoint(1)
            cells.InsertCellPoint(3)
            cells.InsertCellPoint(2)
            cells.InsertNextCell(4)
            cells.InsertCellPoint(2)
            cells.InsertCellPoint(3)
            cells.InsertCellPoint(5)
            cells.InsertCellPoint(4)
            cells.InsertNextCell(4)
            cells.InsertCellPoint(4)
            cells.InsertCellPoint(5)
            cells.InsertCellPoint(7)
            cells.InsertCellPoint(6)
            cells.InsertNextCell(4)
            cells.InsertCellPoint(6)
            cells.InsertCellPoint(7)
            cells.InsertCellPoint(1)
            cells.InsertCellPoint(0)

        try:  # for VTK 3.x
            scalars = vtk.vtkScalars()
            scalars.SetDataTypeToUnsignedChar()
            scalars.InsertScalar(0, 0)
            scalars.InsertScalar(1, 2)
            scalars.InsertScalar(2, 2)
            scalars.InsertScalar(3, 3)
            scalars.InsertScalar(4, 3)
        except (NameError, AttributeError):
            scalars = vtk.vtkUnsignedCharArray()
            scalars.InsertTuple1(0, 0)
            scalars.InsertTuple1(1, 2)
            scalars.InsertTuple1(2, 2)
            scalars.InsertTuple1(3, 3)
            scalars.InsertTuple1(4, 3)

        data = vtk.vtkPolyData()
        data.SetPoints(self._Points)
        data.SetPolys(cells)
        data.GetCellData().SetScalars(scalars)

        mapper = vtk.vtkPolyDataMapper2D()
        mapper.SetInput(data)
        mapper.SetLookupTable(self._LookupTable)
        mapper.SetColorModeToMapScalars()
        mapper.SetScalarRange(0, 3)

        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.SetPosition(x - x0, y - y0)

        self._Scalars = scalars
        self._Actors.append(actor)
        if self._Renderer:
            self._Renderer.AddActor2D(actor)

        # if there is a bitmap
        if image:
            image.UpdateInformation()
            extent = image.GetExtent()  # VTK 6
            spacing = image.GetSpacing()
            origin = image.GetOrigin()

            newextent = (0, width - 1 - borderwidth * 2,
                         0, height - 1 - borderwidth * 2,
                         extent[4], extent[5])
            newspacing = (spacing[0] * float(extent[1] - extent[0]) /
                          float(newextent[1] - newextent[0]),
                          spacing[1] * float(extent[3] - extent[2]) /
                          float(newextent[3] - newextent[2]),
                          spacing[2])
            neworigin = (origin[0] + extent[0] * spacing[0] -
                         newextent[0] * newspacing[0],
                         origin[1] + extent[2] * spacing[1] -
                         newextent[2] * newspacing[1],
                         origin[2])

            reslice = vtk.vtkImageReslice()
            reslice.SetInput(image)
            reslice.SetInterpolationModeToCubic()
            reslice.SetOutputExtent(newextent)
            reslice.SetOutputSpacing(newspacing)
            reslice.SetOutputOrigin(neworigin)
            self._BitmapReslice = reslice

            mapper = vtk.vtkImageMapper()
            mapper.SetInput(reslice.GetOutput())
            mapper.SetColorWindow(255.0)
            mapper.SetColorLevel(127.5)

            actor = vtk.vtkActor2D()
            actor.SetMapper(mapper)
            actor.SetPosition(x - x0, y - y0)

            self._Actors.append(actor)
            if self._Renderer:
                self._Renderer.AddActor2D(actor)

        mapper = vtk.vtkTextMapper()
        mapper.SetInput(self._Config['text'])
        try:
            property = mapper.GetTextProperty()
        except AttributeError:
            property = mapper
        property.SetFontSize(self._Config['fontsize'])
        if self._Config['font'] in ('courier', 'Courier'):
            property.SetFontFamilyToCourier()
        elif self._Config['font'] in ('arial', 'Arial'):
            property.SetFontFamilyToArial()
        elif self._Config['font'] in ('times', 'Times'):
            property.SetFontFamilyToTimes()
        property.SetJustificationToCentered()
        property.SetVerticalJustificationToCentered()
        property.BoldOn()
        self._TextMapper = mapper

        actor = vtk.vtkActor2D()
        actor.GetProperty().SetColor(*self._Config['foreground'])
        actor.SetMapper(mapper)
        if "FreeType" in mapper.GetClassName():
            actor.SetPosition(x + old_div(width, 2) - x0,
                              y + old_div(height, 2) - y0)
        else:  # not a FreeType font, needs position correction
            actor.SetPosition(x + old_div(width, 2) - x0 + 1,
                              y + old_div(height, 2) - y0 + 1)

        self._Actors.append(actor)
        if self._Renderer:
            self._Renderer.AddActor2D(actor)
source = mabdi.SourceEnvironmentTable()
source.Update()

fdi = mabdi.FilterDepthImage(offscreen=False)
fdi.set_polydata(source)

# show output of the filter

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

renWin.SetSize(640, 480)
imageMapper = vtk.vtkImageMapper()
imageMapper.SetInputConnection(fdi.GetOutputPort())
imageMapper.SetColorWindow(1.0)
imageMapper.SetColorLevel(0.5)
imageActor = vtk.vtkActor2D()
imageActor.SetMapper(imageMapper)
ren.AddActor(imageActor)

iren.Initialize()
iren.Render()

rang = np.arange(-40, 41, dtype=float)
position = np.vstack((rang/20,
                      np.ones(len(rang)),
                      np.ones(len(rang))*2)).T
lookat = np.vstack((rang/40,
Exemple #32
0
    def testWipe(self):

        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        image1 = vtk.vtkImageCanvasSource2D()
        image1.SetNumberOfScalarComponents(3)
        image1.SetScalarTypeToUnsignedChar()
        image1.SetExtent(0, 79, 0, 79, 0, 0)
        image1.SetDrawColor(255, 255, 0)
        image1.FillBox(0, 79, 0, 79)
        image1.Update()

        image2 = vtk.vtkImageCanvasSource2D()
        image2.SetNumberOfScalarComponents(3)
        image2.SetScalarTypeToUnsignedChar()
        image2.SetExtent(0, 79, 0, 79, 0, 0)
        image2.SetDrawColor(0, 255, 255)
        image2.FillBox(0, 79, 0, 79)
        image2.Update()

        mapper = vtk.vtkImageMapper()
        mapper.SetInputConnection(image1.GetOutputPort())
        mapper.SetColorWindow(255)
        mapper.SetColorLevel(127.5)
        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        imager = vtk.vtkRenderer()
        imager.AddActor2D(actor)

        renWin.AddRenderer(imager)

        wipes = ["Quad", "Horizontal", "Vertical", "LowerLeft", "LowerRight", "UpperLeft", "UpperRight"]

        wiper = dict()
        mapper = dict()
        actor = dict()
        imagers = dict()

        for wipe in wipes:
            wiper.update({wipe:vtk.vtkImageRectilinearWipe()})
            wiper[wipe].SetInput1Data(image1.GetOutput())
            wiper[wipe].SetInput2Data(image2.GetOutput())
            wiper[wipe].SetPosition(20, 20)
            eval('wiper[wipe].SetWipeTo' + wipe + '()')

            mapper.update({wipe:vtk.vtkImageMapper()})
            mapper[wipe].SetInputConnection(wiper[wipe].GetOutputPort())
            mapper[wipe].SetColorWindow(255)
            mapper[wipe].SetColorLevel(127.5)

            actor.update({wipe:vtk.vtkActor2D()})
            actor[wipe].SetMapper(mapper[wipe])

            imagers.update({wipe:vtk.vtkRenderer()})
            imagers[wipe].AddActor2D(actor[wipe])

            renWin.AddRenderer(imagers[wipe])

        imagers["Quad"].SetViewport(0, .5, .25, 1)
        imagers["Horizontal"].SetViewport(.25, .5, .5, 1)
        imagers["Vertical"].SetViewport(.5, .5, .75, 1)
        imagers["LowerLeft"].SetViewport(.75, .5, 1, 1)
        imagers["LowerRight"].SetViewport(0, 0, .25, .5)
        imagers["UpperLeft"].SetViewport(.25, 0, .5, .5)
        imagers["UpperRight"].SetViewport(.5, 0, .75, .5)
        imager.SetViewport(.75, 0, 1, .5)

        renWin.SetSize(400, 200)

        # render and interact with data

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

        img_file = "TestWipe.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
    def testAllMathematics(self):

        # append multiple displaced spheres into an RGB image.

        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        sphere1 = vtk.vtkImageEllipsoidSource()
        sphere1.SetCenter(40, 20, 0)
        sphere1.SetRadius(30, 30, 0)
        sphere1.SetInValue(.75)
        sphere1.SetOutValue(.3)
        sphere1.SetOutputScalarTypeToFloat()
        sphere1.SetWholeExtent(0, 99, 0, 74, 0, 0)
        sphere1.Update()

        sphere2 = vtk.vtkImageEllipsoidSource()
        sphere2.SetCenter(60, 30, 0)
        sphere2.SetRadius(20, 20, 20)
        sphere2.SetInValue(.2)
        sphere2.SetOutValue(.5)
        sphere2.SetOutputScalarTypeToFloat()
        sphere2.SetWholeExtent(0, 99, 0, 74, 0, 0)
        sphere2.Update()

        mathematics = [
            "Add", "Subtract", "Multiply", "Divide", "Invert", "Sin", "Cos",
            "Exp", "Log", "AbsoluteValue", "Square", "SquareRoot", "Min",
            "Max", "ATAN", "ATAN2", "MultiplyByK", "ReplaceCByK", "AddConstant"
        ]

        mathematic = list()
        mapper = list()
        actor = list()
        imager = list()

        for idx, operator in enumerate(mathematics):
            mathematic.append(vtk.vtkImageMathematics())
            mathematic[idx].SetInput1Data(sphere1.GetOutput())
            mathematic[idx].SetInput2Data(sphere2.GetOutput())
            eval('mathematic[idx].SetOperationTo' + operator + '()')
            mathematic[idx].SetConstantK(.3)
            mathematic[idx].SetConstantC(.75)
            mapper.append(vtk.vtkImageMapper())
            mapper[idx].SetInputConnection(mathematic[idx].GetOutputPort())
            mapper[idx].SetColorWindow(2.0)
            mapper[idx].SetColorLevel(.75)
            actor.append(vtk.vtkActor2D())
            actor[idx].SetMapper(mapper[idx])
            imager.append(vtk.vtkRenderer())
            imager[idx].AddActor2D(actor[idx])
            renWin.AddRenderer(imager[idx])

        column = 1
        row = 1
        deltaX = 1.0 / 6.0
        deltaY = 1.0 / 4.0

        for idx, operator in enumerate(mathematics):
            imager[idx].SetViewport((column - 1) * deltaX, (row - 1) * deltaY,
                                    column * deltaX, row * deltaY)
            column += 1
            if column > 6:
                column = 1
                row += 1

        # Make the last operator finish the row
        vp = imager[len(mathematics) - 1].GetViewport()
        imager[len(mathematics) - 1].SetViewport(vp[0], vp[1], 1, 1)

        renWin.SetSize(600, 300)

        # render and interact with data

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

        img_file = "TestAllMathematics.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
Exemple #34
0
    def testAllBlendsFloat(self):

        # This script blends images that consist of float data

        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(512, 256)

        # Image pipeline

        inputImage = vtk.vtkTIFFReader()
        inputImage.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")

        # "beach.tif" image contains ORIENTATION tag which is
        # ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
        # reader parses this tag and sets the internal TIFF image
        # orientation accordingly.  To overwrite this orientation with a vtk
        # convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
        # SetOrientationType method with parameter value of 4.
        inputImage.SetOrientationType(4)

        inputImage2 = vtk.vtkBMPReader()
        inputImage2.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")

        # shrink the images to a reasonable size

        shrink1 = vtk.vtkImageShrink3D()
        shrink1.SetInputConnection(inputImage.GetOutputPort())
        shrink1.SetShrinkFactors(2, 2, 1)

        shrink2 = vtk.vtkImageShrink3D()
        shrink2.SetInputConnection(inputImage2.GetOutputPort())
        shrink2.SetShrinkFactors(2, 2, 1)

        color = vtk.vtkImageShiftScale()
        color.SetOutputScalarTypeToFloat()
        color.SetShift(0)
        color.SetScale(1.0 / 255)
        color.SetInputConnection(shrink1.GetOutputPort())

        backgroundColor = vtk.vtkImageShiftScale()
        backgroundColor.SetOutputScalarTypeToFloat()
        backgroundColor.SetShift(0)
        backgroundColor.SetScale(1.0 / 255)
        backgroundColor.SetInputConnection(shrink2.GetOutputPort())

        # create a greyscale version

        luminance = vtk.vtkImageLuminance()
        luminance.SetInputConnection(color.GetOutputPort())

        backgroundLuminance = vtk.vtkImageLuminance()
        backgroundLuminance.SetInputConnection(backgroundColor.GetOutputPort())

        # create an alpha mask

        alpha = vtk.vtkImageThreshold()
        alpha.SetInputConnection(luminance.GetOutputPort())
        alpha.ThresholdByLower(0.9)
        alpha.SetInValue(1.0)
        alpha.SetOutValue(0.0)

        # make luminanceAlpha and colorAlpha versions

        luminanceAlpha = vtk.vtkImageAppendComponents()
        luminanceAlpha.AddInputConnection(luminance.GetOutputPort())
        luminanceAlpha.AddInputConnection(alpha.GetOutputPort())

        colorAlpha = vtk.vtkImageAppendComponents()
        colorAlpha.AddInputConnection(color.GetOutputPort())
        colorAlpha.AddInputConnection(alpha.GetOutputPort())

        foregrounds = ["luminance", "luminanceAlpha", "color", "colorAlpha"]
        backgrounds = ["backgroundColor", "backgroundLuminance"]

        deltaX = 1.0 / 4.0
        deltaY = 1.0 / 2.0

        blend = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for row, bg in enumerate(backgrounds):
            for column, fg in enumerate(foregrounds):
                blend.update({bg:{fg:vtk.vtkImageBlend()}})
                blend[bg][fg].AddInputConnection(eval(bg + '.GetOutputPort()'))
                if bg == "backgroundColor" or fg == "luminance" or fg == "luminanceAlpha":
                    blend[bg][fg].AddInputConnection(eval(fg + '.GetOutputPort()'))
                    blend[bg][fg].SetOpacity(1, 0.8)

                mapper.update({bg:{fg:vtk.vtkImageMapper()}})
                mapper[bg][fg].SetInputConnection(blend[bg][fg].GetOutputPort())
                mapper[bg][fg].SetColorWindow(1.0)
                mapper[bg][fg].SetColorLevel(0.5)

                actor.update({bg:{fg:vtk.vtkActor2D()}})
                actor[bg][fg].SetMapper(mapper[bg][fg])

                imager.update({bg:{fg:vtk.vtkRenderer()}})
                imager[bg][fg].AddActor2D(actor[bg][fg])
                imager[bg][fg].SetViewport(column * deltaX, row * deltaY, (column + 1) * deltaX, (row + 1) * deltaY)

                renWin.AddRenderer(imager[bg][fg])

        # render and interact with data

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

        img_file = "TestAllBlendsFloat.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #35
0
    def testAllShrinks(self):


        prefix = VTK_DATA_ROOT + "/Data/headsq/quarter"


        renWin = vtk.vtkRenderWindow()

        # Image pipeline
        reader = vtk.vtkImageReader()
        reader.SetDataExtent(0, 63, 0, 63, 1, 93)
        reader.SetFilePrefix(prefix)
        reader.SetDataByteOrderToLittleEndian()
        reader.SetDataMask(0x7fff)

        factor = 4
        magFactor = 8

        ops = ["Minimum", "Maximum", "Mean", "Median", "NoOp"]

        shrink = dict()
        mag = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for operator in ops:
            shrink.update({operator:vtk.vtkImageShrink3D()})
            shrink[operator].SetMean(0)
            if operator != "NoOp":
             eval('shrink[operator].' + operator + 'On()')
            shrink[operator].SetShrinkFactors(factor, factor, factor)
            shrink[operator].SetInputConnection(reader.GetOutputPort())
            mag.update({operator:vtk.vtkImageMagnify()})
            mag[operator].SetMagnificationFactors(magFactor, magFactor, magFactor)
            mag[operator].InterpolateOff()
            mag[operator].SetInputConnection(shrink[operator].GetOutputPort())
            mapper.update({operator:vtk.vtkImageMapper()})
            mapper[operator].SetInputConnection(mag[operator].GetOutputPort())
            mapper[operator].SetColorWindow(2000)
            mapper[operator].SetColorLevel(1000)
            mapper[operator].SetZSlice(45)
            actor.update({operator:vtk.vtkActor2D()})
            actor[operator].SetMapper(mapper[operator])
            imager.update({operator:vtk.vtkRenderer()})
            imager[operator].AddActor2D(actor[operator])
            renWin.AddRenderer(imager[operator])

        shrink["Minimum"].Update
        shrink["Maximum"].Update
        shrink["Mean"].Update
        shrink["Median"].Update

        imager["Minimum"].SetViewport(0, 0, .5, .33)
        imager["Maximum"].SetViewport(0, .33, .5, .667)
        imager["Mean"].SetViewport(.5, 0, 1, .33)
        imager["Median"].SetViewport(.5, .33, 1, .667)
        imager["NoOp"].SetViewport(0, .667, 1, 1)

        renWin.SetSize(256, 384)

        # render and interact with data

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

        img_file = "TestAllShrinks.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #36
0
    def testAllLogic(self):

        # append multiple displaced spheres into an RGB image.

        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        logics = ["And", "Or", "Xor", "Nand", "Nor", "Not"]
        types = [
            "Float", "Double", "UnsignedInt", "UnsignedLong", "UnsignedShort",
            "UnsignedChar"
        ]

        sphere1 = list()
        sphere2 = list()
        logic = list()
        mapper = list()
        actor = list()
        imager = list()

        for idx, operator in enumerate(logics):
            ScalarType = types[idx]

            sphere1.append(vtk.vtkImageEllipsoidSource())
            sphere1[idx].SetCenter(95, 100, 0)
            sphere1[idx].SetRadius(70, 70, 70)
            eval('sphere1[idx].SetOutputScalarTypeTo' + ScalarType + '()')
            sphere1[idx].Update()

            sphere2.append(vtk.vtkImageEllipsoidSource())
            sphere2[idx].SetCenter(161, 100, 0)
            sphere2[idx].SetRadius(70, 70, 70)
            eval('sphere2[idx].SetOutputScalarTypeTo' + ScalarType + '()')
            sphere2[idx].Update()

            logic.append(vtk.vtkImageLogic())
            logic[idx].SetInput1Data(sphere1[idx].GetOutput())
            if operator != "Not":
                logic[idx].SetInput2Data(sphere2[idx].GetOutput())

            logic[idx].SetOutputTrueValue(150)
            eval('logic[idx].SetOperationTo' + operator + '()')

            mapper.append(vtk.vtkImageMapper())
            mapper[idx].SetInputConnection(logic[idx].GetOutputPort())
            mapper[idx].SetColorWindow(255)
            mapper[idx].SetColorLevel(127.5)

            actor.append(vtk.vtkActor2D())
            actor[idx].SetMapper(mapper[idx])

            imager.append(vtk.vtkRenderer())
            imager[idx].AddActor2D(actor[idx])

            renWin.AddRenderer(imager[idx])

        imager[0].SetViewport(0, .5, .33, 1)
        imager[1].SetViewport(.33, .5, .66, 1)
        imager[2].SetViewport(.66, .5, 1, 1)
        imager[3].SetViewport(0, 0, .33, .5)
        imager[4].SetViewport(.33, 0, .66, .5)
        imager[5].SetViewport(.66, 0, 1, .5)

        renWin.SetSize(768, 512)

        # render and interact with data

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

        img_file = "TestAllLogic.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
Exemple #37
0
    def testAllBlends(self):

        # This script calculates the luminance of an image

        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(512, 256)

        # Image pipeline

        image1 = vtk.vtkTIFFReader()
        image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")

        # "beach.tif" image contains ORIENTATION tag which is
        # ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
        # reader parses this tag and sets the internal TIFF image
        # orientation accordingly.  To overwrite this orientation with a vtk
        # convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
        # SetOrientationType method with parameter value of 4.
        image1.SetOrientationType(4)

        image2 = vtk.vtkBMPReader()
        image2.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")

        # shrink the images to a reasonable size

        color = vtk.vtkImageShrink3D()
        color.SetInputConnection(image1.GetOutputPort())
        color.SetShrinkFactors(2, 2, 1)

        backgroundColor = vtk.vtkImageShrink3D()
        backgroundColor.SetInputConnection(image2.GetOutputPort())
        backgroundColor.SetShrinkFactors(2, 2, 1)

        # create a greyscale version

        luminance = vtk.vtkImageLuminance()
        luminance.SetInputConnection(color.GetOutputPort())

        backgroundLuminance = vtk.vtkImageLuminance()
        backgroundLuminance.SetInputConnection(backgroundColor.GetOutputPort())

        # create an alpha mask

        table = vtk.vtkLookupTable()
        table.SetTableRange(220, 255)
        table.SetValueRange(1, 0)
        table.SetSaturationRange(0, 0)
        table.Build()

        alpha = vtk.vtkImageMapToColors()
        alpha.SetInputConnection(luminance.GetOutputPort())
        alpha.SetLookupTable(table)
        alpha.SetOutputFormatToLuminance()

        # make luminanceAlpha and colorAlpha versions

        luminanceAlpha = vtk.vtkImageAppendComponents()
        luminanceAlpha.AddInputConnection(luminance.GetOutputPort())
        luminanceAlpha.AddInputConnection(alpha.GetOutputPort())

        colorAlpha = vtk.vtkImageAppendComponents()
        colorAlpha.AddInputConnection(color.GetOutputPort())
        colorAlpha.AddInputConnection(alpha.GetOutputPort())

        foregrounds = ["luminance", "luminanceAlpha", "color", "colorAlpha"]
        backgrounds = ["backgroundColor", "backgroundLuminance"]

        deltaX = 1.0 / 4.0
        deltaY = 1.0 / 2.0

        blend = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for row, bg in enumerate(backgrounds):
            for column, fg in enumerate(foregrounds):
                blend.update({bg:{fg:vtk.vtkImageBlend()}})
                blend[bg][fg].AddInputConnection(eval(bg + '.GetOutputPort()'))
                if bg == "backgroundColor" or fg == "luminance" or fg == "luminanceAlpha":
                    blend[bg][fg].AddInputConnection(eval(fg + '.GetOutputPort()'))
                    blend[bg][fg].SetOpacity(1, 0.8)

                mapper.update({bg:{fg:vtk.vtkImageMapper()}})
                mapper[bg][fg].SetInputConnection(blend[bg][fg].GetOutputPort())
                mapper[bg][fg].SetColorWindow(255)
                mapper[bg][fg].SetColorLevel(127.5)

                actor.update({bg:{fg:vtk.vtkActor2D()}})
                actor[bg][fg].SetMapper(mapper[bg][fg])

                imager.update({bg:{fg:vtk.vtkRenderer()}})
                imager[bg][fg].AddActor2D(actor[bg][fg])
                imager[bg][fg].SetViewport(column * deltaX, row * deltaY, (column + 1) * deltaX, (row + 1) * deltaY)

                renWin.AddRenderer(imager[bg][fg])

                column += 1

        # render and interact with data

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

        img_file = "TestAllBlends.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #38
0
def render(Data1, Data2, point):

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

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

    pts = vtk.vtkPoints()

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

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

    lines = vtk.vtkCellArray()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    iren.Initialize()
    renWin.Render()
    iren.Start()
    print("GetAlphaBitPlanes: " + str(renWin.GetAlphaBitPlanes()))

# create window to image filter, grabbing RGB and alpha
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(renWin)
w2i.SetInputBufferTypeToRGBA()

# grab window
w2i.Update()

# copy the output
outputData = w2i.GetOutput().NewInstance()
outputData.DeepCopy(w2i.GetOutput())

# set up mappers and actors to display the image
im = vtk.vtkImageMapper()
im.SetColorWindow(255)
im.SetColorLevel(127.5)
im.SetInputData(outputData)

ia2 = vtk.vtkActor2D()
ia2.SetMapper(im)

# now, change the image (background is now green)
sphactor.SetScale(2, 2, 2)

ren1.SetBackground(0, 1, 0)
# add the image of the sphere (keeping the original sphere too)
ren1.AddActor(ia2)
ren1.SetViewport(0, 0, 1, 1)
Exemple #40
0
blend = dict()
mapper = dict()
actor = dict()
imager = dict()

for row, bg in enumerate(backgrounds):
    for column, fg in enumerate(foregrounds):
        blend.update({bg: {fg: vtk.vtkImageBlend()}})
        blend[bg][fg].AddInputConnection(eval(bg + '.GetOutputPort()'))
        blend[bg][fg].SetBlendModeToCompound()
        if bg == "backgroundColor" or fg == "luminance" or fg == "luminanceAlpha":
            blend[bg][fg].AddInputConnection(eval(fg + '.GetOutputPort()'))
            blend[bg][fg].SetOpacity(1, 0.8)

        mapper.update({bg: {fg: vtk.vtkImageMapper()}})
        mapper[bg][fg].SetInputConnection(blend[bg][fg].GetOutputPort())
        mapper[bg][fg].SetColorWindow(255)
        mapper[bg][fg].SetColorLevel(127.5)

        actor.update({bg: {fg: vtk.vtkActor2D()}})
        actor[bg][fg].SetMapper(mapper[bg][fg])

        imager.update({bg: {fg: vtk.vtkRenderer()}})
        imager[bg][fg].AddActor2D(actor[bg][fg])
        imager[bg][fg].SetViewport(column * deltaX, row * deltaY,
                                   (column + 1) * deltaX, (row + 1) * deltaY)

        renWin.AddRenderer(imager[bg][fg])

        column += 1
Exemple #41
0
    def testThreshold(self):

        # This script is for testing the 3D threshold filter.

        # Image pipeline

        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(192, 256)

        reader = vtk.vtkImageReader()
        reader.ReleaseDataFlagOff()
        reader.SetDataByteOrderToLittleEndian()
        reader.SetDataExtent(0, 63, 0, 63, 1, 93)
        reader.SetDataSpacing(3.2, 3.2, 1.5)
        reader.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
        reader.SetDataMask(0x7fff)

        outputtype = ["SignedChar", "UnsignedChar", "Long", "UnsignedLong", "Int", "UnsignedInt",
                        "Short", "UnsignedShort", "Double", "Float", "Double", "Float"]
        replacein = ["ReplaceInOn", "ReplaceInOff"]
        replaceout = ["ReplaceOutOn", "ReplaceOutOff"]
        thresholds = ["ThresholdByLower(800)", "ThresholdByUpper(1200)", "ThresholdBetween(800, 1200)"]

        thresh = list()
        map = list()
        act = list()
        ren = list()

        k = 0
        for rin in replacein:
            for rout in replaceout:
                for t in thresholds:

                    thresh.append(vtk.vtkImageThreshold())
                    thresh[k].SetInValue(2000)
                    thresh[k].SetOutValue(0)
                    eval('thresh[k].' + rin + '()')
                    eval('thresh[k].' + rout + '()')
                    thresh[k].SetInputConnection(reader.GetOutputPort())
                    eval('thresh[k].' + t)
                    eval('thresh[k].SetOutputScalarTypeTo' + outputtype[k] + '()')

                    map.append(vtk.vtkImageMapper())
                    map[k].SetInputConnection(thresh[k].GetOutputPort())
                    if k < 3:
                        map[k].SetColorWindow(255)
                        map[k].SetColorLevel(127.5)
                    else:
                        map[k].SetColorWindow(2000)
                        map[k].SetColorLevel(1000)

                    act.append(vtk.vtkActor2D())
                    act[k].SetMapper(map[k])

                    ren.append(vtk.vtkRenderer())
                    ren[k].AddActor2D(act[k])

                    renWin.AddRenderer(ren[k])

                    k += 1

        ren[0].SetViewport(0, 0, .33333, .25)
        ren[1].SetViewport(.33333, 0, .66667, .25)
        ren[2].SetViewport(.66667, 0, 1, .25)
        ren[3].SetViewport(0, .25, .33333, .5)
        ren[4].SetViewport(.33333, .25, .66667, .5)
        ren[5].SetViewport(.66667, .25, 1, .5)
        ren[6].SetViewport(0, .5, .33333, .75)
        ren[7].SetViewport(.33333, .5, .66667, .75)
        ren[8].SetViewport(.66667, .5, 1, .75)
        ren[9].SetViewport(0, .75, .33333, 1)
        ren[10].SetViewport(.33333, .75, .66667, 1)
        ren[11].SetViewport(.66667, .75, 1, 1)

        # render and interact with data

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

        img_file = "TestThreshold.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #42
0
    def __init__(self, in_source):
        self.mapper = vtk.vtkImageMapper()
        self.mapper.SetInputConnection(in_source.GetOutputPort())

        self.actor = vtk.vtkActor2D()
        self.actor.SetMapper(self.mapper)
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

#
# display text over an image
#
ellipse = vtk.vtkImageEllipsoidSource()
mapImage = vtk.vtkImageMapper()
mapImage.SetInputConnection(ellipse.GetOutputPort())
mapImage.SetColorWindow(255)
mapImage.SetColorLevel(127.5)
img = vtk.vtkActor2D()
img.SetMapper(mapImage)
mapText = vtk.vtkTextMapper()
mapText.SetInput("Text Overlay")
mapText.GetTextProperty().SetFontSize(15)
mapText.GetTextProperty().SetColor(0,1,1)
mapText.GetTextProperty().BoldOn()
mapText.GetTextProperty().ShadowOn()
txt = vtk.vtkActor2D()
txt.SetMapper(mapText)
txt.SetPosition(138,128)
ren1 = vtk.vtkRenderer()
ren1.AddActor2D(img)
ren1.AddActor2D(txt)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
Exemple #44
0
 def SetMapper(self):
     self.mapper = vtk.vtkImageMapper()
     self.SetColorLevel()
     self.SetColorWindow()
stencil1.SetInputConnection(reader.GetOutputPort())
stencil1.SetBackgroundInputData(shiftScale.GetOutput())
stencil1.SetStencilConnection(roiStencil1.GetOutputPort())
stencil2 = vtk.vtkImageStencil()
stencil2.SetInputConnection(reader.GetOutputPort())
stencil2.SetBackgroundInputData(shiftScale.GetOutput())
stencil2.SetStencilConnection(roiStencil2.GetOutputPort())
stencil3 = vtk.vtkImageStencil()
stencil3.SetInputConnection(reader.GetOutputPort())
stencil3.SetBackgroundInputData(shiftScale.GetOutput())
stencil3.SetStencilConnection(roiStencil3.GetOutputPort())
stencil4 = vtk.vtkImageStencil()
stencil4.SetInputConnection(reader.GetOutputPort())
stencil4.SetBackgroundInputData(shiftScale.GetOutput())
stencil4.SetStencilConnection(roiStencil4.GetOutputPort())
mapper1 = vtk.vtkImageMapper()
mapper1.SetInputConnection(stencil1.GetOutputPort())
mapper1.SetColorWindow(2000)
mapper1.SetColorLevel(1000)
mapper1.SetZSlice(0)
mapper2 = vtk.vtkImageMapper()
mapper2.SetInputConnection(stencil2.GetOutputPort())
mapper2.SetColorWindow(2000)
mapper2.SetColorLevel(1000)
mapper2.SetZSlice(0)
mapper3 = vtk.vtkImageMapper()
mapper3.SetInputConnection(stencil3.GetOutputPort())
mapper3.SetColorWindow(2000)
mapper3.SetColorLevel(1000)
mapper3.SetZSlice(0)
mapper4 = vtk.vtkImageMapper()
    def testAllMaskBits(self):

        # This script calculates the luminance of an image

        renWin = vtk.vtkRenderWindow()


        # Image pipeline

        image1 = vtk.vtkTIFFReader()
        image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")

        # "beach.tif" image contains ORIENTATION tag which is
        # ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
        # reader parses this tag and sets the internal TIFF image
        # orientation accordingly.  To overwrite this orientation with a vtk
        # convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
        # SetOrientationType method with parameter value of 4.
        image1.SetOrientationType(4)

        shrink = vtk.vtkImageShrink3D()
        shrink.SetInputConnection(image1.GetOutputPort())
        shrink.SetShrinkFactors(2, 2, 1)

        operators = ["ByPass", "And", "Nand", "Xor", "Or", "Nor"]

        operator = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for idx, op in enumerate(operators):
            if op != "ByPass":
                operator.update({idx: vtk.vtkImageMaskBits()})
                operator[idx].SetInputConnection(shrink.GetOutputPort())
                eval('operator[' + str(idx) + '].SetOperationTo' + op + '()')
                operator[idx].SetMasks(255, 255, 0)

            mapper.update({idx: vtk.vtkImageMapper()})
            if op != "ByPass":
                mapper[idx].SetInputConnection(operator[idx].GetOutputPort())
            else:
                mapper[idx].SetInputConnection(shrink.GetOutputPort())
            mapper[idx].SetColorWindow(255)
            mapper[idx].SetColorLevel(127.5)

            actor.update({idx: vtk.vtkActor2D()})
            actor[idx].SetMapper(mapper[idx])

            imager.update({idx: vtk.vtkRenderer()})
            imager[idx].AddActor2D(actor[idx])

            renWin.AddRenderer(imager[idx])


        column = 0
        row = 0
        deltaX = 1.0 / 3.0
        deltaY = 1.0 / 2.0

        for idx in range(len(operators)):
            imager[idx].SetViewport(column * deltaX, row * deltaY, (column + 1) * deltaX, (row + 1) * deltaY)
            column += 1
            if column > 2:
                column = 0
                row += 1

        renWin.SetSize(384, 256)

        # render and interact with data

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

        img_file = "TestAllMaskBits.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #47
0
reslice2.SetOutputExtent(0, 127, 0, 127, 0, 0)
reslice3 = vtk.vtkImageReslice()
reslice3.SetInputConnection(reader.GetOutputPort())
reslice3.WrapOn()
reslice3.SetInterpolationModeToNearestNeighbor()
reslice3.SetOutputSpacing(2.0, 2.0, 1.5)
reslice3.SetOutputOrigin(-32, -32, 40)
reslice3.SetOutputExtent(0, 127, 0, 127, 0, 0)
reslice4 = vtk.vtkImageReslice()
reslice4.SetInputConnection(reader.GetOutputPort())
reslice4.WrapOn()
reslice4.SetInterpolationModeToLinear()
reslice4.SetOutputSpacing(3.2, 3.2, 1.5)
reslice4.SetOutputOrigin(-102.4, -102.4, 40)
reslice4.SetOutputExtent(0, 127, 0, 127, 0, 0)
mapper1 = vtk.vtkImageMapper()
mapper1.SetInputConnection(reslice1.GetOutputPort())
mapper1.SetColorWindow(2000)
mapper1.SetColorLevel(1000)
mapper1.SetZSlice(0)
mapper2 = vtk.vtkImageMapper()
mapper2.SetInputConnection(reslice2.GetOutputPort())
mapper2.SetColorWindow(2000)
mapper2.SetColorLevel(1000)
mapper2.SetZSlice(0)
mapper3 = vtk.vtkImageMapper()
mapper3.SetInputConnection(reslice3.GetOutputPort())
mapper3.SetColorWindow(2000)
mapper3.SetColorLevel(1000)
mapper3.SetZSlice(0)
mapper4 = vtk.vtkImageMapper()
Exemple #48
0
        blend.update({bg:{fg:vtk.vtkImageBlend()}})
        blend[bg][fg].AddInputConnection(eval(bg + '.GetOutputPort()'))
        blend[bg][fg].SetBlendModeToCompound()
        if bg == "backgroundAlpha" or bg == "backgroundColor":
            blend[bg][fg].AddInputConnection(eval(fg + '.GetOutputPort()'))
            if bg == "backgroundAlpha":
                blend[bg][fg].SetCompoundAlpha(True)
                blend[bg][fg].SetOpacity(0, 0.5)
                blend[bg][fg].SetOpacity(1, 0.5)
            else:
                blend[bg][fg].SetOpacity(1, 0.8)
        elif fg == "luminance" or fg == "luminanceAlpha":
            blend[bg][fg].AddInputConnection(eval(fg + '.GetOutputPort()'))
            blend[bg][fg].SetOpacity(1, 0.8)

        mapper.update({bg:{fg:vtk.vtkImageMapper()}})
        mapper[bg][fg].SetInputConnection(blend[bg][fg].GetOutputPort())
        mapper[bg][fg].SetColorWindow(255)
        mapper[bg][fg].SetColorLevel(127.5)

        actor.update({bg:{fg:vtk.vtkActor2D()}})
        actor[bg][fg].SetMapper(mapper[bg][fg])

        imager.update({bg:{fg:vtk.vtkRenderer()}})
        imager[bg][fg].AddActor2D(actor[bg][fg])
        imager[bg][fg].SetViewport(column * deltaX, row * deltaY, (column + 1) * deltaX, (row + 1) * deltaY)
        imager[bg][fg].SetBackground(0.3, 0.3, 0.3)

        renWin.AddRenderer(imager[bg][fg])

        column += 1