Example #1
0
    def addT2transvisualize(self, T2images, image_pos_pat, image_ori_pat, T2dims, T2spacing, sideBreast, interact):
        '''Added to build second reference frame and display T2 overlayed into T1 reference frame'''
        # Proceed to build reference frame for display objects based on DICOM coords   
        [transformed_T2image, transform_cube] = self.dicomTransform(T2images, image_pos_pat, image_ori_pat)
        
        #alignR = int(raw_input('\nAlign right? Yes:1 No:0 : '))
        #if alignR:
        if(sideBreast=="Right"):
            zf1 = self.T1spacing[2]*self.T1extent[5] + self.T1origin[2]
            self.T2origin[2] = zf1 - T2spacing[2]*self.T2extent[5] # this is z-span
        else:
            self.T2origin[2] = self.T1origin[2]
        
        # Change info origin
        translated_T2image = vtk.vtkImageChangeInformation()
        translated_T2image.SetInput( transformed_T2image )
        translated_T2image.SetOutputOrigin(self.T2origin)
        translated_T2image.Update()
        
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInput( translated_T2image.GetOutput() )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0.5, 0.5, 0)
        tprop.ShadowOff()
        
        # Update the reneder window to receive new image !Important*****
        self.renderer1.Modified()
        self.renWin1.Modified()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInput(translated_T2image.GetOutput())
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)
        
        ### Update T2Images
        t_T2images = vtk.vtkImageChangeInformation()
        t_T2images.SetInput( T2images )
        t_T2images.SetOutputOrigin(self.T2origin)
        t_T2images.Update()        

        ############                
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()
            
        return 
def transform_all_images(register, image_datas, defining_image):
    image_list = list()
    idx = 0
    transform_list = register.convert_transforms_to_vtk()
    image_datas = [image_datas[0]]
    info = vtk.vtkImageChangeInformation()
    info.SetInput(defining_image)
    info.CenterImageOn()
        
    for image in image_datas:
        change = vtk.vtkImageChangeInformation()
        change.SetInput(image)
        change.CenterImageOn()
        #change.SetOutputSpacing(1,1,1)
        #spacing = image.GetSpacing()
        
        if 1:
            trans = vtk.vtkTransform()
            # this is right except scaling is 1/correct
            tx = transform_list[idx]
            trans.Concatenate(tx)
            #trans = tx
            #trans.Scale(-1,-1,-1)
            trans.Inverse()
            #trans.Scale(-1,-1,-1)
        if 0:
            transform = numpy.zeros(15)
            transform2 = numpy.zeros(15)
            tform = register._subjects[idx].transform
            # rotation and translation are "already inverted"
            # from images being in LPS
            transform[0:6] = tform[0:6]
            # invert scaling
            transform[6:9] = numpy.divide(1.0, tform[6:9])
            # invert shear
            transform2[6:9] = 1.0
            transform2[9:15] = tform[9:15]             
            reg_ops = wma.register.RegistrationInformation()
            trans = reg_ops.convert_transform_to_vtk(transform)
            trans2 = reg_ops.convert_transform_to_vtk(transform2)
            trans2.Scale(-1,-1,-1)
            trans2.Inverse()
            trans.Concatenate(trans2)
            
        resample = vtk.vtkImageReslice()
        #resample.SetResliceAxesDirectionCosines(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
        #resample.SetResliceAxesDirectionCosines(-1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, -1.0)
        #resample.SetInput(image)
        resample.SetInput(change.GetOutput())
        resample.SetResliceTransform(trans)
        print trans
        #resample.SetInformationInput(info.GetOutput())
        #resample.SetOutputSpacing(spacing)
        resample.Update()
        #resample.SetOutputOrigin(origin)
        image_list.append(resample.GetOutput())
        idx += 1
    del resample
    return image_list
Example #3
0
    def __init__(self):
        super(DualFlouroSceneVisualizer, self).__init__()

        # Remove origin information
        self.xray_changer_1 = vtk.vtkImageChangeInformation()
        self.xray_changer_1.SetOutputOrigin(0, 0, 0)
        self.xray_changer_2 = vtk.vtkImageChangeInformation()
        self.xray_changer_2.SetOutputOrigin(0, 0, 0)
        self.ct_changer = vtk.vtkImageChangeInformation()
        self.ct_changer.SetOutputOrigin(0, 0, 0)

        # Setup mapper and actor for x-ray images
        self.xray_mapper_1 = vtk.vtkImageSliceMapper()
        self.xray_mapper_1.SetInputConnection(
            self.xray_changer_1.GetOutputPort())
        self.xray_mapper_2 = vtk.vtkImageSliceMapper()
        self.xray_mapper_2.SetInputConnection(
            self.xray_changer_2.GetOutputPort())

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

        self.xray_slice_1 = vtk.vtkImageSlice()
        self.xray_slice_1.SetMapper(self.xray_mapper_1)
        self.xray_slice_1.SetProperty(self.xray_property)

        self.xray_slice_2 = vtk.vtkImageSlice()
        self.xray_slice_2.SetMapper(self.xray_mapper_2)
        self.xray_slice_2.SetProperty(self.xray_property)

        self.marchingCubes = vtk.vtkImageMarchingCubes()
        self.marchingCubes.SetInputConnection(self.ct_changer.GetOutputPort())
        self.marchingCubes.ComputeGradientsOn()
        self.marchingCubes.ComputeNormalsOn()
        self.marchingCubes.ComputeScalarsOn()
        self.marchingCubes.SetNumberOfContours(1)
        self.marchingCubes.SetValue(0, 0)

        self.ct_mapper = vtk.vtkPolyDataMapper()
        self.ct_mapper.SetInputConnection(self.marchingCubes.GetOutputPort())
        self.ct_mapper.ScalarVisibilityOff()
        self.ct_actor = vtk.vtkActor()
        self.ct_actor.SetMapper(self.ct_mapper)
        self.ct_actor.GetProperty().SetInterpolationToGouraud()
        self.ct_actor.GetProperty().SetColor(GetRGBColor('antique_white'))

        self.renderer = vtk.vtkRenderer()
        self.renderer.AddViewProp(self.ct_actor)
        self.renderer.AddViewProp(self.xray_slice_1)
        self.renderer.AddViewProp(self.xray_slice_2)
        self.renderer.SetBackground(0.1, 0.2, 0.3)

        self.interactor = vtk.vtkRenderWindowInteractor()
        self.interactor_style = vtk.vtkInteractorStyleTrackballCamera()
        self.interactor.SetInteractorStyle(self.interactor_style)
Example #4
0
    def Execute(self):

        if not self.KSpace:
            self.PrintError("Error: no KSpace.")

        ifft = vtk.vtkImageRFFT()
        ifft.SetInput(self.KSpace)
        ifft.SetDimensionality(self.KSpaceDimensionality)
        ifft.Update()

        ifftMagnitude = vtk.vtkImageMagnitude()
        ifftMagnitude.SetInput(ifft.GetOutput())
        ifftMagnitude.Update()

        origin = self.KSpace.GetOrigin()
        kspacing = self.KSpace.GetSpacing()
        dimensions = self.KSpace.GetDimensions()
        spacing = [
            1.0 / (dimensions[0] * kspacing[0]),
            1.0 / (dimensions[1] * kspacing[1]),
            1.0 / (dimensions[2] * kspacing[2]),
        ]

        imageInformation = vtk.vtkImageChangeInformation()
        imageInformation.SetInput(ifftMagnitude.GetOutput())
        imageInformation.SetOutputSpacing(spacing)
        imageInformation.SetOutputOrigin(origin)
        imageInformation.Update()

        self.Image = imageInformation.GetOutput()
Example #5
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        # setup config
        self._config.resolution = 40

        # and then our scripted config
        configList = [('Resolution: ', 'resolution', 'base:int', 'text',
                       'x, y and z resolution of sampled volume.  '
                       'According to the article, should be 40 to be '
                       'at Nyquist.')]

        # now create the necessary VTK modules
        self._es = vtk.vtkImageEllipsoidSource()
        self._es.SetOutputScalarTypeToFloat()

        self._ic = vtk.vtkImageChangeInformation()
        self._ic.SetInputConnection(self._es.GetOutputPort())

        self._output = vtk.vtkImageData()

        # mixin ctor
        ScriptedConfigModuleMixin.__init__(self, configList,
                                           {'Module (self)': self})

        self.sync_module_logic_with_config()
Example #6
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        self._reader = vtkgdcm.vtkGDCMImageReader()
        # NB NB NB: for now we're SWITCHING off the VTK-compatible
        # Y-flip, until the X-mirror issues can be solved.
        self._reader.SetFileLowerLeft(1)
        self._ici = vtk.vtkImageChangeInformation()
        self._ici.SetInputConnection(0, self._reader.GetOutputPort(0))

        # create output MedicalMetaData and populate it with the
        # necessary bindings.
        mmd = MedicalMetaData()
        mmd.medical_image_properties = \
                self._reader.GetMedicalImageProperties()
        mmd.direction_cosines = \
                self._reader.GetDirectionCosines()
        self._output_mmd = mmd

        module_utils.setup_vtk_object_progress(self, self._reader,
                                           'Reading DICOM data')

        self._view_frame = None
        self._file_dialog = None
        self._config.dicom_filenames = []
        # if this is true, module will still try to load set even if
        # IPP sorting fails by sorting images alphabetically
        self._config.robust_spacing = False

        self.sync_module_logic_with_config()
Example #7
0
    def _handlerVoiSaveButton(self, event):
        input_data = self.getPrimaryInput()
        filename = self.controlFrame.voiFilenameText.GetValue()
        if input_data and self._voi_widget.GetEnabled() and filename:
            # see if we need to reset to zero origin
            zor = self.controlFrame.voiResetToOriginCheck.GetValue()

            extractVOI = vtk.vtkExtractVOI()
            extractVOI.SetInput(input_data)
            extractVOI.SetVOI(self._currentVOI)

            writer = vtk.vtkXMLImageDataWriter()
            writer.SetDataModeToBinary()
            writer.SetFileName(filename)

            if zor:
                ici = vtk.vtkImageChangeInformation()
                ici.SetOutputExtentStart(0, 0, 0)
                ici.SetInput(extractVOI.GetOutput())
                writer.SetInput(ici.GetOutput())

            else:
                writer.SetInput(extractVOI.GetOutput())

            writer.Write()
Example #8
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        # setup config
        self._config.resolution = 40

        # and then our scripted config
        configList = [
            ('Resolution: ', 'resolution', 'base:int', 'text',
             'x, y and z resolution of sampled volume.  '
             'According to the article, should be 40 to be '
             'at Nyquist.')]

        # now create the necessary VTK modules
        self._es = vtk.vtkImageEllipsoidSource()
        self._es.SetOutputScalarTypeToFloat()

        self._ic = vtk.vtkImageChangeInformation()
        self._ic.SetInputConnection(self._es.GetOutputPort())

        self._output = vtk.vtkImageData()

        # mixin ctor
        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)' : self})

        self.sync_module_logic_with_config()
Example #9
0
 def buildPipeline(self):
     """ execute() -> None
     Dispatch the vtkRenderer to the actual rendering widget
     """        
     self.initialOrigin = self.input.GetOrigin()
     self.initialExtent = self.input.GetExtent()
     self.initialSpacing = self.input.GetSpacing()
     self.initialAoi = self.getUnscaledWorldExtent( self.initialExtent, self.initialSpacing ) 
     self.currentAoi = list( self.initialAoi )
             
     self.clip = vtk.vtkExtractVOI()  
     self.inputModule.inputToAlgorithm( self.clip )
     
     self.pad = vtk.vtkImageMagnify()
     self.pad.InterpolateOn()
     self.pad.SetInputConnection( self.clip.GetOutputPort() ) 
     
     self.imageInfo = vtk.vtkImageChangeInformation()
     self.imageInfo.SetInputConnection( self.pad.GetOutputPort() ) 
     self.imageInfo.SetOutputOrigin( self.initialOrigin[0], self.initialOrigin[1], self.initialOrigin[2] )
     self.imageInfo.SetOutputExtentStart( self.initialExtent[0], self.initialExtent[2], self.initialExtent[4] )
     self.imageInfo.SetOutputSpacing( self.initialSpacing[0], self.initialSpacing[1], self.initialSpacing[2] )
     
     self.setExtent( self.initialExtent )          
     self.set3DOutput( port=self.imageInfo.GetOutputPort() )
Example #10
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageChangeInformation(), 'Processing.',
         ('vtkImageData', 'vtkImageData'), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Example #11
0
    def _handlerVoiSaveButton(self, event):
        input_data = self.getPrimaryInput()
        filename = self.controlFrame.voiFilenameText.GetValue()
        if input_data and self._voi_widget.GetEnabled() and filename:
            # see if we need to reset to zero origin
            zor = self.controlFrame.voiResetToOriginCheck.GetValue()

            extractVOI = vtk.vtkExtractVOI()
            extractVOI.SetInput(input_data)
            extractVOI.SetVOI(self._currentVOI)

            writer = vtk.vtkXMLImageDataWriter()
            writer.SetDataModeToBinary()
            writer.SetFileName(filename)
            
            if zor:
                ici = vtk.vtkImageChangeInformation()
                ici.SetOutputExtentStart(0,0,0)
                ici.SetInput(extractVOI.GetOutput())
                writer.SetInput(ici.GetOutput())

            else:
                writer.SetInput(extractVOI.GetOutput())

            writer.Write()
Example #12
0
    def Execute(self):

        if not self.KSpace:
            self.PrintError('Error: no KSpace.')

        ifft = vtk.vtkImageRFFT()
        ifft.SetInput(self.KSpace)
        ifft.SetDimensionality(self.KSpaceDimensionality)
        ifft.Update()

        ifftMagnitude = vtk.vtkImageMagnitude()
        ifftMagnitude.SetInput(ifft.GetOutput())
        ifftMagnitude.Update()

        origin = self.KSpace.GetOrigin()
        kspacing = self.KSpace.GetSpacing()
        dimensions = self.KSpace.GetDimensions()
        spacing = [1.0/(dimensions[0]*kspacing[0]),1.0/(dimensions[1]*kspacing[1]),1.0/(dimensions[2]*kspacing[2])]
  
        imageInformation = vtk.vtkImageChangeInformation()
        imageInformation.SetInput(ifftMagnitude.GetOutput())
        imageInformation.SetOutputSpacing(spacing)
        imageInformation.SetOutputOrigin(origin)
        imageInformation.Update()
        
        self.Image = imageInformation.GetOutput()
