예제 #1
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)
예제 #2
0
    def __set_up_drawing_actor(self):
        lut = vtk.vtkLookupTable()
        lut.SetRange(0, 1000)
        lut.SetValueRange(0.0, 1.0)  # from black to white
        lut.SetSaturationRange(0.0, 0.0)  # no color saturation
        lut.SetRampToLinear()
        lut.Build()

        # Map the image through the lookup table
        color = vtk.vtkImageMapToColors()
        color.SetLookupTable(lut)
        color.SetInputConnection(self.filter.GetOutputPort())

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

        # mask
        mask_lut = vtk.vtkLookupTable()
        mask_lut.SetNumberOfTableValues(2)
        mask_lut.SetTableValue(0, 0.0, 0.0, 0.0, 1.0)
        mask_lut.SetTableValue(1, 1.0, 0.0, 0.0, 1.0)

        color = vtk.vtkImageMapToColors()
        color.SetLookupTable(mask_lut)
        color.SetInputConnection(self.mask_filter.GetOutputPort())

        self.mask_actor = vtk.vtkImageActor()
        self.mask_actor.GetMapper().SetInputConnection(color.GetOutputPort())
        self.mask_actor.SetOpacity(0.7)
예제 #3
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)
예제 #4
0
    def __init__(self,
                 world_to_slice,
                 image,
                 display_coordinates="physical",
                 colormap=None,
                 opacity=1.0):

        ############################
        # Property-related members #
        ############################

        self._actor = vtkImageActor()

        ###################
        # Private members #
        ###################

        self._image_map_to_colors = vtkImageMapToColors()

        ######################
        # Initialize members #
        ######################

        super(ImageLayer,
              self).__init__(world_to_slice, image, display_coordinates,
                             colormap, opacity)

        self._image_map_to_colors.SetInputConnection(
            self._change_information.GetOutputPort())
        self._actor.SetInput(self._image_map_to_colors.GetOutput())
        self._actor.InterpolateOff()
예제 #5
0
def _makeImagePlane(imageData) :
    ''' Takes a vtkImageData object and
        returns a plane textured with that image
        and a camera for the background renderer
        http://www.vtk.org/Wiki/VTK/Examples/Cxx/Images/BackgroundImage
        was the basis for this function
    '''
    imageActor = vtk.vtkImageActor()
    
    if vtk.VTK_MAJOR_VERSION <= 5 :
        imageActor.SetInput(imageData)
    else :
        imageActor.SetInputData(imageData)

    origin = imageData.GetOrigin()
    spacing = imageData.GetSpacing()
    extent = imageData.GetExtent()

    camera = vtk.vtkCamera()
    camera.ParallelProjectionOn()

    xc = origin[0] + 0.5*(extent[0] + extent[1])*spacing[0]
    yc = origin[1] + 0.5*(extent[2] + extent[3])*spacing[1]
    yd = (extent[3] - extent[2] + 1)*spacing[1]
    d = camera.GetDistance()
    camera.SetParallelScale(0.5*yd)
    camera.SetFocalPoint(xc,yc,0.0)
    camera.SetPosition(xc,yc,d)

    return camera, imageActor
예제 #6
0
    def __init__(self, image_handler):
        self._name = 'Image View'
        self._view = PythonQt.dd.ddQVTKWidgetView()
        self._image_handler = image_handler

        self._image = vtk.vtkImageData()
        self._prev_attrib = None

        # Initialize the view.
        self._view.installImageInteractor()
        # Add actor.
        self._image_actor = vtk.vtkImageActor()
        vtk_SetInputData(self._image_actor, self._image)
        self._image_actor.SetVisibility(False)
        self._view.renderer().AddActor(self._image_actor)

        self._view.orientationMarkerWidget().Off()
        self._view.backgroundRenderer().SetBackground(0, 0, 0)
        self._view.backgroundRenderer().SetBackground2(0, 0, 0)

        self._depth_mapper = None

        # Add timer.
        self._render_timer = TimerCallback(
            targetFps=60,
            callback=self.render)
        self._render_timer.start()
예제 #7
0
def _makeImagePlane(imageData):
    ''' Takes a vtkImageData object and
        returns a plane textured with that image
        and a camera for the background renderer
        http://www.vtk.org/Wiki/VTK/Examples/Cxx/Images/BackgroundImage
        was the basis for this function
    '''
    imageActor = vtk.vtkImageActor()

    if vtk.VTK_MAJOR_VERSION <= 5:
        imageActor.SetInput(imageData)
    else:
        imageActor.SetInputData(imageData)

    origin = imageData.GetOrigin()
    spacing = imageData.GetSpacing()
    extent = imageData.GetExtent()

    camera = vtk.vtkCamera()
    camera.ParallelProjectionOn()

    xc = origin[0] + 0.5 * (extent[0] + extent[1]) * spacing[0]
    yc = origin[1] + 0.5 * (extent[2] + extent[3]) * spacing[1]
    yd = (extent[3] - extent[2] + 1) * spacing[1]
    d = camera.GetDistance()
    camera.SetParallelScale(0.5 * yd)
    camera.SetFocalPoint(xc, yc, 0.0)
    camera.SetPosition(xc, yc, d)

    return camera, imageActor
예제 #8
0
    def create_slice_window(self):
        renderer = vtk.vtkRenderer()
        renderer.SetLayer(0)
        cam = renderer.GetActiveCamera()

        overlay_renderer = vtk.vtkRenderer()
        overlay_renderer.SetLayer(1)
        overlay_renderer.SetActiveCamera(cam)
        overlay_renderer.SetInteractive(0)

        self.interactor.GetRenderWindow().SetNumberOfLayers(2)
        self.interactor.GetRenderWindow().AddRenderer(overlay_renderer)
        self.interactor.GetRenderWindow().AddRenderer(renderer)

        actor = vtk.vtkImageActor()
        # TODO: Create a option to let the user set if he wants to interpolate
        # the slice images.
        #actor.InterpolateOff()
        slice_data = sd.SliceData()
        slice_data.SetOrientation(self.orientation)
        slice_data.renderer = renderer
        slice_data.overlay_renderer = overlay_renderer
        slice_data.actor = actor
        slice_data.SetBorderStyle(sd.BORDER_ALL)
        renderer.AddActor(actor)
        renderer.AddActor(slice_data.text.actor)
        renderer.AddViewProp(slice_data.box_actor)
        return slice_data
예제 #9
0
 def put_img_on_canvas(self,filename,zoom=1,xOffset=0,yOffset=0,*args,**kargs):
   self.hideGUI()
   readerFactory = vtk.vtkImageReader2Factory()
   reader = readerFactory.CreateImageReader2(filename)
   reader.SetFileName(filename)
   reader.Update()
   imageData = reader.GetOutput()
   a = vtk.vtkImageActor()
   a.GetMapper().SetInputConnection(reader.GetOutputPort())
   origin = imageData.GetOrigin()
   spc = imageData.GetSpacing()
   ext = imageData.GetExtent()
   ren = self.createRenderer()
   cam = ren.GetActiveCamera()
   cam.ParallelProjectionOn()
   width = (ext[1]-ext[0])*spc[0]
   height = (ext[3]-ext[2])*spc[1]
   xoff = width*xOffset/zoom/200.
   yoff = height*yOffset/zoom/200.
   xc  = origin[0] + .5*(ext[0]+ext[1])*spc[0]
   yc  = origin[1] + .5*(ext[2]+ext[3])*spc[1]
   yd = (ext[3]-ext[2])*spc[1]
   d = cam.GetDistance()
   cam.SetParallelScale(.5*yd/zoom)
   cam.SetFocalPoint(xc+xoff,yc+yoff,0.)
   cam.SetPosition(xc+xoff,yc+yoff,d)
   ren.AddActor(a)
   layer = max(self.renWin.GetNumberOfLayers() - 2, 0)
   ren.SetLayer(layer)
   self.renWin.AddRenderer(ren)
   self.showGUI(render=False)
   self.renWin.Render()
   return