Example #13
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 )
Example #14
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        NoConfigModuleMixin.__init__(self, {'Module (self)': self})

        self.sync_module_logic_with_config()
        self._ir = vtk.vtkImageReslice()
        self._ici = vtk.vtkImageChangeInformation()
Example #15
0
def scaleImage(image, scaleX=None,scaleY=None,scaleZ=None):
    if (scaleX == None)or(scaleY == None)or(scaleZ == None):    
        scale = max(abs(image.GetBounds()[1]-image.GetBounds()[0]),abs(image.GetBounds()[3]-image.GetBounds()[2]),abs(image.GetBounds()[5]-image.GetBounds()[4]))
        scaleX,scaleY,scaleZ = 1./scale,1./scale,1./scale    
    rescale = vtk.vtkImageChangeInformation()
    rescale.SetInput(image)
    rescale.SetOutputOrigin(0.0,0.0,0.0)
    rescale.SetSpacingScale(scaleX,scaleY,scaleZ)
    rescale.Update()
    return rescale.GetOutput()
Example #16
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        NoConfigModuleMixin.__init__(
            self, {'Module (self)' : self})

        self.sync_module_logic_with_config()    
        self._ir = vtk.vtkImageReslice()
        self._ici = vtk.vtkImageChangeInformation()
Example #17
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 ]  
Example #18
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 ]  
Example #19
0
 def mhaTransform(self, image, image_pos_pat, image_ori_pat):
     """ mhaTransform: transforms an image from mha coordinate frame"""
     "Image Orientation Patient Matrix"
     IO = matrix(    [[0, 0, 0, 0],
             [0, 0, 0, 0],
             [0, 0, 0, 0],
             [0, 0, 0, 1]])
     # Assign the 6-Image orientation patient coordinates (from Dicomtags)
     IO[0,0] = image_ori_pat[0]; IO[0,1] = image_ori_pat[1]; IO[0,2] = image_ori_pat[2]; 
     IO[1,0] = image_ori_pat[3]; IO[1,1] = image_ori_pat[4]; IO[1,2] = image_ori_pat[5]; 
     
     # obtain thrid column as the cross product of column 1 y 2
     IO_col1 = [image_ori_pat[0], image_ori_pat[1], image_ori_pat[2]]
     IO_col2 = [image_ori_pat[3], image_ori_pat[4], image_ori_pat[5]]
     IO_col3 = cross(IO_col1, IO_col2)
     
     # assign column 3    
     IO[2,0] = IO_col3[0]; IO[2,1] = IO_col3[1]; IO[2,2] = IO_col3[2]; 
     
     IP =  array([0, 0, 0, 1]) # Initialization Image Position
     IP[0] = image_pos_pat[0]; IP[1] = image_pos_pat[1]; IP[2] = image_pos_pat[2];  
     IO[0,3] = image_pos_pat[0]; IO[1,3] = image_pos_pat[1]; IO[2,3] = image_pos_pat[2]
            
     print "Compute: Position, Orientation, matrix, & Volume Origin"
     print image_pos_pat
     print image_ori_pat
     print IO
     origin = IP*IO.I
     print origin[0,0], origin[0,1], origin[0,2]
     
     # Change info
     # No need to Flip along Y-Z-axis like form DICOM          
     # Change info origin
     origin_image = vtk.vtkImageChangeInformation()
     origin_image.SetInputData( image )
     origin_image.SetOutputOrigin(origin[0,0], origin[0,1], origin[0,2])
     origin_image.Update()
     
     transformed_image = origin_image.GetOutput()
     self.T2dims = transformed_image.GetDimensions()
     print "Image Dimensions"
     print self.T2dims
     (xMin, xMax, yMin, yMax, zMin, zMax) = transformed_image.GetExtent()
     print "Image Extension"
     print xMin, xMax, yMin, yMax, zMin, zMax
     self.T2spacing = transformed_image.GetSpacing()
     print "Image Spacing"
     print self.T2spacing
     self.T2origin = transformed_image.GetOrigin()
     print "Image Origin"
     print self.T2origin
     
     return transformed_image 
Example #20
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 ]  
Example #21
0
    def loadFilesWithSeriesReader(self, imageIOName, files, name):
        """ Explicitly use the named imageIO to perform the loading
    """

        reader = vtkITK.vtkITKArchetypeImageSeriesScalarReader()
        reader.SetArchetype(files[0])
        for f in files:
            reader.AddFileName(slicer.util.toVTKString(f))
        reader.SetSingleFile(0)
        reader.SetOutputScalarTypeToNative()
        reader.SetDesiredCoordinateOrientationToNative()
        reader.SetUseNativeOriginOn()
        if imageIOName == "GDCM":
            reader.SetDICOMImageIOApproachToGDCM()
        elif imageIOName == "DCMTK":
            reader.SetDICOMImageIOApproachToDCMTK()
        else:
            raise Exception("Invalid imageIOName of %s" % imageIOName)
        logging.info("Loading with imageIOName: %s" % imageIOName)
        reader.Update()

        slicer.modules.reader = reader
        if reader.GetErrorCode() != vtk.vtkErrorCode.NoError:
            errorStrings = (imageIOName,
                            vtk.vtkErrorCode.GetStringFromErrorCode(
                                reader.GetErrorCode()))
            logging.error(
                "Could not read scalar volume using %s approach.  Error is: %s"
                % errorStrings)
            return

        imageChangeInformation = vtk.vtkImageChangeInformation()
        imageChangeInformation.SetInputConnection(reader.GetOutputPort())
        imageChangeInformation.SetOutputSpacing(1, 1, 1)
        imageChangeInformation.SetOutputOrigin(0, 0, 0)
        imageChangeInformation.Update()

        name = slicer.mrmlScene.GenerateUniqueName(
            slicer.util.toVTKString(name))
        volumeNode = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLScalarVolumeNode", name)
        volumeNode.SetAndObserveImageData(
            imageChangeInformation.GetOutputDataObject(0))
        slicer.vtkMRMLVolumeArchetypeStorageNode.SetMetaDataDictionaryFromReader(
            volumeNode, reader)
        volumeNode.SetRASToIJKMatrix(reader.GetRasToIjkMatrix())
        volumeNode.CreateDefaultDisplayNodes()

        slicer.modules.DICOMInstance.reader = reader
        slicer.modules.DICOMInstance.imageChangeInformation = imageChangeInformation

        return (volumeNode)
Example #22
0
    def RollMap(self, baseImage):
        #        baseImage.Update()
        if self.world_cut == self.map_cut: return baseImage
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        newCut = self.NormalizeMapLon(self.world_cut)
        delCut = newCut - self.map_cut
        #        print "  %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) )
        imageLen = x1 - x0 + 1
        sliceSize = imageLen * (delCut / 360.0)
        sliceCoord = int(round(x0 + sliceSize))
        extent = list(baseExtent)

        extent[0:2] = [x0, x0 + sliceCoord - 1]
        clip0 = vtk.vtkImageClip()
        if vtk.VTK_MAJOR_VERSION <= 5: clip0.SetInput(baseImage)
        else: clip0.SetInputData(baseImage)
        clip0.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3],
                                   extent[4], extent[5])

        extent[0:2] = [x0 + sliceCoord, x1]
        clip1 = vtk.vtkImageClip()
        if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput(baseImage)
        else: clip1.SetInputData(baseImage)
        clip1.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3],
                                   extent[4], extent[5])

        clip0.Update()
        clip1.Update()
        append = vtk.vtkImageAppend()
        append.SetAppendAxis(0)
        if vtk.VTK_MAJOR_VERSION <= 5:
            append.AddInput(clip1.GetOutput())
            append.AddInput(clip0.GetOutput())
        else:
            append.SetInputData(0, clip1.GetOutput())
            append.SetInputData(1, clip0.GetOutput())

        append.Update()
        imageInfo = vtk.vtkImageChangeInformation()
        imageInfo.SetInputConnection(append.GetOutputPort())
        imageInfo.SetOutputOrigin(0.0, 0.0, 0.0)
        imageInfo.SetOutputExtentStart(0, 0, 0)
        imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1],
                                   baseSpacing[2])

        imageInfo.Update()
        result = imageInfo.GetOutput()
        return result
Example #23
0
    def Update(self):
        # If a dummy input is defined  then, probaby a diagnostic run asking
        # for output data type is performed. In such case, just generate a
        # blank ImageData object just to be able to determine filter's output
        # data type.
        if self._padding == (0, 0, 0):
            self._output = self._input
            return

        # XXX: (note the date: Mon Mar 25 22:57:45 CET 2013)
        # Ok, when we arrived here, it means that we're doing sometging
        # significant.
        source = self._input
        self._output = vtk.vtkImageData()

        padx, pady, padz = self._padding
        initial_extent = self._input.GetWholeExtent()
        sx, sy, sz = self._input.GetSpacing()

        if __debug__:
            print "\tInitial image extent: " + str(initial_extent)
            print "\tInitial image origin: " + str(self._input.GetOrigin())
            print "\tRequested padding: %d, %d, %d" % (padx, pady, padz)

        translator = vtk.vtkImageChangeInformation()
        translator.SetExtentTranslation(padx, pady, padz)
        translator.SetOriginTranslation(-padx * sx, -pady * sy, -padz * sz)
        translator.SetInput(source)

        # Now we actually pad the image filling the extended canvas with the
        # "0" value.
        pad_filter = vtk.vtkImageConstantPad()
        pad_filter.SetConstant(0)
        pad_filter.SetOutputWholeExtent(initial_extent[0],
                                        initial_extent[1] + 2 * padx,
                                        initial_extent[2],
                                        initial_extent[3] + 2 * pady,
                                        initial_extent[4],
                                        initial_extent[5] + 2 * padz)
        pad_filter.SetInput(translator.GetOutput())
        pad_filter.Update()

        # Assign the resulting image to the output
        self._output = pad_filter.GetOutput()

        if __debug__:
            print "\tFinal image extent: " + str(self._output.GetWholeExtent())
            print "\tFinal image origin: " + str(self._output.GetOrigin())
Example #24
0
def magnify_multiply_imagedata(reader, zSpacing=1.0):
    logging.debug("In data.magnify_multiply_imagedata()")
    imagedata = reader.GetOutput()
    imagedata.UpdateInformation()
    spacing = imagedata.GetSpacing()
    # dimensions = imagedata.GetDimensions()
    # if dimensions[0] > 256 and dimensions[1] > 256:
    #    spacing = [x/0.5 for x in spacing]

    change = vtk.vtkImageChangeInformation()
    change.SetInput(imagedata)
    change.SetOutputOrigin(imagedata.GetOrigin())
    change.SetOutputSpacing(spacing[0], spacing[1], zSpacing)
    change.Update()

    return vtk.vtkImageData.SafeDownCast(change.GetOutput())
Example #25
0
  def loadFilesWithSeriesReader(self,imageIOName,files,name):
    """ Explicitly use the named imageIO to perform the loading
    """

    reader = vtkITK.vtkITKArchetypeImageSeriesScalarReader()
    reader.SetArchetype(files[0]);
    for f in files:
      reader.AddFileName(slicer.util.toVTKString(f))
    reader.SetSingleFile(0);
    reader.SetOutputScalarTypeToNative()
    reader.SetDesiredCoordinateOrientationToNative()
    reader.SetUseNativeOriginOn()
    if imageIOName == "GDCM":
      reader.SetDICOMImageIOApproachToGDCM()
    elif imageIOName == "DCMTK":
      reader.SetDICOMImageIOApproachToDCMTK()
    else:
      raise Exception("Invalid imageIOName of %s" % imageIOName)
    logging.info("Loading with imageIOName: %s" % imageIOName)
    reader.Update()

    slicer.modules.reader = reader
    if reader.GetErrorCode() != vtk.vtkErrorCode.NoError:
      errorStrings = (imageIOName, vtk.vtkErrorCode.GetStringFromErrorCode(reader.GetErrorCode()))
      logging.error("Could not read scalar volume using %s approach.  Error is: %s" % errorStrings)
      return


    imageChangeInformation = vtk.vtkImageChangeInformation()
    imageChangeInformation.SetInputConnection(reader.GetOutputPort())
    imageChangeInformation.SetOutputSpacing( 1, 1, 1 )
    imageChangeInformation.SetOutputOrigin( 0, 0, 0 )
    imageChangeInformation.Update()

    name = slicer.mrmlScene.GenerateUniqueName(slicer.util.toVTKString(name))
    volumeNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLScalarVolumeNode", name)
    volumeNode.SetAndObserveImageData(imageChangeInformation.GetOutputDataObject(0))
    slicer.vtkMRMLVolumeArchetypeStorageNode.SetMetaDataDictionaryFromReader(volumeNode, reader)
    volumeNode.SetRASToIJKMatrix(reader.GetRasToIjkMatrix())
    volumeNode.CreateDefaultDisplayNodes()

    slicer.modules.DICOMInstance.reader = reader
    slicer.modules.DICOMInstance.imageChangeInformation = imageChangeInformation

    return(volumeNode)
Example #26
0
    def Update(self):
        # If a dummy input is defined  then, probaby a diagnostic run asking
        # for output data type is performed. In such case, just generate a
        # blank ImageData object just to be able to determine filter's output
        # data type.
        if self._padding == (0, 0, 0):
            self._output = self._input
            return

        # XXX: (note the date: Mon Mar 25 22:57:45 CET 2013)
        # Ok, when we arrived here, it means that we're doing sometging
        # significant.
        source = self._input
        self._output = vtk.vtkImageData()

        padx, pady, padz = self._padding
        initial_extent = self._input.GetWholeExtent()
        sx, sy, sz = self._input.GetSpacing()

        if __debug__:
            print "\tInitial image extent: " + str(initial_extent)
            print "\tInitial image origin: " + str(self._input.GetOrigin())
            print "\tRequested padding: %d, %d, %d" % (padx, pady, padz)

        translator = vtk.vtkImageChangeInformation()
        translator.SetExtentTranslation(padx, pady, padz)
        translator.SetOriginTranslation(-padx*sx, -pady*sy, -padz*sz)
        translator.SetInput(source)

        # Now we actually pad the image filling the extended canvas with the
        # "0" value.
        pad_filter = vtk.vtkImageConstantPad()
        pad_filter.SetConstant(0)
        pad_filter.SetOutputWholeExtent(initial_extent[0], initial_extent[1]+2*padx,
                                        initial_extent[2], initial_extent[3]+2*pady,
                                        initial_extent[4], initial_extent[5]+2*padz)
        pad_filter.SetInput(translator.GetOutput())
        pad_filter.Update()

        # Assign the resulting image to the output
        self._output = pad_filter.GetOutput()

        if __debug__:
            print "\tFinal image extent: " + str(self._output.GetWholeExtent())
            print "\tFinal image origin: " + str(self._output.GetOrigin())