예제 #10
0
 def put_img_on_canvas(self,filename,zoom=1,xOffset=0,yOffset=0,*args,**kargs):
   readerFactory = vtk.vtkImageReader2Factory()
   reader = readerFactory.CreateImageReader2(filename)
   reader.SetFileName(filename)
   reader.Update()
   imageData = reader.GetOutput()
   a = vtk.vtkImageActor()
   a.GetMapper().SetInputConnection(reader.GetOutputPort())
   origin = imageData.GetOrigin()
   spc = imageData.GetSpacing()
   ext = imageData.GetExtent()
   ren = vtk.vtkRenderer()
   r,g,b = self.canvas.backgroundcolor
   ren.SetBackground(r/255.0, g/255.0, b/255.0)
   cam = ren.GetActiveCamera()
   cam.ParallelProjectionOn()
   width = (ext[1]-ext[0])*spc[0]
   height = (ext[3]-ext[2])*spc[1]
   xoff = width*xOffset/zoom/200.
   yoff = height*yOffset/zoom/200.
   xc  = origin[0] + .5*(ext[0]+ext[1])*spc[0]
   yc  = origin[1] + .5*(ext[2]+ext[3])*spc[1]
   yd = (ext[3]-ext[2])*spc[1]
   d = cam.GetDistance()
   cam.SetParallelScale(.5*yd/zoom)
   cam.SetFocalPoint(xc+xoff,yc+yoff,0.)
   cam.SetPosition(xc+xoff,yc+yoff,d)
   ren.AddActor(a)
   self.renWin.AddRenderer(ren)
   self.renWin.Render()
   return
예제 #11
0
def main(args):

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

    print(img)

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

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

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

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetInteractorStyle(vtk.vtkInteractorStyleImage())
    renderWindowInteractor.AddObserver("KeyPressEvent", Keypress)
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderWindowInteractor.Initialize()
    renderWindowInteractor.Start()
예제 #12
0
    def ShowSlice(self, index = 0):
        dicom = self.dicom_list[index]

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

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

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

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

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

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

        rdicom = vtkgdcm.vtkGDCMImageReader()
        rdicom.SetFileName(dicom.image.file)
        rdicom.Update()

        # ADJUST CONTRAST
        window_level = dicom.image.level
        window_width = dicom.image.window
        colorer = vtk.vtkImageMapToWindowLevelColors()
        colorer.SetInputConnection(rdicom.GetOutputPort())
        colorer.SetWindow(float(window_width))
        colorer.SetLevel(float(window_level))
        colorer.Update()

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

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

        # Setting slider position
        self.slider.SetValue(index)
예제 #13
0
    def __init__(self, ren):
        self.volume = self.LoadVolume()
        self.ren = ren

        # next initialize the pipeline
        self.slicer = vtk.vtkImageReslice()
        self.slicer.SetInput( self.volume )
        self.slicer.SetOutputDimensionality(2)

        # the next filter provides a mechanism for slice selection
        self.selector = SliceSelector(self.volume)
        self.slicer.SetResliceAxes( self.selector.GetDirectionCosines() )
        self.slicer.SetResliceAxesOrigin( self.selector.GetAxesOrigin() )

        # setup link for adjusting the contrast of the image
        r = self.volume.GetScalarRange()
        self.lutBuilder = LUTBuilder(r[0],r[1],1)
        lut = self.lutBuilder.Build()

        self.colors = vtk.vtkImageMapToColors()
        self.colors.SetInputConnection( self.slicer.GetOutputPort() )
        self.colors.SetLookupTable( lut )

        self.actor = vtk.vtkImageActor()
        self.actor.SetInput( self.colors.GetOutput() )
예제 #14
0
 def put_img_on_canvas(self,filename,zoom=1,xOffset=0,yOffset=0,*args,**kargs):
   self.hideGUI()
   readerFactory = vtk.vtkImageReader2Factory()
   reader = readerFactory.CreateImageReader2(filename)
   reader.SetFileName(filename)
   reader.Update()
   imageData = reader.GetOutput()
   a = vtk.vtkImageActor()
   a.GetMapper().SetInputConnection(reader.GetOutputPort())
   origin = imageData.GetOrigin()
   spc = imageData.GetSpacing()
   ext = imageData.GetExtent()
   ren = self.createRenderer()
   cam = ren.GetActiveCamera()
   cam.ParallelProjectionOn()
   width = (ext[1]-ext[0])*spc[0]
   height = (ext[3]-ext[2])*spc[1]
   xoff = width*xOffset/zoom/200.
   yoff = height*yOffset/zoom/200.
   xc  = origin[0] + .5*(ext[0]+ext[1])*spc[0]
   yc  = origin[1] + .5*(ext[2]+ext[3])*spc[1]
   yd = (ext[3]-ext[2])*spc[1]
   d = cam.GetDistance()
   cam.SetParallelScale(.5*yd/zoom)
   cam.SetFocalPoint(xc+xoff,yc+yoff,0.)
   cam.SetPosition(xc+xoff,yc+yoff,d)
   ren.AddActor(a)
   layer = max(self.renWin.GetNumberOfLayers() - 2, 0)
   ren.SetLayer(layer)
   self.renWin.AddRenderer(ren)
   self.showGUI(render=False)
   self.renWin.Render()
   return
예제 #15
0
 def removeActor(self):
     logging.debug("In VTKImageView::removeActor()")
     self.render.RemoveActor(self.actor)
     self.actor = vtk.vtkImageActor()
     self.render.AddActor(self.actor)
     self.render.ResetCamera()
     self.Render()
    def __init__(self, source, orientation, opacity=1.0):

        self.reslice = vtk.vtkImageReslice()
        self.reslice.SetInputData(source)
        self.reslice.SetOutputDimensionality(2)
        self.reslice.SetResliceAxes(orientation)
        self.reslice.SetInterpolationModeToNearestNeighbor()

        # Set lookup table
        color_transfer = vtk.vtkDiscretizableColorTransferFunction()
        alpha_transfer = vtk.vtkPiecewiseFunction()
        color_transfer.AddRGBPoint(0, 0., 0., 0.)  # Background
        alpha_transfer.AddPoint(0, 0)  # Background
        for i, organ in enumerate(Settings.labels):
            color_transfer.AddRGBPoint(Settings.labels[organ]['value'],
                                       *Settings.labels[organ]['rgb'])
            if organ in Settings.organs:
                alpha_transfer.AddPoint(Settings.labels[organ]['value'],
                                        opacity)
            else:
                alpha_transfer.AddPoint(Settings.labels[organ]['value'], 0.)
        color_transfer.SetScalarOpacityFunction(alpha_transfer)
        color_transfer.EnableOpacityMappingOn()

        # Map the image through the lookup table
        self.color = vtk.vtkImageMapToColors()
        self.color.SetLookupTable(color_transfer)
        self.color.SetInputConnection(self.reslice.GetOutputPort())

        # Display the image
        self.actor = vtk.vtkImageActor()
        self.actor.GetMapper().SetInputConnection(self.color.GetOutputPort())
예제 #17
0
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: no Image.')

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        if self.Type == 'freehand':
            self.ImageTracerWidget = vtk.vtkImageTracerWidget()
        elif self.Type == 'contour':
            self.ImageTracerWidget = vtk.vtkContourWidget()
        self.ImageTracerWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)

        self.SliderWidget = vtk.vtkSliderWidget()
        self.SliderWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)

        self.ImageActor = vtk.vtkImageActor()

        self.vmtkRenderer.RenderWindowInteractor.AddObserver(
            "KeyPressEvent", self.Keypress)

        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
예제 #18
0
    def Execute(self):

        if self.Image == None:
            self.PrintError("Error: no Image.")

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self)

        if self.Type == "freehand":
            self.ImageTracerWidget = vtk.vtkImageTracerWidget()
        elif self.Type == "contour":
            self.ImageTracerWidget = vtk.vtkContourWidget()
        self.ImageTracerWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        self.SliderWidget = vtk.vtkSliderWidget()
        self.SliderWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        self.ImageActor = vtk.vtkImageActor()

        self.vmtkRenderer.AddKeyBinding("n", "Next.", self.NextCallback)
        self.vmtkRenderer.AddKeyBinding("p", "Previous.", self.PreviousCallback)
        self.vmtkRenderer.AddKeyBinding("i", "Interact.", self.InteractCallback)

        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
예제 #19
0
    def create_slice_window(self):
        renderer = vtk.vtkRenderer()
        renderer.SetLayer(0)
        cam = renderer.GetActiveCamera()

        overlay_renderer = vtk.vtkRenderer()
        overlay_renderer.SetLayer(1)
        overlay_renderer.SetActiveCamera(cam)
        overlay_renderer.SetInteractive(0)
        
        self.interactor.GetRenderWindow().SetNumberOfLayers(2)
        self.interactor.GetRenderWindow().AddRenderer(overlay_renderer)
        self.interactor.GetRenderWindow().AddRenderer(renderer)

        actor = vtk.vtkImageActor()
        # TODO: Create a option to let the user set if he wants to interpolate
        # the slice images.
        #actor.InterpolateOff()
        slice_data = sd.SliceData()
        slice_data.SetOrientation(self.orientation)
        slice_data.renderer = renderer
        slice_data.overlay_renderer = overlay_renderer
        slice_data.actor = actor
        slice_data.SetBorderStyle(sd.BORDER_ALL)
        renderer.AddActor(actor)
        renderer.AddActor(slice_data.text.actor)
        renderer.AddViewProp(slice_data.box_actor)
        return slice_data
예제 #20
0
def main():
    filename = get_program_parameters()

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

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

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

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

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

    render_window_interactor.SetInteractorStyle(style)

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

    render_window_interactor.Start()
예제 #21
0
    def __init__(self, data_dir, PW, reader):

        # Create a greyscale lookup table
        table2 = vtk.vtkLookupTable()
        table2.SetRange(2440, 2800)  # image intensity range
        table2.SetValueRange(0.0, 1)  # from black to white
        table2.SetAlphaRange(1.0, 1.0)
        table2.SetHueRange(0.0, 0.1)
        table2.SetSaturationRange(0.0, 0.2)  # no color saturation
        table2.SetRampToLinear()
        table2.Build()

        grx = PW.GetResliceAxes()

        reslice = vtk.vtkImageReslice()
        reslice.SetInputConnection(reader.GetOutputPort())
        reslice.SetOutputDimensionality(2)
        reslice.SetResliceAxes(grx)
        reslice.SetSlabModeToMax()
        reslice.SetSlabNumberOfSlices(30)
        reslice.SetInterpolationModeToLinear()
        reslice.Update()
        # Map the image through the lookup table
        color = vtk.vtkImageMapToColors()
        color.SetLookupTable(table2)
        color.SetInputConnection(reslice.GetOutputPort())
        actor = vtk.vtkImageActor()
        actor.GetMapper().SetInputConnection(color.GetOutputPort())

        self.actor = actor
예제 #22
0
    def __init__(self):
        # Objects for volume rendering
        self.volume = vtk.vtkVolume()
        self.volumeMapper = vtk.vtkSmartVolumeMapper()
        self.volumeProperty = vtk.vtkVolumeProperty()

        # Objects for slice rendering
        self.sliceActor = vtk.vtkImageActor()
        self.sliceMapper = vtk.vtkImageResliceMapper()
        self.sliceProperty = vtk.vtkImageProperty()

        # Objects for importing and reslicing the data
        self.importer = [vtk.vtkImageImport()]
        self.slice = [vtk.vtkImageResliceToColors()]

        # Objects that point to the output algorithms
        # These must be specified at run time by the implementing class
        self.output = None
        self.sliceOutput = None

        # Some properties of the data
        self.numberOfDataSets = 0
        self.numberOfTimeFrames = 0
        self.currentTimeFrame = 0
        self.dimensions = [0, 0, 0]
예제 #23
0
    def __init__(self, image_handler):
        self._name = 'Image View'
        self._view = PythonQt.dd.ddQVTKWidgetView()
        self._image_handler = image_handler

        self._image = vtk.vtkImageData()
        self._prev_attrib = None

        # Initialize the view.
        self._view.installImageInteractor()
        # Add actor.
        self._image_actor = vtk.vtkImageActor()
        vtk_SetInputData(self._image_actor, self._image)
        self._image_actor.SetVisibility(False)
        self._view.renderer().AddActor(self._image_actor)

        self._view.orientationMarkerWidget().Off()
        self._view.backgroundRenderer().SetBackground(0, 0, 0)
        self._view.backgroundRenderer().SetBackground2(0, 0, 0)

        self._depth_mapper = None

        # Add timer.
        self._render_timer = TimerCallback(targetFps=60, callback=self.render)
        self._render_timer.start()
예제 #24
0
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: no Image.')

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self) 

        if self.Type == 'freehand':
            self.ImageTracerWidget = vtk.vtkImageTracerWidget()
        elif self.Type == 'contour':
            self.ImageTracerWidget = vtk.vtkContourWidget()
        self.ImageTracerWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        self.SliderWidget = vtk.vtkSliderWidget()
        self.SliderWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        self.ImageActor = vtk.vtkImageActor()

        self.vmtkRenderer.AddKeyBinding('n','Next.',self.NextCallback)
        self.vmtkRenderer.AddKeyBinding('p','Previous.',self.PreviousCallback)
        self.vmtkRenderer.AddKeyBinding('i','Interact.', self.InteractCallback)

        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