Example #27
0
    def getTimepoint(self, n, onlyDims=0):
        """
		Return the nth timepoint
		"""
        if not self.readers:
            self.getReadersFromFilenames()

        if self.is3DImage():
            if not self.readers:
                raise Logging.GUIError(
                    "Attempt to read bad timepoint",
                    "Timepoint %d is not defined by the given filenames" % n)
            self.reader = self.readers[0]
            minZ = n * self.slicesPerTimepoint
            maxZ = (n + 1) * self.slicesPerTimepoint - 1
            extract = vtk.vtkExtractVOI()
            extract.SetInput(self.reader.GetOutput())
            extract.SetVOI(0, self.x - 1, 0, self.y - 1, minZ, maxZ)
            changeInfo = vtk.vtkImageChangeInformation()
            changeInfo.SetInput(extract.GetOutput())
            changeInfo.SetOutputOrigin(0, 0, 0)
            changeInfo.SetExtentTranslation((0, 0, -minZ))
            data = changeInfo.GetOutput()
        else:
            if n >= len(self.readers):
                n = 0
                raise Logging.GUIError(
                    "Attempt to read bad timepoint",
                    "Timepoint %d is not defined by the given filenames" % n)

            self.reader = self.readers[n]
            data = self.reader.GetOutput()

        if not self.voxelsize:
            size = data.GetSpacing()
            x, y, z = [size.GetElement(x) for x in range(0, 3)]
            self.voxelsize = (x, y, z)
            print "Read voxel size", self.voxelsize

        if onlyDims:
            return

        return data
    def RollMap( self, baseImage ):
#        baseImage.Update()
        if self.world_cut  == self.map_cut: return baseImage
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        newCut = self.NormalizeMapLon( self.world_cut )
        delCut = newCut - self.map_cut
#        print "  %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) )
        imageLen = x1 - x0 + 1
        sliceSize =  imageLen * ( delCut / 360.0 )
        sliceCoord = int( round( x0 + sliceSize) )        
        extent = list( baseExtent ) 
        
        extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
        clip0 = vtk.vtkImageClip()
        if vtk.VTK_MAJOR_VERSION <= 5:  clip0.SetInput( baseImage )
        else:                           clip0.SetInputData( baseImage )                
        clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
        
        extent[0:2] = [ x0 + sliceCoord, x1 ]
        clip1 = vtk.vtkImageClip()
        if vtk.VTK_MAJOR_VERSION <= 5:  clip1.SetInput( baseImage )
        else:                           clip1.SetInputData( baseImage )                
        clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
        
        append = vtk.vtkImageAppend()
        append.SetAppendAxis( 0 )
        append.SetInputConnection ( clip1.GetOutputPort() )
        append.AddInputConnection ( clip0.GetOutputPort() )           
        
        imageInfo = vtk.vtkImageChangeInformation()
        imageInfo.SetInputConnection( append.GetOutputPort() ) 
        imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
        imageInfo.SetOutputExtentStart( 0, 0, 0 )
        imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
        
        imageInfo.Update()
        result = imageInfo.GetOutput() 
        return result
Example #29
0
    def RollMap(self, baseImage):
        baseImage.Update()
        if self.world_cut == self.map_cut: return baseImage
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        newCut = NormalizeLon(self.world_cut)
        delCut = NormalizeLon(self.map_cut - newCut)
        imageLen = x1 - x0 + 1
        sliceSize = imageLen * (delCut / 360.0)
        sliceCoord = int(round(x0 + sliceSize))
        extent = list(baseExtent)

        extent[0:2] = [x0, x0 + sliceCoord - 1]
        clip0 = vtk.vtkImageClip()
        clip0.SetInput(baseImage)
        clip0.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3],
                                   extent[4], extent[5])

        extent[0:2] = [x0 + sliceCoord, x1]
        clip1 = vtk.vtkImageClip()
        clip1.SetInput(baseImage)
        clip1.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3],
                                   extent[4], extent[5])

        append = vtk.vtkImageAppend()
        append.SetAppendAxis(0)
        append.AddInput(clip1.GetOutput())
        append.AddInput(clip0.GetOutput())

        imageInfo = vtk.vtkImageChangeInformation()
        imageInfo.SetInputConnection(append.GetOutputPort())
        imageInfo.SetOutputOrigin(0.0, 0.0, 0.0)
        imageInfo.SetOutputExtentStart(0, 0, 0)
        imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1],
                                   baseSpacing[2])

        result = imageInfo.GetOutput()
        result.Update()
        return result
Example #30
0
    def Execute(self):

        if not self.Image:
            self.PrintError('Error: no Image.')

        fft = vtk.vtkImageFFT()
        fft.SetInput(self.Image)
        fft.SetDimensionality(self.KSpaceDimensionality)
        fft.Update()

        origin = self.Image.GetOrigin()
        spacing = self.Image.GetSpacing()
        dimensions = self.Image.GetDimensions()
        kspacing = [1.0/(dimensions[0]*spacing[0]),1.0/(dimensions[1]*spacing[1]),1.0/(dimensions[2]*spacing[2])]
  
        imageInformation = vtk.vtkImageChangeInformation()
        imageInformation.SetInput(fft.GetOutput())
        imageInformation.SetOutputSpacing(kspacing)
        imageInformation.SetOutputOrigin(origin)
        imageInformation.Update()
        
        self.KSpace = imageInformation.GetOutput()
	def getTimepoint(self, n, onlyDims = 0):
		"""
		Return the nth timepoint
		"""
		if not self.readers:
			self.getReadersFromFilenames()

		if self.is3DImage():
			if not self.readers:
				raise Logging.GUIError("Attempt to read bad timepoint", "Timepoint %d is not defined by the given filenames" % n)
			self.reader = self.readers[0]
			minZ = n * self.slicesPerTimepoint
			maxZ = (n+1) * self.slicesPerTimepoint - 1
			extract = vtk.vtkExtractVOI()
			extract.SetInput(self.reader.GetOutput())
			extract.SetVOI(0, self.x - 1, 0, self.y - 1, minZ, maxZ)
			changeInfo = vtk.vtkImageChangeInformation()
			changeInfo.SetInput(extract.GetOutput())
			changeInfo.SetOutputOrigin(0, 0, 0)
			changeInfo.SetExtentTranslation((0,0,-minZ))
			data = changeInfo.GetOutput()
		else:
			if n >= len(self.readers):
				n = 0
				raise Logging.GUIError("Attempt to read bad timepoint", "Timepoint %d is not defined by the given filenames" % n)
			
			self.reader = self.readers[n]
			data = self.reader.GetOutput()

		if not self.voxelsize:
			size = data.GetSpacing()
			x, y, z = [size.GetElement(x) for x in range(0, 3)]
			self.voxelsize = (x, y, z)
			print "Read voxel size", self.voxelsize

		if onlyDims:
			return
		
		return data
Example #32
0
 def RollMap( self, baseImage ):
     baseImage.Update()
     if self.world_cut  == self.map_cut: return baseImage
     baseExtent = baseImage.GetExtent()
     baseSpacing = baseImage.GetSpacing()
     x0 = baseExtent[0]
     x1 = baseExtent[1]
     newCut = NormalizeLon( self.world_cut )
     delCut = NormalizeLon( self.map_cut - newCut )
     imageLen = x1 - x0 + 1
     sliceSize =  imageLen * ( delCut / 360.0 )
     sliceCoord = int( round( x0 + sliceSize) )        
     extent = list( baseExtent ) 
     
     extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
     clip0 = vtk.vtkImageClip()
     clip0.SetInput( baseImage )
     clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
     
     extent[0:2] = [ x0 + sliceCoord, x1 ]
     clip1 = vtk.vtkImageClip()
     clip1.SetInput( baseImage )
     clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
     
     append = vtk.vtkImageAppend()
     append.SetAppendAxis( 0 )
     append.AddInput( clip1.GetOutput() )          
     append.AddInput( clip0.GetOutput() )
     
     imageInfo = vtk.vtkImageChangeInformation()
     imageInfo.SetInputConnection( append.GetOutputPort() ) 
     imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
     imageInfo.SetOutputExtentStart( 0, 0, 0 )
     imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
     
     result = imageInfo.GetOutput() 
     result.Update()
     return result
Example #33
0
 def transformVolume(self, inputVolume, outputVolume, transformationMatrix):
     # Normalize matrix so it preserve its scaling (diagonal elements are
     # equal to 1)
     M = self.__normalizeMatrix(transformationMatrix)
     
     reader = vtk.vtkStructuredPointsReader()
     reader.SetFileName(inputVolume)
     reader.Update()
     reader.GetOutput().UpdateInformation()
     
     matrix = vtk.vtkMatrix4x4()
     matrix.DeepCopy((
         M[0,0], M[0,1], M[0,2], M[0,3],
         M[1,0], M[1,1], M[1,2], M[1,3],
         M[2,0], M[2,1], M[2,2], M[2,3],
         M[3,0], M[3,1], M[3,2], M[3,3]
         ))
     
     # Extract a slice in the desired orientation
     reslice = vtk.vtkImageReslice()
     reslice.SetInputConnection(reader.GetOutputPort())
     reslice.SetResliceAxes(matrix)
     reslice.AutoCropOutputOff()
     reslice.SetInterpolationModeToNearestNeighbor()
     #reslice.SetInterpolationModeToLinear()
     
     print >>sys.stderr,'M=\n',M
     ch = vtk.vtkImageChangeInformation()
     ch.SetInput(reslice.GetOutput())
     ch.SetOutputOrigin(*OUTPUT_VOLUME_ORIGIN)
     ch.SetOutputSpacing(*OUTPUT_VOLUME_SPACING)
     ch.Update() 
     
     writer = vtk.vtkStructuredPointsWriter()
     writer.SetFileTypeToBinary()
     writer.SetInput(ch.GetOutput())
     writer.SetFileName(outputVolume)
     writer.Update()
Example #34
0
    def getBoundedMap( self, baseImage, dataLocation, map_cut_size ):
        baseImage.Update()
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        y0 = baseExtent[2]
        y1 = baseExtent[3]
        imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ]
        selectionDim = [ map_cut_size[0]/2, map_cut_size[1]/2 ]
        dataXLoc = NormalizeLon( dataLocation[0] ) 
        imageInfo = vtk.vtkImageChangeInformation()
        dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ]
        vertExtent = [ y0, y1 ]
        bounded_dims = None
        if dataYbounds[0] > -90.0:
            yOffset = dataYbounds[0] + 90.0
            extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
            vertExtent[0] = y0 + extOffset
            self.y0 = dataYbounds[0]
        if dataYbounds[1] < 90.0:
            yOffset = 90.0 - dataYbounds[1]
            extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
            vertExtent[1] = y1 - extOffset
                   
        if (( dataXLoc > selectionDim[0] ) and ( dataXLoc < ( 360 - selectionDim[0]) )):

            cut0 = dataXLoc - selectionDim[0] 
            sliceSize =  imageLen[0] * ( cut0 / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )        
            extent = list( baseExtent )         
            extent[0] = x0 + sliceCoord - 1
        
            cut1 = dataXLoc + selectionDim[0] 
            sliceSize =  imageLen[0] * ( cut1 / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )       
            extent[1] = x0 + sliceCoord
            clip = vtk.vtkImageClip()
            clip.SetInput( baseImage )
            clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            self.x0 = cut0
            bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 )

            imageInfo.SetInputConnection( clip.GetOutputPort() ) 
            
        else:
            cut0 = NormalizeLon( dataXLoc + selectionDim[0] )
            sliceSize =  imageLen[0] * ( cut0 / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )        
            extent = list( baseExtent )         
            extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
            clip0 = vtk.vtkImageClip()
            clip0.SetInput( baseImage )
            clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            size0 = extent[1] - extent[0] + 1
        
            cut1 = NormalizeLon( dataLocation[0] - selectionDim[0] )
            sliceSize =  imageLen[0] * ( cut1 / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )       
            extent[0:2] = [ x0 + sliceCoord, x1 ]
            clip1 = vtk.vtkImageClip()
            clip1.SetInput( baseImage )
            clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            size1 = extent[1] - extent[0] + 1
            self.x0 = cut1
        
            append = vtk.vtkImageAppend()
            append.SetAppendAxis( 0 )
            append.AddInput( clip1.GetOutput() )          
            append.AddInput( clip0.GetOutput() )
            bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 )
            
            imageInfo.SetInputConnection( append.GetOutputPort() ) 
            
        imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
        imageInfo.SetOutputExtentStart( 0, 0, 0 )
        imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
        
        result = imageInfo.GetOutput() 
        result.Update()
        return result, bounded_dims
Example #35
0
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Simple volume rendering example.
reader = vtk.vtkImageReader()
reader.SetDataByteOrderToLittleEndian()
reader.SetDataExtent(0, 63, 0, 63, 1, 93)
reader.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
reader.SetDataMask(0x7fff)
reader.SetDataSpacing(2, 2, 1)
reader.SetDataScalarTypeToUnsignedShort()
reader.Update()

changeFilter = vtk.vtkImageChangeInformation()
changeFilter.SetInputConnection(reader.GetOutputPort())
changeFilter.SetOutputOrigin(-63, -63, -46)

# Create transfer functions for opacity and color
opacityTransferFunction = vtk.vtkPiecewiseFunction()
opacityTransferFunction.AddPoint(600, 0.0)
opacityTransferFunction.AddPoint(2000, 1.0)