예제 #25
0
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: no Image.')

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self)

        if self.Type == 'freehand':
            self.ImageTracerWidget = vtk.vtkImageTracerWidget()
        elif self.Type == 'contour':
            self.ImageTracerWidget = vtk.vtkContourWidget()
        self.ImageTracerWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)

        self.SliderWidget = vtk.vtkSliderWidget()
        self.SliderWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)

        self.ImageActor = vtk.vtkImageActor()

        self.vmtkRenderer.AddKeyBinding('n', 'Next.', self.NextCallback)
        self.vmtkRenderer.AddKeyBinding('p', 'Previous.',
                                        self.PreviousCallback)
        self.vmtkRenderer.AddKeyBinding('i', 'Interact.',
                                        self.InteractCallback)

        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
예제 #26
0
    def __init__(self):

        self.vtk_actor = vtk.vtkImageActor()

        # Need to keep reference to the image
        self.image = None
        self.vtk_image_data = None
예제 #27
0
    def __init__(self):
        """ Class constructor """

        # Initialize the OpenCV object responsible for acquire the images
        self.capture = cv2.VideoCapture(0)

        # Initialize the VTK object that is going to translate the image
        self.image = vtk.vtkImageImport()
        self.image.SetDataScalarTypeToUnsignedChar()

        # Three color layers
        self.image.SetNumberOfScalarComponents(3)

        # Image dimensions
        width, height = self.size
        self.image.SetDataExtent(0, width-1, 0, height-1, 0, 0)
        self.image.SetWholeExtent(0, width-1, 0, height-1, 0, 0)
        self.update()

        # Initialize render and assign the deepest layer
        self.render = vtk.vtkRenderer()
        self.render.SetLayer(0)
        self.render.InteractiveOff()

        # In VTK renders objects are shown through actors, like in a movie
        self.image_actor = vtk.vtkImageActor()
        image_port = self.image.GetOutputPort()
        self.image_actor.GetMapper().SetInputConnection(image_port)

        # Place actor into action
        self.render.AddActor(self.image_actor)
예제 #28
0
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: no Image.')

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        if self.Type == 'freehand':
            self.ImageTracerWidget = vtk.vtkImageTracerWidget()
        elif self.Type == 'contour':
            self.ImageTracerWidget = vtk.vtkContourWidget()
        self.ImageTracerWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        self.SliderWidget = vtk.vtkSliderWidget()
        self.SliderWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        self.ImageActor = vtk.vtkImageActor()

        self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.Keypress)

        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
예제 #29
0
    def __init__(self, filename, visibility=True, opacity=1.0):
        """
        Creates an image model, represented as a vtkImageActor.
        :param filename: filename, should be .png in the first instance.
        :param visibility: [True/False] boolean
        :param opacity: [0, 1]
        """
        super(VTKImageModel, self).__init__((1.0, 1.0, 1.0), visibility,
                                            opacity)

        self.source_file = None
        self.reader = None
        self.source = None

        if filename is not None:
            self.reader = vtk.vtkPNGReader()
            self.reader.SetFileName(filename)
            self.reader.Update()
            self.source = self.reader.GetOutput()
            self.source_file = filename
            self.name = os.path.basename(self.source_file)
        else:
            self.source = vtk.vtkImageData()
            self.name = ""

        self.actor = vtk.vtkImageActor()
        self.actor.SetInputData(self.source)
예제 #30
0
    def ShowSlice(self, index=0):
        dicom = self.dicom_list[index]

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

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

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

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

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

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

        rdicom = vtkgdcm.vtkGDCMImageReader()
        rdicom.SetFileName(dicom.image.file)
        rdicom.Update()

        # ADJUST CONTRAST
        window_level = dicom.image.level
        window_width = dicom.image.window
        colorer = vtk.vtkImageMapToWindowLevelColors()
        colorer.SetInputConnection(rdicom.GetOutputPort())
        colorer.SetWindow(float(window_width))
        colorer.SetLevel(float(window_level))
        colorer.Update()

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

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

        # Setting slider position
        self.slider.SetValue(index)
    def __init__(self, im_data, orie='Sagittal'):

        # orie
        self.orie = orie

        source = im_data.im_src

        self.translation = [0, 0]

        # (xMin, xMax, yMin, yMax, zMin, zMax)
        self.sizes = source.GetExecutive().GetWholeExtent(
            source.GetOutputInformation(0))
        self.spacing = source.GetOutput().GetSpacing()
        self.origin = source.GetOutput().GetOrigin()

        # include (xSpacing, ySpacing, zSpacing) to get the correct slices

        self.center = [
            self.origin[0] + self.spacing[0] * 0.5 *
            (self.sizes[0] + self.sizes[1]), self.origin[1] +
            self.spacing[1] * 0.5 * (self.sizes[2] + self.sizes[3]),
            self.origin[2] + self.spacing[2] * 0.5 *
            (self.sizes[4] + self.sizes[5])
        ]

        self.slices = [
            self.center[0] - self.spacing[0] * 0.5 *
            (self.sizes[0] + self.sizes[1]), self.center[0] +
            self.spacing[0] * 0.5 * (self.sizes[0] + self.sizes[1]),
            self.center[1] - self.spacing[1] * 0.5 *
            (self.sizes[2] + self.sizes[3]), self.center[1] +
            self.spacing[1] * 0.5 * (self.sizes[2] + self.sizes[3]),
            self.center[2] - self.spacing[2] * 0.5 *
            (self.sizes[4] + self.sizes[5]), self.center[2] +
            self.spacing[2] * 0.5 * (self.sizes[4] + self.sizes[5])
        ]

        self.reslice = vtk.vtkImageReslice()
        self.reslice.SetInputConnection(source.GetOutputPort())
        self.reslice.SetOutputDimensionality(2)
        self.reslice.SetResliceAxes(self.get_orie_mat())
        self.reslice.SetInterpolationModeToLinear()

        # Create a greyscale lookup table
        self.table = vtk.vtkLookupTable()
        self.table.SetRange(0, 1500)  # image intensity range
        self.table.SetValueRange(0.0, 0.7)  # from black to white
        self.table.SetSaturationRange(0.0, 0.0)  # no color saturation
        self.table.SetRampToLinear()
        self.table.Build()

        # Map the image through the lookup table
        self.color = vtk.vtkImageMapToColors()
        self.color.SetLookupTable(self.table)
        self.color.SetInputConnection(self.reslice.GetOutputPort())

        # Display the image
        self.actor = vtk.vtkImageActor()
        self.actor.GetMapper().SetInputConnection(self.color.GetOutputPort())
예제 #32
0
 def vtkSagittalSlice(self):
    """ Creation de la coupe coronale """
    self.sagittalCut = vtk.vtkImageActor()
    self.sagittalCut.SetInput(self.sliceColors0.GetOutput())
    self.sagittalCut.SetDisplayExtent(0, self.col-1, self.valSagittal, self.valSagittal, 0, self.nb_coupe - 1)
    #-----------------------------------------
    self.ren.AddActor(self.sagittalCut)
    self.vtkRedraw()
예제 #33
0
 def vtkTransversalSlice(self):
    """ Creation de la coupe transversale """
    self.transversalCut = vtk.vtkImageActor()
    self.transversalCut.SetInput(self.sliceColors2.GetOutput())
    self.transversalCut.SetDisplayExtent(0, self.col-1, 0, self.lig-1, self.valTransversal, self.valTransversal)
    #-----------------------------------------
    self.ren.AddActor(self.transversalCut)
    self.vtkRedraw()