colorTransferFunction = vtk.vtkColorTransferFunction()
colorTransferFunction.ClampingOff()
colorTransferFunction.AddHSVPoint(0.0, 0.01, 1.0, 1.0)
colorTransferFunction.AddHSVPoint(1000.0, 0.50, 1.0, 1.0)
colorTransferFunction.AddHSVPoint(2000.0, 0.99, 1.0, 1.0)
colorTransferFunction.SetColorSpaceToHSV()
  def apply(self, segmentMarkupNode, segmentModel, text, textDepth, mode):

    self.updateModel(segmentMarkupNode, segmentModel, text, textDepth)

    import vtkSegmentationCore

    if not segmentMarkupNode:
      raise AttributeError(f"{self.__class__.__name__}: segment markup node not set.")
    if not segmentModel:
      raise AttributeError(f"{self.__class__.__name__}: segment model not set.")

    if segmentMarkupNode and segmentModel.GetPolyData().GetNumberOfCells() > 0:
      segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()
      if not segmentationNode:
        raise AttributeError(f"{self.__class__.__name__}: Segmentation node not set.")

      modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap()
      if not modifierLabelmap:
        raise AttributeError("{}: ModifierLabelmap not set. This can happen for various reasons:\n"
                             "No master volume set for segmentation,\n"
                             "No existing segments for segmentation, or\n"
                             "No referenceImageGeometry is specified in the segmentation".format(self.__class__.__name__))

      WorldToModifierLabelmapIjkTransform = vtk.vtkTransform()

      WorldToModifierLabelmapIjkTransformer = vtk.vtkTransformPolyDataFilter()
      WorldToModifierLabelmapIjkTransformer.SetTransform(WorldToModifierLabelmapIjkTransform)
      WorldToModifierLabelmapIjkTransformer.SetInputConnection(segmentModel.GetPolyDataConnection())

      segmentationToSegmentationIjkTransformMatrix = vtk.vtkMatrix4x4()
      modifierLabelmap.GetImageToWorldMatrix(segmentationToSegmentationIjkTransformMatrix)
      segmentationToSegmentationIjkTransformMatrix.Invert()
      WorldToModifierLabelmapIjkTransform.Concatenate(segmentationToSegmentationIjkTransformMatrix)

      worldToSegmentationTransformMatrix = vtk.vtkMatrix4x4()
      slicer.vtkMRMLTransformNode.GetMatrixTransformBetweenNodes(None, segmentationNode.GetParentTransformNode(),
                                                                 worldToSegmentationTransformMatrix)
      WorldToModifierLabelmapIjkTransform.Concatenate(worldToSegmentationTransformMatrix)
      WorldToModifierLabelmapIjkTransformer.Update()

      polyToStencil = vtk.vtkPolyDataToImageStencil()
      polyToStencil.SetOutputSpacing(1.0, 1.0, 1.0)
      polyToStencil.SetInputConnection(WorldToModifierLabelmapIjkTransformer.GetOutputPort())
      boundsIjk = WorldToModifierLabelmapIjkTransformer.GetOutput().GetBounds()
      modifierLabelmapExtent = self.scriptedEffect.modifierLabelmap().GetExtent()
      polyToStencil.SetOutputWholeExtent(modifierLabelmapExtent[0], modifierLabelmapExtent[1],
                                         modifierLabelmapExtent[2], modifierLabelmapExtent[3],
                                         int(round(boundsIjk[4])), int(round(boundsIjk[5])))
      polyToStencil.Update()

      stencilData = polyToStencil.GetOutput()
      stencilExtent = [0, -1, 0, -1, 0, -1]
      stencilData.SetExtent(stencilExtent)

      stencilToImage = vtk.vtkImageStencilToImage()
      stencilToImage.SetInputConnection(polyToStencil.GetOutputPort())
      stencilToImage.SetInsideValue(1.0)
      stencilToImage.SetOutsideValue(0.0)
      stencilToImage.SetOutputScalarType(modifierLabelmap.GetScalarType())

      stencilPositioner = vtk.vtkImageChangeInformation()
      stencilPositioner.SetInputConnection(stencilToImage.GetOutputPort())
      stencilPositioner.SetOutputSpacing(modifierLabelmap.GetSpacing())
      stencilPositioner.SetOutputOrigin(modifierLabelmap.GetOrigin())

      stencilPositioner.Update()
      orientedStencilPositionerOutput = vtkSegmentationCore.vtkOrientedImageData()
      orientedStencilPositionerOutput.ShallowCopy(stencilToImage.GetOutput())
      imageToWorld = vtk.vtkMatrix4x4()
      modifierLabelmap.GetImageToWorldMatrix(imageToWorld)
      orientedStencilPositionerOutput.SetImageToWorldMatrix(imageToWorld)

      vtkSegmentationCore.vtkOrientedImageDataResample.ModifyImage(
        modifierLabelmap, orientedStencilPositionerOutput,
        vtkSegmentationCore.vtkOrientedImageDataResample.OPERATION_MAXIMUM)

      modeName = self.scriptedEffect.parameter("Mode")
      if modeName == "EMBOSS":
        mode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeAdd
      elif modeName == "ENGRAVE":
        mode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeRemove
      else:
        logging.error("Invalid mode: "+modeName+" (valid modes: EMBOSS, ENGRAVE)")
      self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierLabelmap, mode)

      # get plane parameters as space-separated string list
      planeParameters = []
      if segmentMarkupNode.GetIsPlaneValid():
        planeParameters.extend(segmentMarkupNode.GetOriginWorld())
        xAxis = [1, 0, 0]
        yAxis = [0, 1, 0]
        zAxis = [0, 0, 1]
        segmentMarkupNode.GetAxesWorld(xAxis, yAxis, zAxis)
        planeParameters.extend(xAxis)
        planeParameters.extend(yAxis)
        planeParameters.extend(zAxis)
        planeParameters.extend(segmentMarkupNode.GetPlaneBounds())
      planeParametersString = ' '.join(map(str, planeParameters))

      segmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID()
      segment = segmentationNode.GetSegmentation().GetSegment(segmentID)
      segment.SetTag("EngraveEffectPlaneParameters", planeParametersString)
  def smoothMultipleSegments(self):
    import vtkSegmentationCorePython as vtkSegmentationCore

    # Generate merged labelmap of all visible segments
    segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()
    visibleSegmentIds = vtk.vtkStringArray()
    segmentationNode.GetDisplayNode().GetVisibleSegmentIDs(visibleSegmentIds)
    if visibleSegmentIds.GetNumberOfValues() == 0:
      logging.info("Smoothing operation skipped: there are no visible segments")
      return

    mergedImage = vtkSegmentationCore.vtkOrientedImageData()
    if not segmentationNode.GenerateMergedLabelmapForAllSegments(mergedImage,
                                                                 vtkSegmentationCore.vtkSegmentation.EXTENT_UNION_OF_SEGMENTS_PADDED,
                                                                 None, visibleSegmentIds):
      logging.error('Failed to apply smoothing: cannot get list of visible segments')
      return

    segmentLabelValues = [] # list of [segmentId, labelValue]
    for i in range(visibleSegmentIds.GetNumberOfValues()):
      segmentId = visibleSegmentIds.GetValue(i)
      segmentLabelValues.append([segmentId, i+1])

    # Perform smoothing in voxel space
    ici = vtk.vtkImageChangeInformation()
    ici.SetInputData(mergedImage)
    ici.SetOutputSpacing(1, 1, 1)
    ici.SetOutputOrigin(0, 0, 0)

    # Convert labelmap to combined polydata
    # vtkDiscreteFlyingEdges3D cannot be used here, as in the output of that filter,
    # each labeled region is completely disconnected from neighboring regions, and
    # for joint smoothing it is essential for the points to move together.
    convertToPolyData = vtk.vtkDiscreteMarchingCubes()
    convertToPolyData.SetInputConnection(ici.GetOutputPort())
    convertToPolyData.SetNumberOfContours(len(segmentLabelValues))

    contourIndex = 0
    for segmentId, labelValue in segmentLabelValues:
      convertToPolyData.SetValue(contourIndex, labelValue)
      contourIndex += 1

    # Low-pass filtering using Taubin's method
    smoothingFactor = self.scriptedEffect.doubleParameter("JointTaubinSmoothingFactor")
    smoothingIterations = 100 #  according to VTK documentation 10-20 iterations could be enough but we use a higher value to reduce chance of shrinking
    passBand = pow(10.0, -4.0*smoothingFactor) # gives a nice range of 1-0.0001 from a user input of 0-1
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(convertToPolyData.GetOutputPort())
    smoother.SetNumberOfIterations(smoothingIterations)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(90.0)
    smoother.SetPassBand(passBand)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()

    # Extract a label
    threshold = vtk.vtkThreshold()
    threshold.SetInputConnection(smoother.GetOutputPort())

    # Convert to polydata
    geometryFilter = vtk.vtkGeometryFilter()
    geometryFilter.SetInputConnection(threshold.GetOutputPort())

    # Convert polydata to stencil
    polyDataToImageStencil = vtk.vtkPolyDataToImageStencil()
    polyDataToImageStencil.SetInputConnection(geometryFilter.GetOutputPort())
    polyDataToImageStencil.SetOutputSpacing(1,1,1)
    polyDataToImageStencil.SetOutputOrigin(0,0,0)
    polyDataToImageStencil.SetOutputWholeExtent(mergedImage.GetExtent())

    # Convert stencil to image
    stencil = vtk.vtkImageStencil()
    emptyBinaryLabelMap = vtk.vtkImageData()
    emptyBinaryLabelMap.SetExtent(mergedImage.GetExtent())
    emptyBinaryLabelMap.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
    vtkSegmentationCore.vtkOrientedImageDataResample.FillImage(emptyBinaryLabelMap, 0)
    stencil.SetInputData(emptyBinaryLabelMap)
    stencil.SetStencilConnection(polyDataToImageStencil.GetOutputPort())
    stencil.ReverseStencilOn()
    stencil.SetBackgroundValue(1) # General foreground value is 1 (background value because of reverse stencil)

    imageToWorldMatrix = vtk.vtkMatrix4x4()
    mergedImage.GetImageToWorldMatrix(imageToWorldMatrix)

    for segmentId, labelValue in segmentLabelValues:
      threshold.ThresholdBetween(labelValue, labelValue)
      stencil.Update()
      smoothedBinaryLabelMap = vtkSegmentationCore.vtkOrientedImageData()
      smoothedBinaryLabelMap.ShallowCopy(stencil.GetOutput())
      smoothedBinaryLabelMap.SetImageToWorldMatrix(imageToWorldMatrix)
      # Write results to segments directly, bypassing masking
      slicer.vtkSlicerSegmentationsModuleLogic.SetBinaryLabelmapToSegment(smoothedBinaryLabelMap,
        segmentationNode, segmentId, slicer.vtkSlicerSegmentationsModuleLogic.MODE_REPLACE, smoothedBinaryLabelMap.GetExtent())
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# In this example, an image is centered at (0,0,0) before a
# rotation is applied to ensure that the rotation occurs about
# the center of the image.
reader = vtk.vtkPNGReader()
reader.SetDataSpacing(0.8,0.8,1.5)
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png")
reader.Update()
# first center the image at (0,0,0)
reslice = vtk.vtkImageReslice()
reslice.SetResliceAxesDirectionCosines([0,1,0,-1,0,0,0,0,1])
reslice.SetInputConnection(reader.GetOutputPort())
reslice.SetInformationInput(reader.GetOutput())
# reset the image back to the way it was (you don't have
# to do this, it is just put in as an example)
information2 = vtk.vtkImageChangeInformation()
information2.SetInputConnection(reslice.GetOutputPort())
information2.SetInformationInputData(reader.GetOutput())
viewer = vtk.vtkImageViewer()
viewer.SetInputConnection(information2.GetOutputPort())
viewer.SetColorWindow(2000)
viewer.SetColorLevel(1000)
viewer.Render()
# --- end of script --
Example #39
0
def loadTifImage(filename):

    step = 1.0

    import os, os.path
    dir = os.path.split(filename)[0]
    name = os.path.split(filename)[1]

    for file in os.listdir(dir):
        if os.path.splitext(file)[1] == '.log':
            logfile = file
            break

    print 'logfile', dir + '/' + logfile

    inFile = open(dir + '/' + logfile, 'r')
    line = inFile.readline().split()

    eof = False
    while not eof:
        if len(line) == 0:
            line = inFile.readline().split()
            if len(line) == 0:
                eof = True
        if (len(line) == 4) and line[0] == 'Result' and line[
                1] == 'Image' and line[2] == 'Width':
            resultimagewidth = line[3]
        if (len(line) == 4) and line[0] == 'Result' and line[
                1] == 'Image' and line[2] == 'Height':
            resultimageheight = line[3]
        if (len(line) == 3) and line[0] == 'Pixel' and line[1] == 'Size':
            pixelsize = line[2]
        line = inFile.readline().split()

    resultimagewidth = int(resultimagewidth.partition('=')[2])
    resultimageheight = int(resultimageheight.partition('=')[2])
    spacing = float(pixelsize.partition('=')[2])

    if pixelsize.partition('=')[0] == '(um)':
        spacing = spacing * 0.001

    names = os.listdir(dir)
    nboffiles = len(names) - 2
    nameonly = os.path.splitext(name)[0]
    fileprefix = os.path.join(dir, nameonly.rpartition('_')[0] + '_')

    reader = vtk.vtkTIFFReader()
    reader.SetFileDimensionality(2)
    reader.SetNumberOfScalarComponents(1)

    print 'spacing: ', spacing, spacing, spacing * step
    print 'dimensions: ', resultimagewidth, resultimageheight, nboffiles
    print 'extent: ', 0, resultimagewidth - 1, 0, resultimageheight - 1, 0, nboffiles - 1
    print 'bounds: ', 0, resultimagewidth * spacing, 0, resultimageheight * spacing, 0, nboffiles * spacing * step

    reader.SetFilePrefix(fileprefix)
    if len(nameonly.rpartition('_')[2]) == 2:
        reader.SetFilePattern("%s%02d.tif")
    elif len(nameonly.rpartition('_')[2]) == 3:
        reader.SetFilePattern("%s%03d.tif")
    reader.SetDataSpacing(
        1.0, 1.0, step
    )  # bizarre: si je mets (spacing,spacing,spacing*step) et remplace par (1.0,1.0,spacing*step) -> vtkImageChangeInformation
    reader.SetDataExtent(0, resultimagewidth - 1, 0, resultimageheight - 1, 0,
                         nboffiles - 1)
    reader.Update()

    rescale = vtk.vtkImageChangeInformation()
    rescale.SetInput(reader.GetOutput())
    rescale.SetOutputOrigin(0.0, 0.0, 0.0)
    rescale.SetSpacingScale(spacing, spacing, spacing)
    rescale.Update()

    return rescale.GetOutput()