예제 #34
0
def numpy_to_actor2d(image,normalize=True,start=None,color=None,max_color=256):
    vtkimage = numpy_to_vtk(image,normalize,start)
    if color is None:
        actor = vtk.vtkImageActor()
        actor.SetInputData(vtkimage)
    else:
        actor = set_image_color(vtkimage,max_color,color)
    return actor
예제 #35
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """  
        module = self.getRegisteredModule()
        world_map =  None # wmod.forceGetInputFromPort( "world_map", None ) if wmod else None
        opacity =  wmod.forceGetInputFromPort( "opacity",   0.4  )  if wmod else 0.4  
        map_border_size =  wmod.forceGetInputFromPort( "map_border_size", 20  )  if wmod else 20  
            
        self.y0 = -90.0  
        dataPosition = None
        if world_map == None:
            self.map_file = defaultMapFile
            self.map_cut = defaultMapCut
        else:
            self.map_file = world_map[0].name
            self.map_cut = world_map[1]
        
        self.world_cut = wmod.forceGetInputFromPort( "world_cut", -1 )  if wmod else getFunctionParmStrValues( module, "world_cut", -1 )
        roi_size = [ self.roi[1] - self.roi[0], self.roi[3] - self.roi[2] ] 
        map_cut_size = [ roi_size[0] + 2*map_border_size, roi_size[1] + 2*map_border_size ]
        data_origin = self.input().GetOrigin() if self.input() else [ 0, 0, 0 ]
      
        if self.world_cut == -1: 
            if  (self.roi <> None): 
                if roi_size[0] > 180:             
                    self.ComputeCornerPosition()
                    self.world_cut = NormalizeLon( self.x0 )
                else:
                    dataPosition = [ ( self.roi[1] + self.roi[0] ) / 2.0, ( self.roi[3] + self.roi[2] ) / 2.0 ]
            else:
                self.world_cut = self.map_cut
        
        self.imageInfo = vtk.vtkImageChangeInformation()        
        image_reader = vtk.vtkJPEGReader()      
        image_reader.SetFileName(  self.map_file )
        baseImage = image_reader.GetOutput() 
        new_dims = None
        if dataPosition == None:    
            baseImage = self.RollMap( baseImage ) 
            new_dims = baseImage.GetDimensions()
        else:                       
            baseImage, new_dims = self.getBoundedMap( baseImage, dataPosition, map_cut_size ) 
        
        scale = [ map_cut_size[0]/new_dims[0], map_cut_size[1]/new_dims[1], 1 ]
#        printArgs( " baseMap: ", extent=baseImage.GetExtent(), spacing=baseImage.GetSpacing(), origin=baseImage.GetOrigin() )        
                  
        self.baseMapActor = vtk.vtkImageActor()
        self.baseMapActor.SetOrigin( 0.0, 0.0, 0.0 )
        self.baseMapActor.SetScale( scale )
        self.baseMapActor.SetOrientation( 0.0, 0.0, 0.0 )
        self.baseMapActor.SetOpacity( opacity )
#        self.baseMapActor.SetDisplayExtent( -1,  0,  0,  0,  0,  0 )
#Positioning map at location %s, size = %s, roi = %s" % ( str( ( self.x0, self.y0) ), str( map_cut_size ), str( ( NormalizeLon( self.roi[0] ), NormalizeLon( self.roi[1] ), self.roi[2], self.roi[3] ) ) )
        self.baseMapActor.SetPosition( self.x0, self.y0, 0.1 )
        self.baseMapActor.SetInput( baseImage )
        
        self.renderer.AddActor( self.baseMapActor )
예제 #36
0
def showImage(inputFileName):
    imgData = None
    dataType = None

    renderer = vtk.vtkRenderer()

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

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

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

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

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

    interactor.SetInteractorStyle(style)

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

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

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

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

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

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

        style = vtk.vtkInteractorStyleImage()

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

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(interactor, 1, wx.GROW | wx.EXPAND)
        sizer.Fit(self.panel)
        self.panel.SetSizer(sizer)
        self.Layout()
        self.Update()
예제 #38
0
    def build( self, **args ):
        if self.enableBasemap:              
#            print " @@@ MapManager: build "
            world_map =  None                 
            dataPosition = None
            if world_map == None:
                self.map_file = defaultMapFile
                self.map_cut = defaultMapCut
            else:
                self.map_file = world_map[0].name
                self.map_cut = world_map[1]
            
#            data_origin = self.input().GetOrigin() if self.input() else [ 0, 0, 0 ]
                      
            if self.world_cut == -1: 
                if  (self.roi <> None): 
                    if self.roi_size[0] > 180:             
                        self.ComputeCornerPosition()
                        self.world_cut = self.NormalizeMapLon( self.x0 )
                    else:
                        dataPosition = [ ( self.roi[1] + self.roi[0] ) / 2.0, ( self.roi[3] + self.roi[2] ) / 2.0 ]
                else:
                    self.world_cut = self.map_cut
            
            self.imageInfo = vtk.vtkImageChangeInformation()        
            self.image_reader = vtk.vtkJPEGReader()      
            self.image_reader.SetFileName(  self.map_file )
            self.image_reader.Update()
            world_image = self.image_reader.GetOutput() 
            self.sphericalBaseImage = self.RollMap( world_image )  
            new_dims, scale = None, None
            if dataPosition == None:    
                self.baseImage = self.RollMap( world_image ) 
                new_dims = self.baseImage.GetDimensions()
                scale = [ 360.0/new_dims[0], 180.0/new_dims[1], 1 ]
                self.width = 360.0
            else:                       
                self.baseImage, new_dims = self.getBoundedMap( world_image, dataPosition ) 
                scale = [ self.map_cut_size[0]/new_dims[0], self.map_cut_size[1]/new_dims[1], 1 ]
                self.width = self.map_cut_size[0]          
                              
            self.baseMapActor = vtk.vtkImageActor()
            self.baseMapActor.SetOrigin( 0.0, 0.0, 0.0 )
            self.baseMapActor.SetScale( scale )
            self.baseMapActor.SetOrientation( 0.0, 0.0, 0.0 )
            self.baseMapActor.SetOpacity( self.map_opacity )
            mapCorner = [ self.x0, self.y0 ]
            self.baseMapActor.SetPosition( mapCorner[0], mapCorner[1], 0.1 )
            extent = self.baseImage.GetExtent()
#             print " @@@ baseImage.GetExtent: ", str( extent )
#             print " @@@ baseImage.Position: ", str( self.x0 )
#             print " @@@ baseImage.Size: ", str( self.map_cut_size )
            if vtk.VTK_MAJOR_VERSION <= 5:  self.baseMapActor.SetInput(self.baseImage)
            else:                           self.baseMapActor.SetInputData(self.baseImage)        
            self.mapCenter = [ self.x0 + self.map_cut_size[0]/2.0, self.y0 + self.map_cut_size[1]/2.0 ]  
예제 #39
0
    def __init_vtk(self):
        actor = vtk.vtkImageActor()
        self.actor = actor

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

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

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

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

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

        style = vtk.vtkInteractorStyleImage()

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

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(interactor, 1, wx.GROW|wx.EXPAND)
        sizer.Fit(self.panel)
        self.panel.SetSizer(sizer)
        self.Layout()
        self.Update()
예제 #40
0
    def build( self, **args ):
        if self.enableBasemap:              
#            print " @@@ MapManager: build "
            world_map =  None                 
            dataPosition = None
            if world_map == None:
                self.map_file = defaultMapFile
                self.map_cut = defaultMapCut
            else:
                self.map_file = world_map[0].name
                self.map_cut = world_map[1]
            
#            data_origin = self.input().GetOrigin() if self.input() else [ 0, 0, 0 ]
                      
            if self.world_cut == -1: 
                if  (self.roi <> None): 
                    if self.roi_size[0] > 180:             
                        self.ComputeCornerPosition()
                        self.world_cut = self.NormalizeMapLon( self.x0 )
                    else:
                        dataPosition = [ ( self.roi[1] + self.roi[0] ) / 2.0, ( self.roi[3] + self.roi[2] ) / 2.0 ]
                else:
                    self.world_cut = self.map_cut
            
            self.imageInfo = vtk.vtkImageChangeInformation()        
            self.image_reader = vtk.vtkJPEGReader()      
            self.image_reader.SetFileName(  self.map_file )
            self.image_reader.Update()
            world_image = self.image_reader.GetOutput() 
            self.sphericalBaseImage = self.RollMap( world_image )  
            new_dims, scale = None, None
            if dataPosition == None:    
                self.baseImage = self.RollMap( world_image ) 
                new_dims = self.baseImage.GetDimensions()
                scale = [ 360.0/new_dims[0], 180.0/new_dims[1], 1 ]
                self.width = 360.0
            else:                       
                self.baseImage, new_dims = self.getBoundedMap( world_image, dataPosition ) 
                scale = [ self.map_cut_size[0]/new_dims[0], self.map_cut_size[1]/new_dims[1], 1 ]
                self.width = self.map_cut_size[0]          
                              
            self.baseMapActor = vtk.vtkImageActor()
            self.baseMapActor.SetOrigin( 0.0, 0.0, 0.0 )
            self.baseMapActor.SetScale( scale )
            self.baseMapActor.SetOrientation( 0.0, 0.0, 0.0 )
            self.baseMapActor.SetOpacity( self.map_opacity )
            mapCorner = [ self.x0, self.y0 ]
            self.baseMapActor.SetPosition( mapCorner[0], mapCorner[1], 0.05 )
            extent = self.baseImage.GetExtent()
#             print " @@@ baseImage.GetExtent: ", str( extent )
#             print " @@@ baseImage.Position: ", str( self.x0 )
#             print " @@@ baseImage.Size: ", str( self.map_cut_size )
            if vtk.VTK_MAJOR_VERSION <= 5:  self.baseMapActor.SetInput(self.baseImage)
            else:                           self.baseMapActor.SetInputData(self.baseImage)        
            self.mapCenter = [ self.x0 + self.map_cut_size[0]/2.0, self.y0 + self.map_cut_size[1]/2.0 ]  
예제 #41
0
def rerender():
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    img = convert_to_vtk(gray)
    image_actor = vtkImageActor()
    image_actor.SetInputData(img)
    background_renderer = vtkRenderer()
    background_renderer.SetLayer(0)
    render_window.AddRenderer(background_renderer)
    background_renderer.AddActor(image_actor)
    render_window.Render()
 def addLogo(self):
     imgReader = vtk.vtkPNGReader()
     imgReader.SetFileName("benano.png")
     imgReader.Update()
     #print(imgReader.GetOutput())
     imgActor = vtk.vtkImageActor()
     imgActor.SetInputData(imgReader.GetOutput())
     background_renderer = vtk.vtkRenderer()
     background_renderer.SetLayer(0)
     background_renderer.InteractiveOff()
     background_renderer.AddActor(imgActor)
     return background_renderer
예제 #43
0
    def setImage(self, dicomfile):
        logging.debug("In VTKImageView::setImage()")
        if dicomfile:
            if os.path.exists(dicomfile):
                self.reader = vtkgdcm.vtkGDCMImageReader()
                self.reader.SetFileName(dicomfile)
                self.reader.Update()

                vtkImageData = self.reader.GetOutput()
                vtkImageData.UpdateInformation()
                srange = vtkImageData.GetScalarRange()

                cast = vtk.vtkImageCast()
                cast.SetInput(vtkImageData)
                cast.SetOutputScalarType(4)
                cast.Update()
                cast.GetOutput().SetUpdateExtentToWholeExtent()

                table = vtk.vtkLookupTable()
                table.SetNumberOfColors(256)
                table.SetHueRange(0.0, 0.0)
                table.SetSaturationRange(0.0, 0.0)
                table.SetValueRange(0.0, 1.0)
                table.SetAlphaRange(1.0, 1.0)
                table.SetRange(srange)
                table.SetRampToLinear()
                table.Build()

                color = vtk.vtkImageMapToColors()
                color.SetLookupTable(table)
                color.SetInputConnection(cast.GetOutputPort())
                color.Update()

                self.cast = vtk.vtkImageMapToWindowLevelColors()
                self.cast.SetOutputFormatToLuminance()
                self.cast.SetInputConnection(color.GetOutputPort())
                self.cast.SetWindow(255.0)
                self.cast.SetLevel(127.0)
                self.cast.Update()
                self.cast.UpdateWholeExtent()

                self.render.RemoveActor(self.actor)
                self.actor = vtk.vtkImageActor()
                self.actor.SetInput(self.cast.GetOutput())
                self.render.AddActor(self.actor)
                self.render.ResetCamera()
                self.Render()
            else:
                self.render.RemoveActor(self.actor)
                self.Render()
        else:
            self.render.RemoveActor(self.actor)
            self.Render()
예제 #44
0
    def build( self, **args ):
        if self.enableBasemap:              
            world_map =  None                 
            dataPosition = None
            if world_map == None:
                self.map_file = defaultMapFile
                self.map_cut = defaultMapCut
            else:
                self.map_file = world_map[0].name
                self.map_cut = world_map[1]
            
            roi_size = [ self.roi[1] - self.roi[0], self.roi[3] - self.roi[2] ] 
            map_cut_size = [ roi_size[0] + 2*self.map_border_size, roi_size[1] + 2*self.map_border_size ]
            if map_cut_size[0] > 360.0: map_cut_size[0] = 360.0
            if map_cut_size[1] > 180.0: map_cut_size[1] = 180.0
#            data_origin = self.input().GetOrigin() if self.input() else [ 0, 0, 0 ]
                      
            if self.world_cut == -1: 
                if  (self.roi <> None): 
                    if roi_size[0] > 180:             
                        self.ComputeCornerPosition()
                        self.world_cut = self.NormalizeMapLon( self.x0 )
                    else:
                        dataPosition = [ ( self.roi[1] + self.roi[0] ) / 2.0, ( self.roi[3] + self.roi[2] ) / 2.0 ]
                else:
                    self.world_cut = self.map_cut
            
            self.imageInfo = vtk.vtkImageChangeInformation()        
            self.image_reader = vtk.vtkJPEGReader()      
            self.image_reader.SetFileName(  self.map_file )
            self.image_reader.Update()
            world_image = self.image_reader.GetOutput() 
            self.sphericalBaseImage = self.RollMap( world_image )  
            new_dims, scale = None, None
            if dataPosition == None:    
                self.baseImage = self.RollMap( world_image ) 
                new_dims = self.baseImage.GetDimensions()
                scale = [ 360.0/new_dims[0], 180.0/new_dims[1], 1 ]
            else:                       
                self.baseImage, new_dims = self.getBoundedMap( world_image, dataPosition, map_cut_size, self.map_border_size )             
                scale = [ map_cut_size[0]/new_dims[0], map_cut_size[1]/new_dims[1], 1 ]
                              
            self.baseMapActor = vtk.vtkImageActor()
            self.baseMapActor.SetOrigin( 0.0, 0.0, 0.0 )
            self.baseMapActor.SetScale( scale )
            self.baseMapActor.SetOrientation( 0.0, 0.0, 0.0 )
            self.baseMapActor.SetOpacity( self.map_opacity )
            mapCorner = [ self.x0, self.y0 ]
            self.baseMapActor.SetPosition( mapCorner[0], mapCorner[1], 0.1 )
            if vtk.VTK_MAJOR_VERSION <= 5:  self.baseMapActor.SetInput(self.baseImage)
            else:                           self.baseMapActor.SetInputData(self.baseImage)        
            self.mapCenter = [ self.x0 + map_cut_size[0]/2.0, self.y0 + map_cut_size[1]/2.0 ]  
예제 #45
0
 def execute(self, obj, event):
     ret, frame = cap.read()
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     img = convert_to_vtk(gray)
     image_actor = vtkImageActor()
     image_actor.SetInputData(img)
     background_renderer = vtkRenderer()
     background_renderer.SetLayer(0)
     render_window.AddRenderer(background_renderer)
     background_renderer.AddActor(image_actor)
     iren = obj
     iren.GetRenderWindow().Render()
     self.timer_count += 1
예제 #46
0
    def __init__(self, reader, axis, parent):

        if axis not in ['x', 'y', 'z']:
            raise TypeError('Argument should be x/y/z')

        super().__init__(parent)
        self.axis = axis
        self.position = 0
        self.reader = reader

        # Calculate the center of the volume
        self.x_min, self.x_max, self.y_min, self.y_max, self.z_min, self.z_max \
            = self.reader.GetExecutive().GetWholeExtent(
                self.reader.GetOutputInformation(0))


        self.x_spacing, self.y_spacing, self.z_spacing = \
            self.reader.GetOutput().GetSpacing()
        self.x_0, self.y_0, self.z_0 = self.reader.GetOutput().GetOrigin()

        self.center =\
         [self.x_0 + self.x_spacing * 0.5 * (self.x_min + self.x_max),
          self.y_0 + self.y_spacing * 0.5 * (self.y_min + self.y_max),
          self.z_0 + self.z_spacing * 0.5 * (self.z_min + self.z_max)]

        self.actor = vtk.vtkImageActor()
        self.set_lookup_table_min_max(-1000, 1000)

        self.text_actor = vtk.vtkTextActor()
        self.text_actor.SetInput(self.axis)

        self.renderer = vtk.vtkRenderer()
        self.renderer.AddActor(self.actor)
        self.renderer.AddActor(self.text_actor)

        # Move camera so that the slice is in view
        if axis == "x":
            self.renderer.GetActiveCamera().Azimuth(90)
        if axis == "y":
            self.renderer.GetActiveCamera().Elevation(90)

        self.set_slice_position_mm(0)
        self.renderer.ResetCamera(self.actor.GetBounds())
        self.GetRenderWindow().AddRenderer(self.renderer)

        # Remove unwanted mouse interaction behaviours
        actions = ['MouseWheelForwardEvent', 'MouseWheelBackwardEvent', \
                   'LeftButtonPressEvent', 'RightButtonPressEvent']
        for action in actions:
            self._Iren.RemoveObservers(action)
    def ShowSlice(self, index = 0):
        bitmap = self.bitmap_list[index]

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

        value1 = ''
        value2 = ''

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


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

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



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


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

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

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

        # Setting slider position
        self.slider.SetValue(index)
예제 #48
0
    def __init__(self, parent=None):
        logging.debug("In VTKImageView::__init__()")
        super(VTKImageView, self).__init__(parent)
        self.setWindowTitle(constant.TITLE_PROGRAM)

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

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

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

        self.window = self.GetRenderWindow()
        self.window.AddRenderer(self.render)
예제 #49
0
 def __init__(self):
     self.colour = (0.0, 0.0, 1.0)
     self.opacity = 1
     self.size = 15.0
     self.orientation = "AXIAL"
     self.spacing = (1, 1, 1)
     if vtk.vtkVersion().GetVTKVersion() > '5.8.0':
         self.mapper = vtk.vtkImageSliceMapper()
         cursor_property = vtk.vtkImageProperty()
         cursor_property.SetInterpolationTypeToNearest()
         self.actor = vtk.vtkImageSlice()
         self.actor.SetMapper(self.mapper)
         self.actor.SetProperty(cursor_property)
     else:
         self.actor = vtk.vtkImageActor()
         self.mapper = None
     self._build_actor()
     self._calculate_area_pixels()
예제 #50
0
    def updateContents(self, inputPorts):
        if self.view == None:
            self.view = pvsp.CreateRenderView()
            renWin = self.view.GetRenderWindow()
            self.SetRenderWindow(renWin)
            iren = renWin.GetInteractor()
            iren.SetNonInteractiveRenderDelay(0)
            iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

            # Load the uvcdat logo and use it for overlay
            logoPath = system.vistrails_root_directory() + "/gui/uvcdat/resources/images/uvcdat_logo_transparent.png"
            reader = vtk.vtkPNGReader()
            reader.SetFileName(logoPath)
            reader.Update()

            imageActor = vtk.vtkImageActor()
            imageActor.SetInput(reader.GetOutput())

            self.overlayRenderer = vtk.vtkRenderer()
            self.overlayRenderer.AddActor(imageActor)

            renWin.SetNumberOfLayers(renWin.GetNumberOfLayers() + 1)
            self.overlayRenderer.SetLayer(renWin.GetNumberOfLayers() - 1)
            renWin.AddRenderer(self.overlayRenderer)

            self.overlayRenderer.SetViewport(0.7, 0, 1.0, 0.3)

        del self.view.Representations[:]

        # Fetch variables from the input port
        (location, representations) = inputPorts

        for rep in representations:
            rep.set_view(self.view)
            rep.execute()

        # Set view specific properties
        self.view.CenterAxesVisibility = 0
        self.view.Background = [0.6, 0.6, 0.6]

        self.view.ResetCamera()
        self.view.StillRender()

        QCellWidget.updateContents(self, inputPorts)
예제 #51
0
 def __init__(self):
     super(Mwindow, self).__init__()
     self.importer = vtk.vtkImageImport()
     self.main_widget = QVTKRenderWindowInteractor(parent=self)
     self.setCentralWidget(self.main_widget)
     self.ren = vtk.vtkRenderer()
     self.image_actor = vtk.vtkImageActor()
     self.image_actor.SetInputData(self.importer.GetOutput())
     self.iren = vtk.vtkRenderWindowInteractor()
     self.main_widget.GetRenderWindow().AddRenderer(self.ren)
     self.ren.AddActor(self.image_actor)
     self.im1 = cv2.imread('1.tif', cv2.CV_LOAD_IMAGE_UNCHANGED)
     self.im1_str = self.im1.tostring()       
     self.importer.SetNumberOfScalarComponents(1)
     self.importer.SetDataScalarTypeToUnsignedChar()
     self.importer.SetWholeExtent(0, 799, 0, 799, 0, 0)
     self.importer.SetDataExtent(0, 799, 0, 799, 0, 0)
     self.image_actor.SetDisplayExtent(0, 799, 0, 799, 0, 0)
     self.importer.SetImportVoidPointer(self.im1_str, len(self.im1_str))
예제 #52
0
    def get_vtk_image(self):
        importer = vtk.vtkImageImport()
        importer.SetDataSpacing(1,1,1)
        importer.SetDataOrigin(0,0,0)
        importer.SetWholeExtent(0, self.im.shape[1] - 1,
                0, self.im.shape[0] - 1, 0, 0)
        importer.SetDataExtentToWholeExtent()
        importer.SetDataScalarTypeToUnsignedChar()
        importer.SetNumberOfScalarComponents(self.im.shape[2])
        importer.SetImportVoidPointer(self.im)
        importer.Update()
        flipY = vtk.vtkImageFlip()
        flipY.SetFilteredAxis(1)
        flipY.SetInputConnection(importer.GetOutputPort())
        flipY.Update()
        yActor = vtk.vtkImageActor()
        yActor.SetInput(flipY.GetOutput())

        return yActor
예제 #53
0
 def iniVTK(self):
     self.last_added_sphere_ren1 = None
     self.newed_spheres = vtk.vtkCollection()
     self.sphere_radius_ren1 = 2.0
     self.bouttons_spheres = []
     self.slice_assembly = None
     self.image_roi = None
     self.im_importer = vtk.vtkImageImport()       
     self.sphere = vtk.vtkSphereSource()
     self.sphere.SetRadius(2.0)
     self.sphere_mapper = vtk.vtkPolyDataMapper()
     self.sphere_mapper.SetInputConnection(self.sphere.GetOutputPort())
     self.sphere_actor_ren2 = vtk.vtkActor()
     self.sphere.SetCenter(show_height / 2, show_width / 2, 0)
     self.sphere_actor_ren2.SetMapper(self.sphere_mapper)
     self.sphere_actor_ren2.GetProperty().SetColor(255.0, 0, 0)
     self.vtk_widget.GetRenderWindow().SetSize(800, 400)
     self.image_actor = vtk.vtkImageActor()
     self.ren1 = vtk.vtkRenderer()
     self.ren2 = vtk.vtkRenderer()
     self.interactorStyle = BouttonInteractorStyle()
     self.vtk_widget.SetInteractorStyle(self.interactorStyle)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren1)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren2)
     self.ren1.SetViewport(0.0, 0.0, 0.5, 1.0)
     self.ren2.SetViewport(0.5, 0.0, 1.0, 1.0)
     self.ren2.AddActor(self.sphere_actor_ren2)
     self.imageLevelFilter = vtk.vtkImageMapToWindowLevelColors()
     self.imageLevelFilter.SetLevel(400)
     self.imageLevelFilter.SetWindow(800)
     self.im_importer.SetNumberOfScalarComponents(1)
     self.im_importer.SetDataScalarTypeToUnsignedShort()
     self.im_importer.SetDataExtent(0, show_width - 1, 0, show_height - 1, 0, 0)
     self.im_importer.SetWholeExtent(0, show_width - 1, 0, show_height - 1, 0, 0)
     self.imageLevelFilter.SetInputConnection(self.im_importer.GetOutputPort())
     self.image_actor.SetInput(self.imageLevelFilter.GetOutput())
     self.ren1_sphere_actors = vtk.vtkActorCollection()
     self.pointPicker = vtk.vtkPointPicker()
     self.actorPicker = vtk.vtkPropPicker()
     self.pickedActor = None
     self.ren1.AddActor(self.image_actor)
     self.ren2.AddActor(self.image_actor)
예제 #54
0
파일: VTKPlots.py 프로젝트: lizadams/uvcdat
 def createLogo(self):
   if self.canvas.drawLogo is False:
       ## Ok we do not want a logo here
       return
   # Pth to logo
   logoFile = os.path.join(sys.prefix,"share","vcs","uvcdat.png")
   # VTK reader for logo
   logoRdr=vtk.vtkPNGReader()
   logoRdr.SetFileName(logoFile)
   logoRdr.Update()
   x0,x1,y0,y1,z0,z1 = logoRdr.GetDataExtent()
   ia = vtk.vtkImageActor()
   ia.GetMapper().SetInputConnection(logoRdr.GetOutputPort())
   ren = self.createRenderer()
   self.renWin.AddRenderer(ren)
   r,g,b = self.canvas.backgroundcolor
   ren.SetBackground(r/255.,g/255.,b/255.)
   #ren.SetLayer(self.renWin.GetNumberOfLayers()-1)
   ren.AddActor(ia)
   self.logo = ren
   self.logoExtent = [x1,y1]
예제 #55
0
    def Visualize(self):
        renderSize = 300;
        numberOfImages = 1;   #implement only one image visulization

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

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

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

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

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

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

        actor.SetInput(connector.GetOutput())

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


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

        renderWindow.Render()

        # start interactor
        interactor.Start()
 def Add2DPhantom(self, input):
     '''
     @param input: vtkImageActor 
     '''
     if not self.GetRenderer():
         return
     
     cbk = ImageActorCallback()
     actor = vtk.vtkImageActor()
     cbk.setActor(actor)
     actor.SetInput(input.GetInput())
     actor.SetDisplayExtent(input.GetDisplayExtent())
     actor.SetUserMatrix(input.GetUserMatrix())
     actor.SetInterpolate(input.GetInterpolate())
     actor.SetOpacity(input.GetOpacity())
     
     input.AddObserver("ModifiedEvent", lambda obj, even: cbk.Execute(obj, "ModifiedEvent", None))
     
     self.GetRenderer().AddActor(actor)
     actor.SetVisibility(self.__RenderingMode == self.PLANAR_RENDERING)
     
     self.__PhantomCollection.AddItem(actor)
    def ShowBlackSlice(self, pub_sub):
        n_array = numpy.zeros((100,100))
       
        self.text_image_size.SetValue('')

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

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

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

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

        # Setting slider position
        self.slider.SetValue(0)
예제 #58
0
파일: gfx.py 프로젝트: ggoret/VEDA
	def set_open_img_on_off(self):
		if not self.isstarton:
			self.axes.VisibilityOff()
			self.camera.SetFocalPoint(145, 61, 0)
			self.camera.SetPosition(145, 61, 529)
			reader = vtk.vtkTIFFReader()
			reader.SetFileName(self.vedadir + 'doc/veda.tif')
			reader.SetOrientationType(4)
			self.ia = vtk.vtkImageActor()
			self.ia.SetInput(reader.GetOutput())
			self.renderer.AddActor(self.ia)
			self.renwin.Render()
			self.isstarton = 1
		else :
			self.axes.VisibilityOn()
			self.camera.SetFocalPoint(0, 0, 0)
			self.camera.SetPosition(0, 0, 400)
			self.camera.SetViewUp(0, 0, 0)
			self.camera.Elevation(0)
			self.camera.Roll(0)
			self.camera.Azimuth(0)
			self.renderer.RemoveActor(self.ia)
			self.renwin.Render()
			self.isstarton=0