Example #40
0
    def onApply(self):

        import vtkSegmentationCorePython as vtkSegmentationCore

        # Allow users revert to this state by clicking Undo
        self.scriptedEffect.saveStateForUndo()

        # This can be a long operation - indicate it to the user
        qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)

        if self.segmentMarkupNode and (
                self.segmentModel.GetPolyData().GetNumberOfPolys() > 0):
            self.observeSegmentation(False)
            operationName = self.scriptedEffect.parameter("Operation")
            modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap()
            segmentationNode = self.scriptedEffect.parameterSetNode(
            ).GetSegmentationNode()
            WorldToModifierLabelmapIjkTransform = vtk.vtkTransform()

            WorldToModifierLabelmapIjkTransformer = vtk.vtkTransformPolyDataFilter(
            )
            WorldToModifierLabelmapIjkTransformer.SetTransform(
                WorldToModifierLabelmapIjkTransform)
            WorldToModifierLabelmapIjkTransformer.SetInputConnection(
                self.segmentModel.GetPolyDataConnection())

            segmentationToSegmentationIjkTransformMatrix = vtk.vtkMatrix4x4()
            modifierLabelmap.GetImageToWorldMatrix(
                segmentationToSegmentationIjkTransformMatrix)
            segmentationToSegmentationIjkTransformMatrix.Invert()
            WorldToModifierLabelmapIjkTransform.Concatenate(
                segmentationToSegmentationIjkTransformMatrix)

            worldToSegmentationTransformMatrix = vtk.vtkMatrix4x4()
            slicer.vtkMRMLTransformNode.GetMatrixTransformBetweenNodes(
                None, segmentationNode.GetParentTransformNode(),
                worldToSegmentationTransformMatrix)
            WorldToModifierLabelmapIjkTransform.Concatenate(
                worldToSegmentationTransformMatrix)
            WorldToModifierLabelmapIjkTransformer.Update()

            polyToStencil = vtk.vtkPolyDataToImageStencil()
            polyToStencil.SetOutputSpacing(1.0, 1.0, 1.0)
            polyToStencil.SetInputConnection(
                WorldToModifierLabelmapIjkTransformer.GetOutputPort())
            boundsIjk = WorldToModifierLabelmapIjkTransformer.GetOutput(
            ).GetBounds()
            modifierLabelmapExtent = self.scriptedEffect.modifierLabelmap(
            ).GetExtent()
            polyToStencil.SetOutputWholeExtent(modifierLabelmapExtent[0],
                                               modifierLabelmapExtent[1],
                                               modifierLabelmapExtent[2],
                                               modifierLabelmapExtent[3],
                                               int(round(boundsIjk[4])),
                                               int(round(boundsIjk[5])))
            polyToStencil.Update()

            stencilData = polyToStencil.GetOutput()
            stencilExtent = [0, -1, 0, -1, 0, -1]
            stencilData.SetExtent(stencilExtent)

            stencilToImage = vtk.vtkImageStencilToImage()
            stencilToImage.SetInputConnection(polyToStencil.GetOutputPort())
            if operationName in ("FILL_INSIDE", "ERASE_INSIDE", "SET"):
                stencilToImage.SetInsideValue(1.0)
                stencilToImage.SetOutsideValue(0.0)
            else:
                stencilToImage.SetInsideValue(0.0)
                stencilToImage.SetOutsideValue(1.0)
            stencilToImage.SetOutputScalarType(
                modifierLabelmap.GetScalarType())

            stencilPositioner = vtk.vtkImageChangeInformation()
            stencilPositioner.SetInputConnection(
                stencilToImage.GetOutputPort())
            stencilPositioner.SetOutputSpacing(modifierLabelmap.GetSpacing())
            stencilPositioner.SetOutputOrigin(modifierLabelmap.GetOrigin())

            stencilPositioner.Update()
            orientedStencilPositionerOuput = vtkSegmentationCore.vtkOrientedImageData(
            )
            orientedStencilPositionerOuput.ShallowCopy(
                stencilToImage.GetOutput())
            imageToWorld = vtk.vtkMatrix4x4()
            modifierLabelmap.GetImageToWorldMatrix(imageToWorld)
            orientedStencilPositionerOuput.SetImageToWorldMatrix(imageToWorld)

            vtkSegmentationCore.vtkOrientedImageDataResample.ModifyImage(
                modifierLabelmap, orientedStencilPositionerOuput,
                vtkSegmentationCore.vtkOrientedImageDataResample.
                OPERATION_MAXIMUM)

            modMode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeAdd
            if operationName == "ERASE_INSIDE" or operationName == "ERASE_OUTSIDE":
                modMode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeRemove
            elif operationName == "SET":
                modMode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet

            self.scriptedEffect.modifySelectedSegmentByLabelmap(
                modifierLabelmap, modMode)

            import numpy
            n = self.segmentMarkupNode.GetNumberOfFiducials()
            # get fiducial positions
            fPos = numpy.zeros((n, 3))
            for i in xrange(n):
                coord = [0.0, 0.0, 0.0]
                self.segmentMarkupNode.GetNthFiducialPosition(i, coord)
                fPos[i] = coord
            segmentID = self.scriptedEffect.parameterSetNode(
            ).GetSelectedSegmentID()
            segment = segmentationNode.GetSegmentation().GetSegment(segmentID)
            segment.SetTag("fP", fPos.tostring())
            segment.SetTag("fN", n)

        self.reset()
        self.createNewMarkupNode()
        self.fiducialPlacementToggle.setCurrentNode(self.segmentMarkupNode)
        self.observeSegmentation(True)
        qt.QApplication.restoreOverrideCursor()
Example #41
0
    def addT2transvisualize(self, T2images, image_pos_pat, image_ori_pat, T2dims, T2spacing, interact):
        '''Added to build second reference frame and display T2 overlayed into T1 reference frame'''
        # Proceed to build reference frame for display objects based on DICOM coords   
        [transformed_T2image, transform_cube] = self.dicomTransform(T2images, image_pos_pat, image_ori_pat)
        
        self.T2origin = list(transformed_T2image.GetOrigin())
        print "T2 Extent"
        self.T2extent = list(transformed_T2image.GetExtent())
        print self.T2extent        
        
        alignR = int(raw_input('\nAlign right? Yes:1 or align with T1w: !=1 : '))
        if alignR:
            zf1 = self.T1spacing[2]*self.T1extent[5] + self.T1origin[2]
            self.T2origin[2] = zf1 - T2spacing[2]*self.T2extent[5] # this is z-span
        else:
            self.T2origin[2] = self.T1origin[2]
                
        # Change info origin
        transformedInfo_T2image = vtk.vtkImageChangeInformation()
        transformedInfo_T2image.SetInputData( transformed_T2image )
        transformedInfo_T2image.SetOutputOrigin(self.T2origin)
        transformedInfo_T2image.Update()
        
        self.transformed_T2image = transformedInfo_T2image.GetOutput()
        
        # Set up ortogonal planes
        self.xImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.xImagePlaneWidget.SetSliceIndex(0)
        self.yImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.yImagePlaneWidget.SetSliceIndex(0)
        self.zImagePlaneWidget.SetInputData( self.transformed_T2image )
        self.zImagePlaneWidget.SetSliceIndex(0)
                    
        # Create a text property for both cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(0.5, 0.5, 0)
        tprop.ShadowOff()
        
        # Update the reneder window to receive new image !Important*****
        self.renderer1.Modified()
        self.renWin1.Modified()
        
        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        axesT2 = vtk.vtkCubeAxesActor2D()
        axesT2.SetInputData(self.transformed_T2image)
        axesT2.SetCamera(self.renderer1.GetActiveCamera())
        axesT2.SetLabelFormat("%6.4g")
        axesT2.SetFlyModeToOuterEdges()
        axesT2.SetFontFactor(1.2)
        axesT2.SetAxisTitleTextProperty(tprop)
        axesT2.SetAxisLabelTextProperty(tprop)      
        self.renderer1.AddViewProp(axesT2)
        
        ### Update T2Images
        t_T2images = vtk.vtkImageChangeInformation()
        t_T2images.SetInputData( T2images )
        t_T2images.SetOutputOrigin(self.T2origin)
        t_T2images.Update()        

        ############                
        if(interact==True):
            interactor = self.renWin1.GetInteractor()
            interactor.Start()
            
        return 
Example #42
0
    def getBoundedMap( self, baseImage, dataLocation ):
#        print " @@@ MapManager: getBoundedMap "
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        y0 = baseExtent[2]
        y1 = baseExtent[3]
        imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ]
        selectionDim = [ self.map_cut_size[0]/2, self.map_cut_size[1]/2 ]
        dataXLoc = dataLocation[0]
        imageInfo = vtk.vtkImageChangeInformation()
        dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ]
        vertExtent = [ y0, y1 ]
        bounded_dims = None
        if dataYbounds[0] > -90.0:
            yOffset = dataYbounds[0] + 90.0
            extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
            vertExtent[0] = y0 + extOffset
            self.y0 = dataYbounds[0]
        if dataYbounds[1] < 90.0:
            yOffset = 90.0 - dataYbounds[1]
            extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
            vertExtent[1] = y1 - extOffset
            
        overlapsBorder = ( self.NormalizeMapLon(dataLocation[0]-selectionDim[0]) > self.NormalizeMapLon(dataLocation[0]+selectionDim[0]) )
        if overlapsBorder:
            cut0 = self.NormalizeMapLon( dataXLoc + selectionDim[0] )
            sliceSize =  imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )        
            extent = list( baseExtent )         
            extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
            clip0 = vtk.vtkImageClip()
            clip0.ClipDataOn()
            clip0.SetInput( baseImage )
            clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            size0 = extent[1] - extent[0] + 1
        
            self.x0 = dataLocation[0] - selectionDim[0]
            cut1 = self.NormalizeMapLon( self.x0 ) 
            sliceSize =  imageLen[0] * ( ( cut1 - self.map_cut )/ 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )       
            extent[0:2] = [ x0 + sliceCoord, x1 ]
            clip1 = vtk.vtkImageClip()
            clip1.ClipDataOn()
            if vtk.VTK_MAJOR_VERSION <= 5:  clip1.SetInput( baseImage )
            else:                           clip1.SetInputData( baseImage )
            clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            size1 = extent[1] - extent[0] + 1
#            print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) )
        
            append = vtk.vtkImageAppend()
            append.SetAppendAxis( 0 )
            append.AddInputConnection( clip1.GetOutputPort() )              
            append.AddInputConnection( clip0.GetOutputPort() )    
            bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 )
            
            imageInfo.SetInputConnection( append.GetOutputPort() ) 

        else:
                        
            self.x0 = dataXLoc - selectionDim[0]
            cut0 = self.NormalizeMapLon( self.x0 )
            sliceSize =  imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )        
            extent = list( baseExtent )         
            extent[0] = x0 + sliceCoord - 1
        
            cut1 = self.NormalizeMapLon( dataXLoc + selectionDim[0] )
            sliceSize =  imageLen[0] * ( ( cut1 - self.map_cut ) / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )       
            extent[1] = x0 + sliceCoord
            clip = vtk.vtkImageClip()
            clip.ClipDataOn()
            if vtk.VTK_MAJOR_VERSION <= 5:  clip.SetInput( baseImage )
            else:                           clip.SetInputData( baseImage )
            clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 )
#            print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) )
            clip.Update()
            imageInfo.SetInputConnection( clip.GetOutputPort() ) 
                       
        imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
        imageInfo.SetOutputExtentStart( 0, 0, 0 )
        imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
        imageInfo.Update()
        
        result = imageInfo.GetOutput() 
        return result, bounded_dims
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Image pipeline
reader = vtk.vtkPNGReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png")
clip = vtk.vtkImageClip()
clip.SetInputConnection(reader.GetOutputPort())
clip.SetOutputWholeExtent(80, 230, 80, 230, 0, 0)
clip.ClipDataOff()
gradient = vtk.vtkImageGradientMagnitude()
gradient.SetDimensionality(2)
gradient.SetInputConnection(clip.GetOutputPort())
gradient.HandleBoundariesOff()
slide = vtk.vtkImageChangeInformation()
slide.SetInputConnection(gradient.GetOutputPort())
slide.SetExtentTranslation(-100, -100, 0)
viewer = vtk.vtkImageViewer()
viewer.SetInputConnection(slide.GetOutputPort())
viewer.SetColorWindow(-1000)
viewer.SetColorLevel(500)
viewer.Render()
#skipping source
# --- end of script --
Example #44
0
    def buildBaseMap(self):
        if self.baseMapActor <> None:
            self.renderer.RemoveActor(self.baseMapActor)
        world_map = None
        map_border_size = 20

        self.y0 = -90.0
        self.x0 = 0.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 = -1
        if (self.roi <> None):
            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
            ]
            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
        else:
            map_cut_size = [360, 180]

        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:
                dataPosition = [
                    180, 0
                ]  # [ ( 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)
        image_reader.Update()
        baseImage = image_reader.GetOutput()
        new_dims, scale = None, None
        if dataPosition == None:
            old_dims = baseImage.GetDimensions()
            baseImage = self.RollMap(baseImage)
            new_dims = baseImage.GetDimensions()
            scale = [360.0 / new_dims[0], 180.0 / new_dims[1], 1]
        else:
            baseImage, new_dims = self.getBoundedMap(baseImage, dataPosition,
                                                     map_cut_size,
                                                     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[0])
        mapCorner = [self.x0, self.y0]

        self.baseMapActor.SetPosition(mapCorner[0], mapCorner[1], 0.1)
        if vtk.VTK_MAJOR_VERSION <= 5: self.baseMapActor.SetInput(baseImage)
        else: self.baseMapActor.SetInputData(baseImage)
        self.mapCenter = [
            self.x0 + map_cut_size[0] / 2.0, self.y0 + map_cut_size[1] / 2.0
        ]
        self.renderer.AddActor(self.baseMapActor)
Example #45
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Image pipeline
reader = vtk.vtkPNGReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png")
clip = vtk.vtkImageClip()
clip.SetInputConnection(reader.GetOutputPort())
clip.SetOutputWholeExtent(80,230,80,230,0,0)
clip.ClipDataOff()
gradient = vtk.vtkImageGradientMagnitude()
gradient.SetDimensionality(2)
gradient.SetInputConnection(clip.GetOutputPort())
gradient.HandleBoundariesOff()
slide = vtk.vtkImageChangeInformation()
slide.SetInputConnection(gradient.GetOutputPort())
slide.SetExtentTranslation(-100,-100,0)
viewer = vtk.vtkImageViewer()
viewer.SetInputConnection(slide.GetOutputPort())
viewer.SetColorWindow(-1000)
viewer.SetColorLevel(500)
viewer.Render()
#skipping source
# --- end of script --
Example #46
0
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Simple volume rendering example.
reader = vtk.vtkImageReader()
reader.SetDataByteOrderToLittleEndian()
reader.SetDataExtent(0, 63, 0, 63, 1, 93)
reader.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
reader.SetDataMask(0x7fff)
reader.SetDataSpacing(2, 2, 1)
reader.SetDataScalarTypeToUnsignedShort()
reader.Update()

changeFilter = vtk.vtkImageChangeInformation()
changeFilter.SetInputConnection(reader.GetOutputPort())
changeFilter.SetOutputOrigin(-63, -63, -46)

# Create transfer functions for opacity and color
opacityTransferFunction = vtk.vtkPiecewiseFunction()
opacityTransferFunction.AddPoint(600, 0.0)
opacityTransferFunction.AddPoint(2000, 1.0)

colorTransferFunction = vtk.vtkColorTransferFunction()
colorTransferFunction.ClampingOff()
colorTransferFunction.AddHSVPoint(0.0, 0.01, 1.0, 1.0)
colorTransferFunction.AddHSVPoint(1000.0, 0.50, 1.0, 1.0)
colorTransferFunction.AddHSVPoint(2000.0, 0.99, 1.0, 1.0)
colorTransferFunction.SetColorSpaceToHSV()
Example #47
0
    def cutSurfaceWithModel(self, segmentMarkupNode, segmentModel):

        import vtkSegmentationCorePython as vtkSegmentationCore

        if not segmentMarkupNode:
            raise AttributeError("{}: segment markup node not set.".format(
                self.__class__.__name__))
        if not segmentModel:
            raise AttributeError("{}: segment model not set.".format(
                self.__class__.__name__))

        if segmentMarkupNode and segmentModel.GetPolyData().GetNumberOfPolys(
        ) > 0:
            operationName = self.scriptedEffect.parameter("Operation")

            segmentationNode = self.scriptedEffect.parameterSetNode(
            ).GetSegmentationNode()
            if not segmentationNode:
                raise AttributeError("{}: Segmentation node not set.".format(
                    self.__class__.__name__))

            modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap()
            if not modifierLabelmap:
                raise AttributeError(
                    "{}: ModifierLabelmap not set. This can happen for various reasons:\n"
                    "No master volume set for segmentation,\n"
                    "No existing segments for segmentation, or\n"
                    "No referenceImageGeometry is specified in the segmentation"
                    .format(self.__class__.__name__))

            WorldToModifierLabelmapIjkTransform = vtk.vtkTransform()

            WorldToModifierLabelmapIjkTransformer = vtk.vtkTransformPolyDataFilter(
            )
            WorldToModifierLabelmapIjkTransformer.SetTransform(
                WorldToModifierLabelmapIjkTransform)
            WorldToModifierLabelmapIjkTransformer.SetInputConnection(
                segmentModel.GetPolyDataConnection())

            segmentationToSegmentationIjkTransformMatrix = vtk.vtkMatrix4x4()
            modifierLabelmap.GetImageToWorldMatrix(
                segmentationToSegmentationIjkTransformMatrix)
            segmentationToSegmentationIjkTransformMatrix.Invert()
            WorldToModifierLabelmapIjkTransform.Concatenate(
                segmentationToSegmentationIjkTransformMatrix)

            worldToSegmentationTransformMatrix = vtk.vtkMatrix4x4()
            slicer.vtkMRMLTransformNode.GetMatrixTransformBetweenNodes(
                None, segmentationNode.GetParentTransformNode(),
                worldToSegmentationTransformMatrix)
            WorldToModifierLabelmapIjkTransform.Concatenate(
                worldToSegmentationTransformMatrix)
            WorldToModifierLabelmapIjkTransformer.Update()

            polyToStencil = vtk.vtkPolyDataToImageStencil()
            polyToStencil.SetOutputSpacing(1.0, 1.0, 1.0)
            polyToStencil.SetInputConnection(
                WorldToModifierLabelmapIjkTransformer.GetOutputPort())
            boundsIjk = WorldToModifierLabelmapIjkTransformer.GetOutput(
            ).GetBounds()
            modifierLabelmapExtent = self.scriptedEffect.modifierLabelmap(
            ).GetExtent()
            polyToStencil.SetOutputWholeExtent(modifierLabelmapExtent[0],
                                               modifierLabelmapExtent[1],
                                               modifierLabelmapExtent[2],
                                               modifierLabelmapExtent[3],
                                               int(round(boundsIjk[4])),
                                               int(round(boundsIjk[5])))
            polyToStencil.Update()

            stencilData = polyToStencil.GetOutput()
            stencilExtent = [0, -1, 0, -1, 0, -1]
            stencilData.SetExtent(stencilExtent)

            stencilToImage = vtk.vtkImageStencilToImage()
            stencilToImage.SetInputConnection(polyToStencil.GetOutputPort())
            if operationName in ("FILL_INSIDE", "ERASE_INSIDE", "SET"):
                stencilToImage.SetInsideValue(1.0)
                stencilToImage.SetOutsideValue(0.0)
            else:
                stencilToImage.SetInsideValue(0.0)
                stencilToImage.SetOutsideValue(1.0)
            stencilToImage.SetOutputScalarType(
                modifierLabelmap.GetScalarType())

            stencilPositioner = vtk.vtkImageChangeInformation()
            stencilPositioner.SetInputConnection(
                stencilToImage.GetOutputPort())
            stencilPositioner.SetOutputSpacing(modifierLabelmap.GetSpacing())
            stencilPositioner.SetOutputOrigin(modifierLabelmap.GetOrigin())

            stencilPositioner.Update()
            orientedStencilPositionerOutput = vtkSegmentationCore.vtkOrientedImageData(
            )
            orientedStencilPositionerOutput.ShallowCopy(
                stencilToImage.GetOutput())
            imageToWorld = vtk.vtkMatrix4x4()
            modifierLabelmap.GetImageToWorldMatrix(imageToWorld)
            orientedStencilPositionerOutput.SetImageToWorldMatrix(imageToWorld)

            vtkSegmentationCore.vtkOrientedImageDataResample.ModifyImage(
                modifierLabelmap, orientedStencilPositionerOutput,
                vtkSegmentationCore.vtkOrientedImageDataResample.
                OPERATION_MAXIMUM)

            modMode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeAdd
            if operationName == "ERASE_INSIDE" or operationName == "ERASE_OUTSIDE":
                modMode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeRemove
            elif operationName == "SET":
                modMode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet

            self.scriptedEffect.modifySelectedSegmentByLabelmap(
                modifierLabelmap, modMode)

            # get fiducial positions as space-separated list
            import numpy
            n = segmentMarkupNode.GetNumberOfFiducials()
            fPos = []
            for i in range(n):
                coord = [0.0, 0.0, 0.0]
                segmentMarkupNode.GetNthFiducialPosition(i, coord)
                fPos.extend(coord)
            fPosString = ' '.join(map(str, fPos))

            segmentID = self.scriptedEffect.parameterSetNode(
            ).GetSelectedSegmentID()
            segment = segmentationNode.GetSegmentation().GetSegment(segmentID)
            segment.SetTag("SurfaceCutEffectMarkupPositions", fPosString)
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot

VTK_DATA_ROOT = vtkGetDataRoot()

# In this example, an image is centered at (0,0,0) before a
# rotation is applied to ensure that the rotation occurs about
# the center of the image.
reader = vtk.vtkPNGReader()
reader.SetDataSpacing(0.8, 0.8, 1.5)
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png")
# first center the image at (0,0,0)
information = vtk.vtkImageChangeInformation()
information.SetInputConnection(reader.GetOutputPort())
information.CenterImageOn()
reslice = vtk.vtkImageReslice()
reslice.SetInputConnection(information.GetOutputPort())
reslice.SetResliceAxesDirectionCosines(
    [0.866025, -0.5, 0, 0.5, 0.866025, 0, 0, 0, 1])
reslice.SetInterpolationModeToCubic()
# reset the image back to the way it was (you don't have
# to do this, it is just put in as an example)
information2 = vtk.vtkImageChangeInformation()
information2.SetInputConnection(reslice.GetOutputPort())
reader.Update()
information2.SetInformationInputData(reader.GetOutput())
viewer = vtk.vtkImageViewer()
viewer.SetInputConnection(information2.GetOutputPort())
viewer.SetColorWindow(2000)
	def createData(self, currentTimepoint):
		"""
		Create a test dataset within the parameters defined
		"""
		x,y,z = self.parameters["X"], self.parameters["Y"], self.parameters["Z"]
		if self.modified:
			print "Creating the time series data"
			self.createTimeSeries()
			if self.parameters["CreateAll"]:
				n = min(self.parameters["CacheAmount"], self.parameters["Time"])
				for i in range(0, n):
					if i == currentTimepoint: 
						print "Won't create timepoint %d, it'll be last"%i
						continue
					self.createData(i)

		print "\n\nGenerating timepoint %d"%currentTimepoint
		
		if currentTimepoint in self.imageCache:
			print "Returning cached image"
			return self.imageCache[currentTimepoint]

		print "Allocating image"

		if self.parameters["CreateNoise"]:
			print "Creating background noise"
			noiseSource = vtk.vtkImageNoiseSource()
			noiseSource.SetWholeExtent(0,x-1,0,y-1,0,z-1)
			noiseSource.SetMinimum(self.parameters["BackgroundNoiseMin"])
			noiseSource.SetMaximum(self.parameters["BackgroundNoiseMax"])
			castFilter = vtk.vtkImageCast()
			castFilter.SetOutputScalarTypeToUnsignedChar()
			castFilter.SetInputConnection(noiseSource.GetOutputPort())
			information = vtk.vtkImageChangeInformation()
			information.SetInputConnection(castFilter.GetOutputPort())
			information.SetOutputSpacing(self.spacing)
			image = information.GetOutput()
			image.Update()
		else:
			image = vtk.vtkImageData()
			image.SetScalarTypeToUnsignedChar()
			x,y,z = self.parameters["X"], self.parameters["Y"], self.parameters["Z"]
			image.SetDimensions((x,y,z))
			image.AllocateScalars()
			image.SetSpacing(self.spacing)
			
			print "Initializing image"
			for iz in range(0,z):
				for iy in range(0,y):
					for ix in range(0,x):
						image.SetScalarComponentFromDouble(ix,iy,iz,0,0)

		if self.parameters["CreateNoise"]:
			noisePercentage = self.parameters["ShotNoiseAmount"]
			noiseAmount = (noisePercentage/100.0) * (x*y*z)
			print "Creating shot noise"
		else:
			noiseAmount = 0

		shotNoiseMin = self.parameters["ShotNoiseMin"]
		shotNoiseMax = self.parameters["ShotNoiseMax"]
		shotNoiseDistr = self.parameters["ShotNoiseDistribution"]

		while noiseAmount > 0:
			rx,ry,rz = random.randint(0,x-1), random.randint(0,y-1), random.randint(0,z-1)
			shotInt = self.generateDistributionValue(shotNoiseDistr, shotNoiseMin, shotNoiseMax)				
			image.SetScalarComponentFromDouble(rx,ry,rz,0,shotInt)
			noiseAmount -= 1

		#shiftx, shifty, shiftz = self.shifts[currentTimepoint]
		
		print "Creating objects",currentTimepoint
		for oIter, (objN, (rx,ry,rz), size, objInt) in enumerate(self.objects[currentTimepoint]):
			#rx += shiftx
			#ry += shifty
			#rz += shiftz

			(rx,ry,rz), realSize, intList, voxelList = self.createObjectAt(image, rx,ry,rz, size, objInt)
			objMean, objStd, objStdErr = lib.Math.meanstdeverr(intList)
			# Change possible new size and com to object
			self.objects[currentTimepoint][oIter] = (objN, (rx,ry,rz), realSize, (objMean, objStdErr), voxelList)

		if self.parameters["ObjectsCreateSource"]:
			locator = vtk.vtkOBBTree()
			locator.SetDataSet(self.polydata)
			locator.BuildLocator()
			pointLocator = vtk.vtkPointLocator()
			pointLocator.SetDataSet(self.polydata)
			pointLocator.BuildLocator()
			objPolyTP = []
			for objN, (cx, cy, cz), size, meanInt, voxelList in self.objects[currentTimepoint]:
				cxs = cx * self.spacing[0]
				cys = cy * self.spacing[1]
				czs = cz * self.spacing[2]
				locatorInside = locator.InsideOrOutside((cxs,cys,czs))
				if locatorInside == -1:
					inside = 1
				else:
					inside = 0
				
				percVoxelsInside = 0.0
				numIn = 0
				for (vx,vy,vz) in voxelList:
					vxs = vx * self.spacing[0]
					vys = vy * self.spacing[1]
					vzs = vz * self.spacing[2]
					locatorInside = locator.InsideOrOutside((vxs,vys,vzs))
					if locatorInside == -1:
						numIn += 1
				percVoxelsInside = float(numIn) / len(voxelList)

				objid = pointLocator.FindClosestPoint((cxs, cys, czs))
				x2,y2,z2 = self.polydata.GetPoint(objid)
				x2 /= self.spacing[0]
				y2 /= self.spacing[1]
				z2 /= self.spacing[2]

				distToSurf = self.distance((cx,cy,cz), (x2,y2,z2), self.voxelSize)
				distToCom = self.distance((cx,cy,cz), self.cellCOM, self.voxelSize)
				objPolyTP.append((objN, (cx,cy,cz), distToSurf, distToCom, inside, percVoxelsInside))
			self.objPolydata[currentTimepoint] = objPolyTP
		
		n = len(self.imageCache.items())
		if n > self.parameters["CacheAmount"]:
			items = self.imageCache.keys()
			items.sort()
			print "Removing ", items[0], "from cache"
			self.imageCache[items[0]].ReleaseData()
			del self.imageCache[items[0]]
		self.imageCache[currentTimepoint] = image

		self.progressObj.setProgress(currentTimepoint/self.parameters["Time"])
		self.updateProgress(None, "ProgressEvent")

		return image
Example #50
0
def volume(vol,voxsz=(1.0,1.0,1.0),affine=None,center_origin=1,info=1,maptype=0,trilinear=1,iso=0,iso_thr=100,opacitymap=None,colormap=None):    
    ''' Create a volume and return a volumetric actor using volumetric rendering. 
    This function has many different interesting capabilities. The maptype, opacitymap and colormap are the most crucial parameters here.
    
    Parameters:
    ----------------
    vol : array, shape (N, M, K), dtype uint8
         an array representing the volumetric dataset that we want to visualize using volumetric rendering            
        
    voxsz : sequence of 3 floats
            default (1., 1., 1.)
            
    affine : array, shape (4,4), default None
            as given by volumeimages             
            
    center_origin : int {0,1}, default 1
             it considers that the center of the volume is the 
            point (-vol.shape[0]/2.0+0.5,-vol.shape[1]/2.0+0.5,-vol.shape[2]/2.0+0.5)
            
    info : int {0,1}, default 1
            if 1 it prints out some info about the volume, the method and the dataset.
            
    trilinear: int {0,1}, default 1
            Use trilinear interpolation, default 1, gives smoother rendering. If you want faster interpolation use 0 (Nearest).
            
    maptype : int {0,1}, default 0,        
            The maptype is a very important parameter which affects the raycasting algorithm in use for the rendering. 
            The options are:
            If 0 then vtkVolumeTextureMapper2D is used.
            If 1 then vtkVolumeRayCastFunction is used.
            
    iso : int {0,1} default 0,
            If iso is 1 and maptype is 1 then  we use vtkVolumeRayCastIsosurfaceFunction which generates an isosurface at 
            the predefined iso_thr value. If iso is 0 and maptype is 1 vtkVolumeRayCastCompositeFunction is used.
            
    iso_thr : int, default 100,
            if iso is 1 then then this threshold in the volume defines the value which will be used to create the isosurface.
            
    opacitymap : array, shape (N,2), default None.
            The opacity map assigns a transparency coefficient to every point in the volume.
            The default value uses the histogram of the volume to calculate the opacitymap.
    colormap : array, shape (N,4), default None.
            The color map assigns a color value to every point in the volume.
            When None from the histogram it uses a red-blue colormap.
                
    Returns:
    ----------
    vtkVolume    
    
    Notes:
    --------
    What is the difference between TextureMapper2D and RayCastFunction? 
    Coming soon... See VTK user's guide [book] & The Visualization Toolkit [book] and VTK's online documentation & online docs.
    
    What is the difference between RayCastIsosurfaceFunction and RayCastCompositeFunction?
    Coming soon... See VTK user's guide [book] & The Visualization Toolkit [book] and VTK's online documentation & online docs.
    
    What about trilinear interpolation?
    Coming soon... well when time permits really ... :-)
    
    Examples:
    ------------
    First example random points    
    
    >>> from dipy.viz import fos
    >>> import numpy as np
    >>> vol=100*np.random.rand(100,100,100)
    >>> vol=vol.astype('uint8')
    >>> print vol.min(), vol.max()
    >>> r = fos.ren()
    >>> v = fos.volume(vol)
    >>> fos.add(r,v)
    >>> fos.show(r)
    
    Second example with a more complicated function
        
    >>> from dipy.viz import fos
    >>> import numpy as np
    >>> x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
    >>> s = np.sin(x*y*z)/(x*y*z)
    >>> r = fos.ren()
    >>> v = fos.volume(s)
    >>> fos.add(r,v)
    >>> fos.show(r)
    
    If you find this function too complicated you can always use mayavi. 
    Please do not forget to use the -wthread switch in ipython if you are running mayavi.
    
    >>> from enthought.mayavi import mlab       
    >>> import numpy as np
    >>> x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
    >>> s = np.sin(x*y*z)/(x*y*z)
    >>> mlab.pipeline.volume(mlab.pipeline.scalar_field(s))
    >>> mlab.show()
    
    More mayavi demos are available here:
    
    http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html
    
    '''
    if vol.ndim!=3:    
        raise ValueError('3d numpy arrays only please')
    
    if info :
        print('Datatype',vol.dtype,'converted to uint8' )
    
    vol=np.interp(vol,[vol.min(),vol.max()],[0,255])
    vol=vol.astype('uint8')

    if opacitymap==None:
        
        bin,res=np.histogram(vol.ravel())
        res2=np.interp(res,[vol.min(),vol.max()],[0,1])
        opacitymap=np.vstack((res,res2)).T
        opacitymap=opacitymap.astype('float32')
                
        '''
        opacitymap=np.array([[ 0.0, 0.0],
                          [50.0, 0.9]])
        ''' 

    if info:
        print 'opacitymap', opacitymap
        
    if colormap==None:

        bin,res=np.histogram(vol.ravel())
        res2=np.interp(res,[vol.min(),vol.max()],[0,1])
        zer=np.zeros(res2.shape)
        colormap=np.vstack((res,res2,zer,res2[::-1])).T
        colormap=colormap.astype('float32')

        '''
        colormap=np.array([[0.0, 0.5, 0.0, 0.0],
                                        [64.0, 1.0, 0.5, 0.5],
                                        [128.0, 0.9, 0.2, 0.3],
                                        [196.0, 0.81, 0.27, 0.1],
                                        [255.0, 0.5, 0.5, 0.5]])
        '''

    if info:
        print 'colormap', colormap                        
    
    im = vtk.vtkImageData()
    im.SetScalarTypeToUnsignedChar()
    im.SetDimensions(vol.shape[0],vol.shape[1],vol.shape[2])
    #im.SetOrigin(0,0,0)
    #im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])
    im.AllocateScalars()        
    
    for i in range(vol.shape[0]):
        for j in range(vol.shape[1]):
            for k in range(vol.shape[2]):
                
                im.SetScalarComponentFromFloat(i,j,k,0,vol[i,j,k])
    
    if affine != None:

        aff = vtk.vtkMatrix4x4()
        aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],affine[0,3],affine[1,0],affine[1,1],affine[1,2],affine[1,3],affine[2,0],affine[2,1],affine[2,2],affine[2,3],affine[3,0],affine[3,1],affine[3,2],affine[3,3]))
        #aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],0,affine[1,0],affine[1,1],affine[1,2],0,affine[2,0],affine[2,1],affine[2,2],0,affine[3,0],affine[3,1],affine[3,2],1))
        #aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],127.5,affine[1,0],affine[1,1],affine[1,2],-127.5,affine[2,0],affine[2,1],affine[2,2],-127.5,affine[3,0],affine[3,1],affine[3,2],1))
        
        reslice = vtk.vtkImageReslice()
        reslice.SetInput(im)
        #reslice.SetOutputDimensionality(2)
        #reslice.SetOutputOrigin(127,-145,147)    
        
        reslice.SetResliceAxes(aff)
        #reslice.SetOutputOrigin(-127,-127,-127)    
        #reslice.SetOutputExtent(-127,128,-127,128,-127,128)
        #reslice.SetResliceAxesOrigin(0,0,0)
        #print 'Get Reslice Axes Origin ', reslice.GetResliceAxesOrigin()
        #reslice.SetOutputSpacing(1.0,1.0,1.0)
        
        reslice.SetInterpolationModeToLinear()    
        #reslice.UpdateWholeExtent()
        
        #print 'reslice GetOutputOrigin', reslice.GetOutputOrigin()
        #print 'reslice GetOutputExtent',reslice.GetOutputExtent()
        #print 'reslice GetOutputSpacing',reslice.GetOutputSpacing()
    
        changeFilter=vtk.vtkImageChangeInformation() 
        changeFilter.SetInput(reslice.GetOutput())
        #changeFilter.SetInput(im)
        if center_origin:
            changeFilter.SetOutputOrigin(-vol.shape[0]/2.0+0.5,-vol.shape[1]/2.0+0.5,-vol.shape[2]/2.0+0.5)
            print 'ChangeFilter ', changeFilter.GetOutputOrigin()
        
    opacity = vtk.vtkPiecewiseFunction()
    for i in range(opacitymap.shape[0]):
        opacity.AddPoint(opacitymap[i,0],opacitymap[i,1])

    color = vtk.vtkColorTransferFunction()
    for i in range(colormap.shape[0]):
        color.AddRGBPoint(colormap[i,0],colormap[i,1],colormap[i,2],colormap[i,3])
        
    if(maptype==0): 
    
        property = vtk.vtkVolumeProperty()
        property.SetColor(color)
        property.SetScalarOpacity(opacity)
        
        if trilinear:
            property.SetInterpolationTypeToLinear()
        else:
            prop.SetInterpolationTypeToNearest()
            
        if info:
            print('mapper VolumeTextureMapper2D')
        mapper = vtk.vtkVolumeTextureMapper2D()
        if affine == None:
            mapper.SetInput(im)
        else:
            #mapper.SetInput(reslice.GetOutput())
            mapper.SetInput(changeFilter.GetOutput())
        
    
    if (maptype==1):

        property = vtk.vtkVolumeProperty()
        property.SetColor(color)
        property.SetScalarOpacity(opacity)
        property.ShadeOn()
        if trilinear:
            property.SetInterpolationTypeToLinear()
        else:
            prop.SetInterpolationTypeToNearest()

        if iso:
            isofunc=vtk.vtkVolumeRayCastIsosurfaceFunction()
            isofunc.SetIsoValue(iso_thr)
        else:
            compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
        
        if info:
            print('mapper VolumeRayCastMapper')
            
        mapper = vtk.vtkVolumeRayCastMapper()
        if iso:
            mapper.SetVolumeRayCastFunction(isofunc)
            if info:
                print('Isosurface')
        else:
            mapper.SetVolumeRayCastFunction(compositeFunction)   
            
            #mapper.SetMinimumImageSampleDistance(0.2)
            if info:
                print('Composite')
             
        if affine == None:
            mapper.SetInput(im)
        else:
            #mapper.SetInput(reslice.GetOutput())    
            mapper.SetInput(changeFilter.GetOutput())
            #Return mid position in world space    
            #im2=reslice.GetOutput()
            #index=im2.FindPoint(vol.shape[0]/2.0,vol.shape[1]/2.0,vol.shape[2]/2.0)
            #print 'Image Getpoint ' , im2.GetPoint(index)
           
        
    volum = vtk.vtkVolume()
    volum.SetMapper(mapper)
    volum.SetProperty(property)

    if info :  
         
        print 'Origin',   volum.GetOrigin()
        print 'Orientation',   volum.GetOrientation()
        print 'OrientationW',    volum.GetOrientationWXYZ()
        print 'Position',    volum.GetPosition()
        print 'Center',    volum.GetCenter()  
        print 'Get XRange', volum.GetXRange()
        print 'Get YRange', volum.GetYRange()
        print 'Get ZRange', volum.GetZRange()  
        print 'Volume data type', vol.dtype
        
    return volum
Example #51
0
    def smoothMultipleSegments(self, maskImage=None, maskExtent=None):
        import vtkSegmentationCorePython as vtkSegmentationCore

        self.showStatusMessage(f'Joint smoothing ...')
        # Generate merged labelmap of all visible segments
        segmentationNode = self.scriptedEffect.parameterSetNode(
        ).GetSegmentationNode()
        visibleSegmentIds = vtk.vtkStringArray()
        segmentationNode.GetDisplayNode().GetVisibleSegmentIDs(
            visibleSegmentIds)
        if visibleSegmentIds.GetNumberOfValues() == 0:
            logging.info(
                "Smoothing operation skipped: there are no visible segments")
            return

        mergedImage = slicer.vtkOrientedImageData()
        if not segmentationNode.GenerateMergedLabelmapForAllSegments(
                mergedImage, vtkSegmentationCore.vtkSegmentation.
                EXTENT_UNION_OF_SEGMENTS_PADDED, None, visibleSegmentIds):
            logging.error(
                'Failed to apply smoothing: cannot get list of visible segments'
            )
            return

        segmentLabelValues = []  # list of [segmentId, labelValue]
        for i in range(visibleSegmentIds.GetNumberOfValues()):
            segmentId = visibleSegmentIds.GetValue(i)
            segmentLabelValues.append([segmentId, i + 1])

        # Perform smoothing in voxel space
        ici = vtk.vtkImageChangeInformation()
        ici.SetInputData(mergedImage)
        ici.SetOutputSpacing(1, 1, 1)
        ici.SetOutputOrigin(0, 0, 0)

        # Convert labelmap to combined polydata
        # vtkDiscreteFlyingEdges3D cannot be used here, as in the output of that filter,
        # each labeled region is completely disconnected from neighboring regions, and
        # for joint smoothing it is essential for the points to move together.
        convertToPolyData = vtk.vtkDiscreteMarchingCubes()
        convertToPolyData.SetInputConnection(ici.GetOutputPort())
        convertToPolyData.SetNumberOfContours(len(segmentLabelValues))

        contourIndex = 0
        for segmentId, labelValue in segmentLabelValues:
            convertToPolyData.SetValue(contourIndex, labelValue)
            contourIndex += 1

        # Low-pass filtering using Taubin's method
        smoothingFactor = self.scriptedEffect.doubleParameter(
            "JointTaubinSmoothingFactor")
        smoothingIterations = 100  # according to VTK documentation 10-20 iterations could be enough but we use a higher value to reduce chance of shrinking
        passBand = pow(
            10.0, -4.0 * smoothingFactor
        )  # gives a nice range of 1-0.0001 from a user input of 0-1
        smoother = vtk.vtkWindowedSincPolyDataFilter()
        smoother.SetInputConnection(convertToPolyData.GetOutputPort())
        smoother.SetNumberOfIterations(smoothingIterations)
        smoother.BoundarySmoothingOff()
        smoother.FeatureEdgeSmoothingOff()
        smoother.SetFeatureAngle(90.0)
        smoother.SetPassBand(passBand)
        smoother.NonManifoldSmoothingOn()
        smoother.NormalizeCoordinatesOn()

        # Extract a label
        threshold = vtk.vtkThreshold()
        threshold.SetInputConnection(smoother.GetOutputPort())

        # Convert to polydata
        geometryFilter = vtk.vtkGeometryFilter()
        geometryFilter.SetInputConnection(threshold.GetOutputPort())

        # Convert polydata to stencil
        polyDataToImageStencil = vtk.vtkPolyDataToImageStencil()
        polyDataToImageStencil.SetInputConnection(
            geometryFilter.GetOutputPort())
        polyDataToImageStencil.SetOutputSpacing(1, 1, 1)
        polyDataToImageStencil.SetOutputOrigin(0, 0, 0)
        polyDataToImageStencil.SetOutputWholeExtent(mergedImage.GetExtent())

        # Convert stencil to image
        stencil = vtk.vtkImageStencil()
        emptyBinaryLabelMap = vtk.vtkImageData()
        emptyBinaryLabelMap.SetExtent(mergedImage.GetExtent())
        emptyBinaryLabelMap.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
        vtkSegmentationCore.vtkOrientedImageDataResample.FillImage(
            emptyBinaryLabelMap, 0)
        stencil.SetInputData(emptyBinaryLabelMap)
        stencil.SetStencilConnection(polyDataToImageStencil.GetOutputPort())
        stencil.ReverseStencilOn()
        stencil.SetBackgroundValue(
            1
        )  # General foreground value is 1 (background value because of reverse stencil)

        imageToWorldMatrix = vtk.vtkMatrix4x4()
        mergedImage.GetImageToWorldMatrix(imageToWorldMatrix)

        # TODO: Temporarily setting the overwrite mode to OverwriteVisibleSegments is an approach that should be change once additional
        # layer control options have been implemented. Users may wish to keep segments on separate layers, and not allow them to be separated/merged automatically.
        # This effect could leverage those options once they have been implemented.
        oldOverwriteMode = self.scriptedEffect.parameterSetNode(
        ).GetOverwriteMode()
        self.scriptedEffect.parameterSetNode().SetOverwriteMode(
            slicer.vtkMRMLSegmentEditorNode.OverwriteVisibleSegments)
        for segmentId, labelValue in segmentLabelValues:
            threshold.ThresholdBetween(labelValue, labelValue)
            stencil.Update()
            smoothedBinaryLabelMap = slicer.vtkOrientedImageData()
            smoothedBinaryLabelMap.ShallowCopy(stencil.GetOutput())
            smoothedBinaryLabelMap.SetImageToWorldMatrix(imageToWorldMatrix)
            self.scriptedEffect.modifySegmentByLabelmap(
                segmentationNode, segmentId, smoothedBinaryLabelMap,
                slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet,
                False)
        self.scriptedEffect.parameterSetNode().SetOverwriteMode(
            oldOverwriteMode)
Example #52
0
    def getBoundedMap(self, baseImage, dataLocation, map_cut_size,
                      map_border_size):
        baseImage.Update()
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        y0 = baseExtent[2]
        y1 = baseExtent[3]
        imageLen = [x1 - x0 + 1, y1 - y0 + 1]
        selectionDim = [map_cut_size[0] / 2, map_cut_size[1] / 2]
        dataXLoc = dataLocation[0]
        imageInfo = vtk.vtkImageChangeInformation()
        dataYbounds = [
            dataLocation[1] - selectionDim[1],
            dataLocation[1] + selectionDim[1]
        ]
        vertExtent = [y0, y1]
        bounded_dims = None
        if dataYbounds[0] > -90.0:
            yOffset = dataYbounds[0] + 90.0
            extOffset = int(round((yOffset / 180.0) * imageLen[1]))
            vertExtent[0] = y0 + extOffset
            self.y0 = dataYbounds[0]
        if dataYbounds[1] < 90.0:
            yOffset = 90.0 - dataYbounds[1]
            extOffset = int(round((yOffset / 180.0) * imageLen[1]))
            vertExtent[1] = y1 - extOffset

        overlapsBorder = (
            self.NormalizeMapLon(dataLocation[0] - selectionDim[0]) >
            self.NormalizeMapLon(dataLocation[0] + selectionDim[0]))
        if overlapsBorder:
            cut0 = self.NormalizeMapLon(dataXLoc + selectionDim[0])
            sliceSize = imageLen[0] * ((cut0 - self.map_cut) / 360.0)
            sliceCoord = int(round(x0 + sliceSize))
            extent = list(baseExtent)
            extent[0:2] = [x0, x0 + sliceCoord - 1]
            clip0 = vtk.vtkImageClip()
            clip0.SetInput(baseImage)
            clip0.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0],
                                       vertExtent[1], extent[4], extent[5])
            size0 = extent[1] - extent[0] + 1

            self.x0 = dataLocation[0] - selectionDim[0]
            cut1 = self.NormalizeMapLon(self.x0)
            sliceSize = imageLen[0] * ((cut1 - self.map_cut) / 360.0)
            sliceCoord = int(round(x0 + sliceSize))
            extent[0:2] = [x0 + sliceCoord, x1]
            clip1 = vtk.vtkImageClip()
            clip1.SetInput(baseImage)
            clip1.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0],
                                       vertExtent[1], extent[4], extent[5])
            size1 = extent[1] - extent[0] + 1
            #            print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) )

            append = vtk.vtkImageAppend()
            append.SetAppendAxis(0)
            append.AddInput(clip1.GetOutput())
            append.AddInput(clip0.GetOutput())
            bounded_dims = (size0 + size1, vertExtent[1] - vertExtent[0] + 1)

            imageInfo.SetInputConnection(append.GetOutputPort())

        else:

            self.x0 = dataXLoc - selectionDim[0]
            cut0 = self.NormalizeMapLon(self.x0)
            sliceSize = imageLen[0] * ((cut0 - self.map_cut) / 360.0)
            sliceCoord = int(round(x0 + sliceSize))
            extent = list(baseExtent)
            extent[0] = x0 + sliceCoord - 1

            cut1 = self.NormalizeMapLon(dataXLoc + selectionDim[0])
            sliceSize = imageLen[0] * ((cut1 - self.map_cut) / 360.0)
            sliceCoord = int(round(x0 + sliceSize))
            extent[1] = x0 + sliceCoord
            clip = vtk.vtkImageClip()
            clip.SetInput(baseImage)
            clip.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0],
                                      vertExtent[1], extent[4], extent[5])
            bounded_dims = (extent[1] - extent[0] + 1,
                            vertExtent[1] - vertExtent[0] + 1)
            #            print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) )

            imageInfo.SetInputConnection(clip.GetOutputPort())

        imageInfo.SetOutputOrigin(0.0, 0.0, 0.0)
        imageInfo.SetOutputExtentStart(0, 0, 0)
        imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1],
                                   baseSpacing[2])

        result = imageInfo.GetOutput()
        result.Update()
        return result, bounded_dims
Example #53
0
 def dicomTransform(self, image, image_pos_pat, image_ori_pat):
     """ dicomTransform: transforms an image to a DICOM coordinate frame
     
     INPUTS:
     =======        
     image: (vtkImageData)    Input image to Transform
     image_pos_pat: (list(dicomInfo[0x0020,0x0032].value)))  Image position patient Dicom Tag
     image_ori_pat: (list(dicomInfo[0x0020,0x0037].value))   Image oreintation patient Dicom Tag
     
     OUTPUTS:
     =======
     transformed_image (vtkImageData)    Transformed imaged mapped to dicom coords frame
     transform (vtkTransform)            Transform used
     
     """ 
     # If one considers the localizer plane as a "viewport" onto the DICOM 3D coordinate space, then that viewport is described by its origin, its row unit vector, column unit vector and a normal unit vector (derived from the row and column vectors by taking the cross product). Now if one moves the origin to 0,0,0 and rotates this viewing plane such that the row vector is in the +X direction, the column vector the +Y direction, and the normal in the +Z direction, then one has a situation where the X coordinate now represents a column offset in mm from the localizer's top left hand corner, and the Y coordinate now represents a row offset in mm from the localizer's top left hand corner, and the Z coordinate can be ignored. One can then convert the X and Y mm offsets into pixel offsets using the pixel spacing of the localizer imag
     # Initialize Image orienation
     "Image Orientation Patient Matrix"
     IO = matrix(    [[0, 0,-1, 1],
             [1, 0, 0, 1],
             [0,-1, 0, 1],
             [0, 0, 0, 1]])
     # Assign the 6-Image orientation patient coordinates (from Dicomtags)
     IO[0,0] = image_ori_pat[0]; IO[0,1] = image_ori_pat[1]; IO[0,2] = image_ori_pat[2]; 
     IO[1,0] = image_ori_pat[3]; IO[1,1] = image_ori_pat[4]; IO[1,2] = image_ori_pat[5]; 
     
     # obtain thrid column as the cross product of column 1 y 2
     IO_col1 = [image_ori_pat[0], image_ori_pat[1], image_ori_pat[2]]
     IO_col2 = [image_ori_pat[3], image_ori_pat[4], image_ori_pat[5]]
     IO_col3 = cross(IO_col1, IO_col2)
     
     # assign column 3    
     IO[2,0] = IO_col3[0]; IO[2,1] = IO_col3[1]; IO[2,2] = IO_col3[2]; 
     
     IP =  array([0, 0, 0, 1]) # Initialization Image Position
     IP[0] = image_pos_pat[0]; IP[1] = image_pos_pat[1]; IP[2] = image_pos_pat[2];  
     IO[0,3] = -image_pos_pat[0]; IO[1,3] = -image_pos_pat[1]; IO[2,3] = -image_pos_pat[2]
            
     "Compute Volume Origin"
     origin = IP*IO.I
     
     # Create matrix 4x4
     DICOM_mat = vtk.vtkMatrix4x4();
     DICOM_mat.SetElement(0, 0, IO[0,0])
     DICOM_mat.SetElement(0, 1, IO[0,1])
     DICOM_mat.SetElement(0, 2, IO[0,2])
     DICOM_mat.SetElement(0, 3, IO[0,3])
     
     DICOM_mat.SetElement(1, 0, IO[1,0])
     DICOM_mat.SetElement(1, 1, IO[1,1])
     DICOM_mat.SetElement(1, 2, IO[1,2])
     DICOM_mat.SetElement(1, 3, IO[1,3])
     
     DICOM_mat.SetElement(2, 0, IO[2,0])
     DICOM_mat.SetElement(2, 1, IO[2,1])
     DICOM_mat.SetElement(2, 2, IO[2,2])
     DICOM_mat.SetElement(2, 3, IO[2,3])
     
     DICOM_mat.SetElement(3, 0, IO[3,0])
     DICOM_mat.SetElement(3, 1, IO[3,1])
     DICOM_mat.SetElement(3, 2, IO[3,2])
     DICOM_mat.SetElement(3, 3, IO[3,3])
     #DICOM_mat.Invert()
     
     # Set up the axes    
     transform = vtk.vtkTransform()
     transform.Concatenate(DICOM_mat)
     transform.Update()
     
     # Set up the cube (set up the translation back to zero    
     DICOM_mat_cube = vtk.vtkMatrix4x4();
     DICOM_mat_cube.DeepCopy(DICOM_mat)
     DICOM_mat_cube.SetElement(0, 3, 0)
     DICOM_mat_cube.SetElement(1, 3, 0)
     DICOM_mat_cube.SetElement(2, 3, 0)
         
     transform_cube = vtk.vtkTransform()
     transform_cube.Concatenate(DICOM_mat_cube)
     transform_cube.Update()
      
     # Change info
     # Flip along Y-Z-axis: VTK uses computer graphics convention where the first pixel in memory is shown 
     # in the lower left of the displayed image.
     flipZ_image = vtk.vtkImageFlip()
     flipZ_image.SetInput(image)
     flipZ_image.SetFilteredAxis(2)
     flipZ_image.Update() 
     
     flipY_image = vtk.vtkImageFlip()
     flipY_image.SetInput(flipZ_image.GetOutput())
     flipY_image.SetFilteredAxis(1)
     flipY_image.Update() 
       
     # Change info origin
     flipY_origin_image = vtk.vtkImageChangeInformation()
     flipY_origin_image.SetInput( flipY_image.GetOutput() );
     flipY_origin_image.SetOutputOrigin(origin[0,0], origin[0,1], origin[0,2])
     flipY_origin_image.Update()
     
     transformed_image = flipY_origin_image.GetOutput()
     
     transformed_image.UpdateInformation()
     self.dims = transformed_image.GetDimensions()
     print "Image Dimensions"
     print self.dims
     (xMin, xMax, yMin, yMax, zMin, zMax) = transformed_image.GetWholeExtent()
     print "Image Extension"
     print xMin, xMax, yMin, yMax, zMin, zMax
     self.spacing = transformed_image.GetSpacing()
     print "Image Spacing"
     print self.spacing
     self.origin = transformed_image.GetOrigin()
     print "Image Origin"
     print self.origin
     
     return transformed_image, transform_cube   
    def buildBaseMap(self):
        if self.baseMapActor <> None: self.renderer.RemoveActor( self.baseMapActor )               
        world_map =  None  
        map_border_size = 20 
            
        self.y0 = -90.0  
        self.x0 =  0.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 =  -1 
        if  (self.roi <> None): 
            roi_size = [ self.roi[1] - self.roi[0], self.roi[3] - self.roi[2] ] 
            scale = (self.roi[1] - self.roi[0])/300.0
            border_size = map_border_size * scale
            map_cut_size = [ roi_size[0] + 2*border_size, roi_size[1] + 2*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
        else:
            map_cut_size = [ 360, 180 ]
            
                  
        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:
                dataPosition = [ 180, 0 ] # [ ( 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 )
        image_reader.Update()
        baseImage = image_reader.GetOutput() 
        new_dims, scale = None, None
        if dataPosition == None: 
            old_dims = baseImage.GetDimensions()   
            baseImage = self.RollMap( baseImage ) 
            new_dims = baseImage.GetDimensions()
            scale = [ 360.0/new_dims[0], 180.0/new_dims[1], 1 ]
        else:                       
            baseImage, new_dims = self.getBoundedMap( baseImage, dataPosition, map_cut_size, 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[0] )
        mapCorner = [ self.x0, self.y0 ]
#         self.xcenter = self.x0 
#         self.ycenter = self.y0
#        self.adjustCamera( baseImage )
                
        self.baseMapActor.SetPosition( mapCorner[0], mapCorner[1], 0.1 )
        if vtk.VTK_MAJOR_VERSION <= 5:  self.baseMapActor.SetInput(baseImage)
        else:                           self.baseMapActor.SetInputData(baseImage)        
        self.mapCenter = [ self.x0 + map_cut_size[0]/2.0, self.y0 + map_cut_size[1]/2.0 ]        
        self.renderer.AddActor( self.baseMapActor )