Ejemplo n.º 1
0
def _volume(dimensions, origin, spacing, scalars,
            surface_alpha, resolution, blending, center):
    # Now we can actually construct the visualization
    grid = pyvista.UniformGrid()
    grid.dimensions = dimensions + 1  # inject data on the cells
    grid.origin = origin
    grid.spacing = spacing
    grid.cell_arrays['values'] = scalars

    # Add contour of enclosed volume (use GetOutput instead of
    # GetOutputPort below to avoid updating)
    grid_alg = vtk.vtkCellDataToPointData()
    grid_alg.SetInputDataObject(grid)
    grid_alg.SetPassCellData(False)
    grid_alg.Update()

    if surface_alpha > 0:
        grid_surface = vtk.vtkMarchingContourFilter()
        grid_surface.ComputeNormalsOn()
        grid_surface.ComputeScalarsOff()
        grid_surface.SetInputData(grid_alg.GetOutput())
        grid_surface.SetValue(0, 0.1)
        grid_surface.Update()
        grid_mesh = vtk.vtkPolyDataMapper()
        grid_mesh.SetInputData(grid_surface.GetOutput())
    else:
        grid_mesh = None

    mapper = vtk.vtkSmartVolumeMapper()
    if resolution is None:  # native
        mapper.SetScalarModeToUseCellData()
        mapper.SetInputDataObject(grid)
    else:
        upsampler = vtk.vtkImageReslice()
        upsampler.SetInterpolationModeToLinear()  # default anyway
        upsampler.SetOutputSpacing(*([resolution] * 3))
        upsampler.SetInputConnection(grid_alg.GetOutputPort())
        mapper.SetInputConnection(upsampler.GetOutputPort())
    # Additive, AverageIntensity, and Composite might also be reasonable
    remap = dict(composite='Composite', mip='MaximumIntensity')
    getattr(mapper, f'SetBlendModeTo{remap[blending]}')()
    volume_pos = vtk.vtkVolume()
    volume_pos.SetMapper(mapper)
    dist = grid.length / (np.mean(grid.dimensions) - 1)
    volume_pos.GetProperty().SetScalarOpacityUnitDistance(dist)
    if center is not None and blending == 'mip':
        # We need to create a minimum intensity projection for the neg half
        mapper_neg = vtk.vtkSmartVolumeMapper()
        if resolution is None:  # native
            mapper_neg.SetScalarModeToUseCellData()
            mapper_neg.SetInputDataObject(grid)
        else:
            mapper_neg.SetInputConnection(upsampler.GetOutputPort())
        mapper_neg.SetBlendModeToMinimumIntensity()
        volume_neg = vtk.vtkVolume()
        volume_neg.SetMapper(mapper_neg)
        volume_neg.GetProperty().SetScalarOpacityUnitDistance(dist)
    else:
        volume_neg = None
    return grid, grid_mesh, volume_pos, volume_neg
Ejemplo n.º 2
0
def ipl_erosion(image_in, erode_distance):
    ipl_erosion_settings(erode_distance)
    extent = image_in.GetExtent()

    #Actual distance of pixel erosion
    distance = erode_distance + 1

    pad = vtk.vtkImageReslice()
    pad.SetInput(image_in)
    pad.SetOutputExtent(extent[0], extent[1], extent[2], extent[3], extent[4],
                        extent[5])
    pad.Update()

    #Kernel size is twice the dilation distance plus one for the center voxel
    erode = vtk.vtkImageContinuousErode3D()
    erode.SetInputConnection(pad.GetOutputPort())
    erode.SetKernelSize(2 * distance + 1, 2 * distance + 1, 2 * distance + 1)
    erode.Update()

    voi = vtk.vtkExtractVOI()
    voi.SetInput(erode.GetOutput())
    voi.SetVOI(extent[0] + distance, extent[1] - distance,
               extent[2] + distance, extent[3] - distance,
               extent[4] + distance, extent[5] - distance)
    voi.Update()

    image_out = voi.GetOutput()
    return image_out
Ejemplo n.º 3
0
    def __init__(self, parent=None):
        super(VTKViewer, self).__init__(parent)

        self.slicePosition = 0
        self.tubeBlocks = None
        self.volume = None
        self.sliceActor = None

        self.hbox = QHBoxLayout(self)

        self.sliceView = QVTKRenderWindowInteractor(self)
        self.hbox.addWidget(self.sliceView)

        self.sliceSlider = SliceSlider(self)
        self.hbox.addWidget(self.sliceSlider)

        self.volumeView = QVTKRenderWindowInteractor(self)
        self.hbox.addWidget(self.volumeView)

        self.sliceSlider.slicePosChanged.connect(self.updateSlice)

        # vtk-producers and filters
        self.producer = vtk.vtkTrivialProducer()
        self.reslice = vtk.vtkImageReslice()
        self.image2worldTransform = vtk.vtkTransform()
        self.tubeProducer = vtk.vtkTrivialProducer()
        self.tubeMapper = vtk.vtkCompositePolyDataMapper2()
        self.tubeActor = vtk.vtkActor()
Ejemplo n.º 4
0
def VTKImageShift(x,u,v,numret=False,interp=True,wrap=False,mirror=False,
   constant=None,cubic=False):
   if type(x) == type(np.arange(2)): i = NumToVTKImage(x)
   else: i = x
   if 0 and int(u) == u and int(v) == v:
      s = vtk.vtkImageTranslateExtent()
      s.SetInput(i)
      s.SetTranslation(u,v,0)
      o = s.GetOutput()
      s.Update()
   else:
      s = vtk.vtkImageReslice()
      s.AutoCropOutputOn()
      if wrap: s.WrapOn()
      else: s.WrapOff()
      if mirror or constant != None: s.MirrorOn()
      else: s.MirrorOff()
      if interp:
        s.InterpolateOn()
        if cubic:
          s.SetInterpolationModeToCubic()
        else:
          s.SetInterpolationModeToLinear()
      else: s.InterpolateOff()
      s.OptimizationOn()
      s.SetOutputOrigin(u,v,0)
      s.SetInputData(i)
      o=s.GetOutput()
      s.Update()
   if numret: return VTKImageToNum(o)
   else: return o
    def __init__(self, source, orientation, opacity=1.0):

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

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

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

        # Display the image
        self.actor = vtk.vtkImageActor()
        self.actor.GetMapper().SetInputConnection(self.color.GetOutputPort())
Ejemplo n.º 6
0
def vtkZoomImage(image, zoomInFactor):
    """
	Zoom a volume
	"""
    zoomOutFactor = 1.0 / zoomInFactor
    reslice = vtk.vtkImageReslice()
    reslice.SetInputConnection(image.GetProducerPort())

    spacing = image.GetSpacing()
    extent = image.GetExtent()
    origin = image.GetOrigin()
    extent = (extent[0], extent[1] / zoomOutFactor, extent[2],
              extent[3] / zoomOutFactor, extent[4], extent[5])

    spacing = (spacing[0] * zoomOutFactor, spacing[1] * zoomOutFactor,
               spacing[2])
    reslice.SetOutputSpacing(spacing)
    reslice.SetOutputExtent(extent)
    reslice.SetOutputOrigin(origin)

    # These interpolation settings were found to have the
    # best effect:
    # If we zoom out, no interpolation
    if zoomOutFactor > 1:
        reslice.InterpolateOff()
    else:
        # If we zoom in, use cubic interpolation
        reslice.SetInterpolationModeToCubic()
        reslice.InterpolateOn()
    data = optimize.execute_limited(reslice)
    data.Update()
    return data
Ejemplo n.º 7
0
    def __init__(self, ren):
        self.volume = self.LoadVolume()
        self.ren = ren

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

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

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

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

        self.actor = vtk.vtkImageActor()
        self.actor.SetInput( self.colors.GetOutput() )
Ejemplo n.º 8
0
    def update_image(self):
        reslice = vtk.vtkImageReslice()

        if self.origin_x is not None:
            # add padding so that origin_x is in the middle of the image
            pad = vtk.vtkImageConstantPad()
            pad.SetInputConnection(self.reader.GetOutputPort())
            pad.SetConstant(BG_HU)

            # GetExtent() returns a tuple (minX, maxX, minY, maxY, minZ, maxZ)
            extent = list(self.reader.GetOutput().GetExtent())
            x_size = extent[1] - extent[0]
            extent[0] -= max(x_size - 2 * self.origin_x, 0)
            extent[1] += max(2 * self.origin_x - x_size, 0)
            pad.SetOutputWholeExtent(*extent)
            reslice.SetInputConnection(pad.GetOutputPort())
        else:
            reslice.SetInputConnection(self.reader.GetOutputPort())

        transform = vtk.vtkPerspectiveTransform()

        # gantry tilt
        transform.Shear(0, *self.shear_params)

        if self.angle_z != 0 or self.angle_y != 0:
            transform.RotateWXYZ(-self.angle_z, 0, 0, 1)  # top
            transform.RotateWXYZ(self.angle_y, 0, 1, 0)  # front

        reslice.SetResliceTransform(transform)
        reslice.SetInterpolationModeToCubic()
        reslice.AutoCropOutputOn()
        reslice.SetBackgroundLevel(BG_HU)
        reslice.Update()

        spacings_lists = reslice.GetOutput().GetSpacing()

        if self.spacing == 'auto':
            min_spacing = min(spacings_lists)
            if not min_spacing:
                raise ValueError('Invalid scan. Path: {}'.format(
                    self.scan_dir))
            spacing = [min_spacing, min_spacing, min_spacing]

        elif self.spacing == 'none':
            spacing = None
        else:
            spacing = self.spacing

        if spacing is None:
            self.image = reslice
        else:
            resample = vtkImageResample()
            resample.SetInputConnection(reslice.GetOutputPort())
            resample.SetAxisOutputSpacing(0, spacing[0])  # x axis
            resample.SetAxisOutputSpacing(1, spacing[1])  # y axis
            resample.SetAxisOutputSpacing(2, spacing[2])  # z axis
            resample.SetInterpolationModeToCubic()
            resample.Update()

            self.image = resample
Ejemplo n.º 9
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self)

        self._imageReslice = vtk.vtkImageReslice()
        self._imageReslice.SetInterpolationModeToCubic()

        self._matrixToHT = vtk.vtkMatrixToHomogeneousTransform()
        self._matrixToHT.Inverse()

        module_utils.setup_vtk_object_progress(self, self._imageReslice,
                                               'Resampling volume')

        self._viewFrame = self._createViewFrame({
            'Module (self)':
            self,
            'vtkImageReslice':
            self._imageReslice
        })

        # pass the data down to the underlying logic
        self.config_to_logic()
        # and all the way up from logic -> config -> view to make sure
        self.syncViewWithLogic()
Ejemplo n.º 10
0
    def GetROIImage(self, clipDataOn=0):
        """Return ROI Image port from ROIStencil"""
        component.getUtility(ICurrentImage).Update()
        minV, maxV = component.getUtility(ICurrentImage).GetScalarRange()
        reslice = vtk.vtkImageReslice()
        reslice.SetInputConnection(
            component.getUtility(ICurrentImage).GetOutputPort())
        reslice.SetInterpolationModeToCubic()

        # 2014-12-22 this is important
        self.__stencil_data.Update()

        # VTK-6
        if vtk.vtkVersion().GetVTKMajorVersion() > 5:
            reslice.SetStencilData(self.__stencil_data)
        else:
            reslice.SetStencil(self.__stencil_data)

        reslice.SetOutputExtent(self.__stencil_data.GetWholeExtent())
        reslice.SetOutputOrigin(self._Origin)
        reslice.SetOutputSpacing(self._Spacing)
        reslice.SetBackgroundLevel(minV)
        reslice.Update()

        return reslice
def vtkZoomImage(image, zoomInFactor):
    """
	Zoom a volume
	"""
    zoomOutFactor = 1.0 / zoomInFactor
    reslice = vtk.vtkImageReslice()
    reslice.SetInputConnection(image.GetProducerPort())

    spacing = image.GetSpacing()
    extent = image.GetExtent()
    origin = image.GetOrigin()
    extent = (extent[0], extent[1] / zoomOutFactor, extent[2], extent[3] / zoomOutFactor, extent[4], extent[5])

    spacing = (spacing[0] * zoomOutFactor, spacing[1] * zoomOutFactor, spacing[2])
    reslice.SetOutputSpacing(spacing)
    reslice.SetOutputExtent(extent)
    reslice.SetOutputOrigin(origin)

    # These interpolation settings were found to have the
    # best effect:
    # If we zoom out, no interpolation
    if zoomOutFactor > 1:
        reslice.InterpolateOff()
    else:
        # If we zoom in, use cubic interpolation
        reslice.SetInterpolationModeToCubic()
        reslice.InterpolateOn()
    data = optimize.execute_limited(reslice)
    data.Update()
    return data
Ejemplo n.º 12
0
    def GetROIImage(self, clipDataOn=0):
        """Return ROI Image port from ROIStencil"""
        component.getUtility(ICurrentImage).Update()
        minV, maxV = component.getUtility(ICurrentImage).GetScalarRange()
        reslice = vtk.vtkImageReslice()
        reslice.SetInputConnection(
            component.getUtility(ICurrentImage).GetOutputPort())
        reslice.SetInterpolationModeToCubic()

        # 2014-12-22 this is important
        self.__stencil_data.Update()

        # VTK-6
        if vtk.vtkVersion().GetVTKMajorVersion() > 5:
            reslice.SetStencilData(self.__stencil_data)
        else:
            reslice.SetStencil(self.__stencil_data)

        reslice.SetOutputExtent(self.__stencil_data.GetWholeExtent())
        reslice.SetOutputOrigin(self._Origin)
        reslice.SetOutputSpacing(self._Spacing)
        reslice.SetBackgroundLevel(minV)
        reslice.Update()

        return reslice
    def __init__(self,data_reader,origin,normal,camera_normal):
        self.axial=self.get_matrix(data_reader,origin,normal,camera_normal)
        # Extract a slice in the desired orientation
        self.reslice = vtk.vtkImageReslice()
        self.reslice.SetInput(data_reader.get_data_set())
        self.reslice.SetOutputDimensionality(2)
        self.reslice.SetResliceAxes(self.axial)
        self.reslice.SetInterpolationModeToLinear()
        
        self.contour=vtk.vtkContourFilter()
        self.contour.SetInputConnection(self.reslice.GetOutputPort())

        self.contour.GenerateValues(25, data_reader.get_scalar_range())
        self.contour.ComputeScalarsOn()
        self.contour.ComputeGradientsOn()      
        self.cutmapper=vtk.vtkPolyDataMapper()
        self.cutmapper.SetInputConnection(self.contour.GetOutputPort())  
        self.actor=vtk.vtkActor()
        self.actor.SetMapper(self.cutmapper)
        self.actor.PokeMatrix(self.axial)
        c="c"
        if origin[0]==c or origin[1]==c or origin[2]==c:
			origin=self.center
        
        origin=(float(origin[0]),float(origin[1]),float(origin[2]))
        self.actor.SetOrigin(origin)		  
Ejemplo n.º 14
0
def vtk_write_mask_as_nifty(mask, image_fn, mask_fn):
    import vtk
    origin = mask.GetOrigin()
    reader = vtk.vtkNIFTIImageReader()
    reader.SetFileName(image_fn)
    reader.Update()
    writer = vtk.vtkNIFTIImageWriter()
    Sign = vtk.vtkMatrix4x4()
    Sign.Identity()
    Sign.SetElement(0, 0, -1)
    Sign.SetElement(1, 1, -1)
    M = reader.GetQFormMatrix()
    if M is None:
        M = reader.GetSFormMatrix()
    M2 = vtk.vtkMatrix4x4()
    M2.Multiply4x4(Sign, M, M2)
    reslice = vtk.vtkImageReslice()
    reslice.SetInputData(mask)
    reslice.SetResliceAxes(M2)
    reslice.SetInterpolationModeToNearestNeighbor()
    reslice.Update()
    mask = reslice.GetOutput()
    mask.SetOrigin([0., 0., 0.])

    writer.SetInputData(mask)
    writer.SetFileName(mask_fn)
    writer.SetQFac(reader.GetQFac())
    q_mat = reader.GetQFormMatrix()
    writer.SetQFormMatrix(q_mat)
    s_mat = reader.GetSFormMatrix()
    writer.SetSFormMatrix(s_mat)
    writer.Write()
    return
Ejemplo n.º 15
0
 def scaleVoxels(self, scale=1):
     """Scale the voxel content by factor `scale`."""
     rsl = vtk.vtkImageReslice()
     rsl.SetInputData(self.imagedata())
     rsl.SetScalarScale(scale)
     rsl.Update()
     return self._update(rsl.GetOutput())
Ejemplo n.º 16
0
def _create_reslice_filter(vtk_obj, axis):
    f = vtk.vtkImageReslice()
    f.SetInputConnection(vtk_obj.GetOutputPort())
    f.SetOutputDimensionality(2)
    f.SetResliceAxes(axis)
    f.SetInterpolationModeToLinear()
    return f
Ejemplo n.º 17
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        self._reslicer = vtk.vtkImageReslice()
        self._probefilter = vtk.vtkProbeFilter()

        self._config.paddingValue = 0.0

        #This is retarded - we (sometimes, see below) need the padder
        #to get the image extent big enough to satisfy the probe filter.
        #No apparent logical reason, but it throws an exception if we don't.
        self._padder = vtk.vtkImageConstantPad()

        configList = [(
            'Padding value:', 'paddingValue', 'base:float', 'text',
            'The value used to pad regions that are outside the supplied volume.'
        )]

        # initialise any mixins we might have
        ScriptedConfigModuleMixin.__init__(
            self, configList, {
                'Module (self)': self,
                'vtkImageReslice': self._reslicer,
                'vtkProbeFilter': self._probefilter,
                'vtkImageConstantPad': self._padder
            })

        module_utils.setup_vtk_object_progress(
            self, self._reslicer, 'Transforming image (Image Reslice)')
        module_utils.setup_vtk_object_progress(
            self, self._probefilter, 'Performing remapping (Probe Filter)')

        self.sync_module_logic_with_config()
Ejemplo n.º 18
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self)


        self._imageReslice = vtk.vtkImageReslice()
        self._imageReslice.SetInterpolationModeToCubic()

        self._matrixToHT = vtk.vtkMatrixToHomogeneousTransform()
        self._matrixToHT.Inverse()


        module_utils.setup_vtk_object_progress(self, self._imageReslice,
                                           'Resampling volume')

        self._viewFrame = self._createViewFrame(
            {'Module (self)' : self,
             'vtkImageReslice' : self._imageReslice})

        # pass the data down to the underlying logic
        self.config_to_logic()
        # and all the way up from logic -> config -> view to make sure
        self.syncViewWithLogic()     
Ejemplo n.º 19
0
def ipl_open(image_in, open):
    ipl_open_settings(open)
    extent = image_in.GetExtent()

    clip = vtk.vtkImageReslice()
    clip.SetInput(image_in)
    clip.SetOutputExtent(extent[0] - open - 2, extent[1] + open + 2,
                         extent[2] - open - 2, extent[3] + open + 2,
                         extent[4] - open - 2, extent[5] + open + 2)
    clip.MirrorOn()
    clip.Update()

    erode = vtk.vtkImageContinuousErode3D()
    erode.SetInputConnection(clip.GetOutputPort())
    erode.SetKernelSize(2 * open + 1, 2 * open + 1, 2 * open + 1)
    erode.Update()

    #Kernel size is twice the dilation distance plus one for the center voxel

    dilate = vtk.vtkImageContinuousDilate3D()
    dilate.SetInputConnection(erode.GetOutputPort())
    dilate.SetKernelSize(2 * open + 1, 2 * open + 1, 2 * open + 1)
    dilate.Update()

    voi = vtk.vtkExtractVOI()
    voi.SetInput(dilate.GetOutput())
    voi.SetVOI(extent[0], extent[1], extent[2], extent[3], extent[4],
               extent[5])
    voi.Update()

    image_out = voi.GetOutput()
    return image_out
Ejemplo n.º 20
0
    def slicePlane(self, origin=(0, 0, 0), normal=(1, 1, 1)):
        """Extract the slice along a given plane position and normal.

        |slicePlane| |slicePlane.py|_
        """
        reslice = vtk.vtkImageReslice()
        reslice.SetInputData(self._data)
        reslice.SetOutputDimensionality(2)
        newaxis = utils.versor(normal)
        pos = np.array(origin)
        initaxis = (0, 0, 1)
        crossvec = np.cross(initaxis, newaxis)
        angle = np.arccos(np.dot(initaxis, newaxis))
        T = vtk.vtkTransform()
        T.PostMultiply()
        T.RotateWXYZ(np.rad2deg(angle), crossvec)
        T.Translate(pos)
        M = T.GetMatrix()
        reslice.SetResliceAxes(M)
        reslice.SetInterpolationModeToLinear()
        reslice.Update()
        vslice = vtk.vtkImageDataGeometryFilter()
        vslice.SetInputData(reslice.GetOutput())
        vslice.Update()
        msh = Mesh(vslice.GetOutput())
        msh.SetOrientation(T.GetOrientation())
        msh.SetPosition(pos)
        return msh
Ejemplo n.º 21
0
def write_vtk_image(vtkIm, fn, M=None):
    """
    This function writes a vtk image to disk
    Args:
        vtkIm: the vtk image to write
        fn: file name
    Returns:
        None
    """
    print("Writing vti with name: ", fn)
    if M is not None:
        M.Invert()
        reslice = vtk.vtkImageReslice()
        reslice.SetInputData(vtkIm)
        reslice.SetResliceAxes(M)
        reslice.SetInterpolationModeToNearestNeighbor()
        reslice.Update()
        vtkIm = reslice.GetOutput()

    _, extension = os.path.splitext(fn)
    if extension == '.vti':
        writer = vtk.vtkXMLImageDataWriter()
    elif extension == '.vtk':
        writer = vtk.vtkStructuredPointsWriter()
    elif extension == '.mhd':
        writer = vtk.vtkMetaImageWriter()
    else:
        raise ValueError("Incorrect extension " + extension)
    writer.SetInputData(vtkIm)
    writer.SetFileName(fn)
    writer.Update()
    writer.Write()
    return
Ejemplo n.º 22
0
    def __init__(self, data_reader, origin, normal, camera_normal):
        self.axial = self.get_matrix(data_reader, origin, normal,
                                     camera_normal)
        # Extract a slice in the desired orientation
        self.reslice = vtk.vtkImageReslice()
        self.reslice.SetInput(data_reader.get_data_set())
        self.reslice.SetOutputDimensionality(2)
        self.reslice.SetResliceAxes(self.axial)
        self.reslice.SetInterpolationModeToLinear()

        self.contour = vtk.vtkContourFilter()
        self.contour.SetInputConnection(self.reslice.GetOutputPort())

        self.contour.GenerateValues(25, data_reader.get_scalar_range())
        self.contour.ComputeScalarsOn()
        self.contour.ComputeGradientsOn()
        self.cutmapper = vtk.vtkPolyDataMapper()
        self.cutmapper.SetInputConnection(self.contour.GetOutputPort())
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.cutmapper)
        self.actor.PokeMatrix(self.axial)
        c = "c"
        if origin[0] == c or origin[1] == c or origin[2] == c:
            origin = self.center

        origin = (float(origin[0]), float(origin[1]), float(origin[2]))
        self.actor.SetOrigin(origin)
Ejemplo n.º 23
0
def dicom_to_vti(imagedata, filename):
    logging.debug("In data.dicom_to_vti()")
    extent = imagedata.GetWholeExtent()
    spacing = imagedata.GetSpacing()
    origin = imagedata.GetOrigin()

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

    resliceAxes = vtk.vtkMatrix4x4()
    vtkMatrix = (1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
    resliceAxes.DeepCopy(vtkMatrix)
    resliceAxes.SetElement(0, 3, center[0])
    resliceAxes.SetElement(1, 3, center[1])
    resliceAxes.SetElement(2, 3, center[2])

    reslice = vtk.vtkImageReslice()
    reslice.SetInput(imagedata)
    reslice.SetInformationInput(imagedata)
    reslice.SetResliceAxes(resliceAxes)
    reslice.SetOutputDimensionality(3)
    reslice.Update()

    imagedata = reslice.GetOutput()
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetInput(imagedata)
    writer.SetFileName(filename)
    writer.Write()
Ejemplo n.º 24
0
    def __init__(self, data_dir, PW, reader):

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

        grx = PW.GetResliceAxes()

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

        self.actor = actor
Ejemplo n.º 25
0
def vtk_write_mask_as_nifty(mask, M, image_fn, mask_fn):
    reader = vtk.vtkNIFTIImageReader()
    reader.SetFileName(image_fn)
    reader.Update()
    writer = vtk.vtkNIFTIImageWriter()
    M.Invert()
    if reader.GetQFac() == -1:
        for i in range(3):
            temp = M.GetElement(i, 2)
            M.SetElement(i, 2, temp * -1)
    reslice = vtk.vtkImageReslice()
    reslice.SetInputData(mask)
    reslice.SetResliceAxes(M)
    reslice.SetInterpolationModeToNearestNeighbor()
    reslice.Update()
    mask = reslice.GetOutput()
    mask.SetOrigin([0., 0., 0.])

    writer.SetInputData(mask)
    writer.SetFileName(mask_fn)
    writer.SetQFac(reader.GetQFac())
    q_mat = reader.GetQFormMatrix()
    writer.SetQFormMatrix(q_mat)
    s_mat = reader.GetSFormMatrix()
    writer.SetSFormMatrix(s_mat)
    writer.Write()
    return
Ejemplo n.º 26
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        self._reslicer = vtk.vtkImageReslice()
        self._probefilter = vtk.vtkProbeFilter()

        self._config.paddingValue = 0.0
        
        #This is retarded - we (sometimes, see below) need the padder 
        #to get the image extent big enough to satisfy the probe filter. 
        #No apparent logical reason, but it throws an exception if we don't.
        self._padder = vtk.vtkImageConstantPad()

        configList = [
            ('Padding value:', 'paddingValue', 'base:float', 'text',
             'The value used to pad regions that are outside the supplied volume.')]        
        
        # initialise any mixins we might have
        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)': self,
             'vtkImageReslice': self._reslicer,
             'vtkProbeFilter': self._probefilter,
             'vtkImageConstantPad': self._padder})

        module_utils.setup_vtk_object_progress(self, self._reslicer,
                                               'Transforming image (Image Reslice)')
        module_utils.setup_vtk_object_progress(self, self._probefilter,
                                               'Performing remapping (Probe Filter)')

        self.sync_module_logic_with_config()
Ejemplo n.º 27
0
def vtkImageResample(image, spacing, opt):
    """
    Resamples the vtk image to the given dimenstion
    Args:
        image: vtk Image data
        spacing: image new spacing
        opt: interpolation option: linear, NN, cubic
    Returns:
        image: resampled vtk image data
    """
    reslicer = vtk.vtkImageReslice()
    reslicer.SetInputData(image)
    if opt == 'linear':
        reslicer.SetInterpolationModeToLinear()
    elif opt == 'NN':
        reslicer.SetInterpolationModeToNearestNeighbor()
    elif opt == 'cubic':
        reslicer.SetInterpolationModeToCubic()
    else:
        raise ValueError("interpolation option not recognized")

    #size = np.array(image.GetSpacing())*np.array(image.GetDimensions())
    #new_spacing = size/np.array(dims)

    reslicer.SetOutputSpacing(*spacing)
    reslicer.Update()

    return reslicer.GetOutput()
Ejemplo n.º 28
0
    def __init__(
        self, parent=None, x=0, y=0, width=100, height=27, fontsize=_FS,
            **kw):

        kw["height"] = height
        kw["width"] = width
        kw["x"] = x
        kw["y"] = y
        kw["fontsize"] = fontsize
        kw["font"] = "courier"
        kw["text"] = "0.000"

        Label.__init__(*(self, parent), **kw)

        self._Cursor = None

        self._Transform = None

        self._Shift = 0.0

        self._Scale = 1.0

        self._Input = None

        self._Reslice = vtk.vtkImageReslice()
        self._Reslice.SetOutputExtent(0, 0, 0, 0, 0, 0)
        self._Reslice.SetInterpolationModeToLinear()
Ejemplo n.º 29
0
 def __init__(self):
     self.__vtkimport=vtk.vtkImageImport()
     self.__vtkimport.SetDataScalarTypeToFloat()
     self.__vtkimport.SetNumberOfScalarComponents(1)
     self.__filePattern=self.__defaultFilePattern
     self.__data = None
     self._irs = vtk.vtkImageReslice()
Ejemplo n.º 30
0
def vtk_resample_with_info_dict(image, img_info, order=1):
    interp = vtk.vtkImageInterpolator()
    if order == 1:
        interp.SetInterpolationModeToLinear()
    elif order == 0:
        interp.SetInterpolationModeToNearest()
    elif order == 3:
        interp.SetInterpolationModeToCubic()
    else:
        raise ValueError("interpolation option not recognized")
    size = image.GetDimensions()
    reference_spacing = np.array(img_info['size']) / np.array(size) * np.array(
        img_info['spacing'])
    reference_spacing = np.mean(reference_spacing) * np.ones(3)
    image.SetSpacing(reference_spacing)
    resize = vtk.vtkImageReslice()
    resize.SetInputData(image)
    resize.SetInterpolator(interp)
    resize.SetBackgroundLevel(0.)
    resize.SetOutputExtent(img_info['extent'])
    resize.SetOutputSpacing(img_info['spacing'])
    resize.Update()
    im = resize.GetOutput()
    im.SetOrigin(img_info['origin'])
    return im
Ejemplo n.º 31
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageReslice(), 'Processing.',
         ('vtkImageData', 'vtkImageStencilData'), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 32
0
def read_label_map(fn):
    """ 
    This function imports the label map as vtk image.

    Args: 
        fn: filename of the label map

    Return:
        label: label map as a vtk image
    """
    _, ext = fn.split(os.extsep, 1)

    if fn[-3:] == 'vti':
        reader = vtk.vtkXMLImageDataReader()
        reader.SetFileName(fn)
        reader.Update()
        label = reader.GetOutput()
    elif ext[-3:] == 'nii' or ext[-6:] == 'nii.gz':
        reader = vtk.vtkNIFTIImageReader()
        reader.SetFileName(fn)
        reader.Update()

        image = reader.GetOutput()
        matrix = reader.GetQFormMatrix()
        if matrix is None:
            matrix = reader.GetSFormMatrix()
        matrix.Invert()
        reslice = vtk.vtkImageReslice()
        reslice.SetInputData(image)
        reslice.SetResliceAxes(matrix)
        reslice.SetInterpolationModeToNearestNeighbor()
        reslice.Update()
        reslice2 = vtk.vtkImageReslice()
        reslice2.SetInputData(reslice.GetOutput())
        matrix = vtk.vtkMatrix4x4()
        for i in range(4):
            matrix.SetElement(i, i, 1)
        matrix.SetElement(0, 0, -1)
        matrix.SetElement(1, 1, -1)
        reslice2.SetResliceAxes(matrix)
        reslice2.SetInterpolationModeToNearestNeighbor()
        reslice2.Update()
        label = reslice2.GetOutput()
    else:
        raise IOError("File extension is not recognized")

    return label
    def __init__(self, im_data, orie='Sagittal'):

        # orie
        self.orie = orie

        source = im_data.im_src

        self.translation = [0, 0]

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

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

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

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

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

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

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

        # Display the image
        self.actor = vtk.vtkImageActor()
        self.actor.GetMapper().SetInputConnection(self.color.GetOutputPort())
Ejemplo n.º 34
0
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
Ejemplo n.º 35
0
def translate3D(image, dx, dy, dz):
    t1 = vtk.vtkTransform()
    t1.Translate(dx,dy,dz)
    reslice = vtk.vtkImageReslice()
    reslice.SetInput(image)
    reslice.SetOutputDimensionality(3)
    reslice.SetResliceAxes(t1.GetInverse().GetMatrix())
    return reslice.GetOutput()
Ejemplo n.º 36
0
def resliceWithNearestNeighbor(image, outSpacing):
    reslice = vtk.vtkImageReslice()
    reslice.SetInput(image)
    reslice.SetInterpolationModeToNearestNeighbor()
    reslice.SetOutputSpacing([outSpacing[0],outSpacing[1],outSpacing[2]])
    reslice.SetOutputOrigin(image.GetOrigin())
    reslice.Update()
    return reslice.GetOutput()   
Ejemplo n.º 37
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()
Ejemplo n.º 38
0
    def applyReslice(self, icp, reader):
        # reslice the image to display tranformation
        rslice = vtk.vtkImageReslice()
        rslice.SetInputData(reader.GetOutput())
        rslice.SetInterpolationModeToLinear()
        rslice.SetResliceAxes(icp.GetMatrix())
        rslice.Update()

        return rslice  # Data
Ejemplo n.º 39
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()
 def __init__(self):
     # index
     self.ori_index = [0,0,0]
     self.ori_direction = [1,1,1] #cosine
     self.cur_index = [0,0,0]
     self.cur_direction = [1,1,1] #cosine
     #define reslice fileter
     self.reslicer = vtk.vtkImageReslice()
     self.reslicer.SetOutputDimensionality(2) #output 2D resliced image
     self.reslicer.SetResliceAxesDirectionCosines([0,0,0,0,0,0,0,0,0])#(self.cur_direction[1],self.cur_direction[1],self.cur_direction[1])
     self.reslicer.SetResliceAxesOrigin(0,0,0)#(self.cur_index)
     self.reslicer.SetInterpolationModeToLinear()
Ejemplo n.º 41
0
def reslice(img, transform, data):
    reslicer=vtk.vtkImageReslice()

    reslicer.SetInputData(img)

    transform = numpy2vtkMatrix(transform)
    vtkTrans = vtk.vtkMatrixToHomogeneousTransform()
    vtkTrans.SetInput(transform)

    reslicer.SetResliceTransform(vtkTrans)
    reslicer.SetOutputOrigin(data.GetOrigin())
    reslicer.SetOutputSpacing(data.GetSpacing())
    reslicer.SetOutputExtent(data.GetExtent())
Ejemplo n.º 42
0
    def SetImageTransform(self, transform):
        """Set optionally the transform to the image data."""

        # TODO: this code is broken...

        self._imageTransform = transform
        reslice = vtk.vtkImageReslice()
        reslice.SetInterpolationModeToCubic()
        image = component.getUtility(ICurrentImage)
        reslice.SetInputConnection(image.GetOutputPort())
        reslice.SetResliceTransform(self._imageTransform.GetInverse())
        self._imageStats.SetInputConnection(reslice.GetOutputPort())
        self._imageStats.SetProgressText("Calculating image stats...")
Ejemplo n.º 43
0
def FixGantryTilt(imagedata, tilt):
    """
    Fix gantry tilt given a vtkImageData and the tilt value. Return new
    vtkImageData.
    """

    # Retrieve data from original imagedata
    extent = [int(value) for value in imagedata.GetExtent()]
    origin = imagedata.GetOrigin()
    spacing = [float(value) for value in imagedata.GetSpacing()]

    n_slices = int(extent[5])
    new_zspacing = math.cos(tilt*(math.acos(-1.0)/180.0)) * spacing[2] #zspacing
    translate_coef = math.tan(tilt*math.pi/180.0)*new_zspacing*(n_slices-1)

    # Class responsible for translating data
    reslice = vtk.vtkImageReslice()
    reslice.SetInput(imagedata)
    reslice.SetInterpolationModeToLinear()
    # Translation will create new pixels. Let's set new pixels' colour to black.
    reslice.SetBackgroundLevel(imagedata.GetScalarRange()[0])

    # Class responsible for append translated data
    append = vtk.vtkImageAppend()
    append.SetAppendAxis(2)

    # Translate and append each slice
    for i in xrange(n_slices+1):
        slice_imagedata = vtk.vtkImageData()
        value = math.tan(tilt*math.pi/180.0) * new_zspacing * i
        new_origin1 = origin[1] + value - translate_coef
        # Translate data
        reslice.SetOutputOrigin(origin[0], new_origin1, origin[2])
        reslice.SetOutputExtent(extent[0], extent[1], extent[2], extent[3], i,i)
        reslice.Update()
        # Append data
        slice_imagedata.DeepCopy(reslice.GetOutput())
        slice_imagedata.UpdateInformation()

        append.AddInput(slice_imagedata)

    append.Update()

    # Final imagedata
    imagedata = vtk.vtkImageData()
    imagedata.DeepCopy(append.GetOutput())
    imagedata.SetSpacing(spacing[0], spacing[1], new_zspacing)
    imagedata.SetExtent(extent)
    imagedata.UpdateInformation()

    return imagedata
def scaleImage(data, factor=1.0, zDimension=-1, interpolation=1, xfactor=0.0, yfactor=0.0):
    """
	Scale an image with cubic interpolation
	"""
    if zDimension != -1:
        data = getSlice(data, zDimension)
    data.SetSpacing(1, 1, 1)
    xDimension, yDimension, zDimension = data.GetDimensions()
    data.SetOrigin(xDimension / 2.0, yDimension / 2.0, 0)
    transform = vtk.vtkTransform()
    xExtent0, xExtent1, yExtent0, yExtent1, zExtent0, zExtent1 = data.GetExtent()
    if xfactor or yfactor:
        xfactor *= factor
        yfactor *= factor

    if not (xfactor or yfactor):
        transform.Scale(1 / factor, 1 / factor, 1)
    else:
        transform.Scale(1 / xfactor, 1 / yfactor, 1)

    reslice = vtk.vtkImageReslice()
    reslice.SetOutputOrigin(0, 0, 0)
    reslice.SetInputConnection(data.GetProducerPort())

    if not (xfactor or yfactor):
        xfactor = factor
        yfactor = factor

    xSize = (xExtent1 - xExtent0 + 1) * xfactor
    xExtent0 *= xfactor
    xExtent1 = xExtent0 + xSize - 1
    ySize = (yExtent1 - yExtent0 + 1) * yfactor
    yExtent0 *= yfactor
    yExtent1 = yExtent0 + ySize - 1

    reslice.SetOutputExtent(int(xExtent0), int(xExtent1), int(yExtent0), int(yExtent1), zExtent0, zExtent1)

    reslice.SetResliceTransform(transform)
    if interpolation == 0:
        reslice.SetInterpolationModeToNearestNeighbor()
    if interpolation == 1:
        reslice.SetInterpolationModeToLinear()
    else:
        reslice.SetInterpolationModeToCubic()
        # XXX: modified, try to get errors out

    data = reslice.GetOutput()
    data.Update()

    return data
Ejemplo n.º 45
0
def transform_all_images_lps_to_ras(image_datas):
    image_list = list()
    for image in image_datas:
        resample = vtk.vtkImageReslice()
        resample.SetResliceAxesDirectionCosines(-1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, -1.0)
        resample.SetInput(image)
        #resample.SetResliceTransform(trans)
        #print trans
        #resample.SetInformationInput(info.GetOutput())
        resample.Update()
        #resample.SetOutputOrigin(origin)
        image_list.append(resample.GetOutput())
    del resample
    return image_list
 def __init__(self, parent=None):
     super(VtkFgBgDisplayWidget, self).__init__(parent)
     self.imVtkBg = None
     self.imVtkFg = None
     self.matrix4x4 = vtk.vtkMatrix4x4()
     self.matrix4x4.DeepCopy((
         1.0, 0.0, 0.0, 0.0,
         0.0, 1.0, 0.0, 0.0,
         0.0, 0.0, 1.0, 0.0,
         0.0, 0.0, 0.0, 1.0
     ))
     self.reslice = vtk.vtkImageReslice()
     self.reslice.SetOutputDimensionality(3)
     self.reslice.SetResliceAxes(self.matrix4x4)
     self.reslice.SetInterpolationModeToLinear()
     self.setupVtkRendering()
Ejemplo n.º 47
0
def gen_slice(img, pnt=(30, 42, 57), wxyz=(30.0, 0.0, 0.0, 1.0), ext=get_xy_extent()):
    """ generate the slice on xy plane"""

    tf = vtk.vtkTransform()
    tf.RotateWXYZ(wxyz[0], wxyz[1:4])

    rs = vtk.vtkImageReslice()
    rs.SetInputData(img)

    rs.SetResliceTransform(tf)
    rs.SetOutputExtent(ext)
    rs.SetOutputOrigin(pnt)

    rs.SetInterpolationModeToLinear()
    rs.Update()

    return rs
Ejemplo n.º 48
0
def gen_slice(img, s_tf, s_ext=sz2ext(16)):
    """ generate a slice on a plane """
    # debug output
    # print "in gen_slice:"

    # the slice
    rs = vtk.vtkImageReslice()
    rs.SetInputData(img)
    rs.SetInterpolationModeToLinear()

    # debug output
    # print "before:"
    # xxx = rs.GetOutputOrigin()
    # print "OutputOrigin", xxx
    # ooo = rs.GetOutputExtent()
    # print "OutputExtent", ooo
    # zzz = rs.GetResliceAxesDirectionCosines()
    # print "ResliceAxesDirectionCosine", zzz
    # yyy = rs.GetResliceAxesOrigin()
    # print "ResliceAxesOrigin", yyy

    # what the slice: define the output plane
    rs.SetOutputDimensionality(2)  # enforcing a plane
    rs.SetOutputSpacing(img.GetSpacing())
    rs.SetOutputExtent(s_ext)
    rs.SetOutputOrigin((0.0, 0.0, 0.0))

    # where the slice: the transformation
    s_axes = s_tf.GetMatrix()
    rs.SetResliceAxes(s_axes)

    rs.Update()

    # debug output
    # print "After:"
    # xxx = rs.GetOutputOrigin()
    # print "OutputOrigin", xxx
    # ooo = rs.GetOutputExtent()
    # print "OutputExtent", ooo
    # zzz = rs.GetResliceAxesDirectionCosines()
    # print "ResliceAxesDirectionCosine", zzz
    # yyy = rs.GetResliceAxesOrigin()
    # print "ResliceAxesOrigin", yyy

    return rs
Ejemplo n.º 49
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        self._imageReslice = vtk.vtkImageReslice()
        self._imageReslice.SetInterpolationModeToCubic()
        self._imageReslice.SetAutoCropOutput(1)
        
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(
            self,
            {'Module (self)' : self,
             'vtkImageReslice' : self._imageReslice})


        module_utils.setup_vtk_object_progress(self, self._imageReslice,
                                           'Resampling volume')

        self.sync_module_logic_with_config()
Ejemplo n.º 50
0
def getImageReslice(img, ext, p, n, x, asnumpy=False):
    """
    gets slice of an image in the plane defined by p, n and x

    args:
        @a img: vtk image (3 dimensional)
        @a ext: extent of the reslice plane [Xext,Yext]
        @a p ((x,y,z)): origin of the plane
        @a n ((x,y,z)): vector normal to plane
        @a x ((x,y,z)): x-axis in the plane

    returns:
        ret (itk image): image in the slice plane
    """
    reslice = vtk.vtkImageReslice()
    reslice.SetInputData(img)
    reslice.SetInterpolationModeToLinear()

    #Get y axis and make sure it satisfies the left hand rule
    tr = vtk.vtkTransform()
    tr.RotateWXYZ(-90,n)
    y = tr.TransformPoint(x)

    reslice.SetResliceAxesDirectionCosines(
        x[0],x[1],x[2],y[0],y[1],y[2],n[0],n[1],n[2])
    reslice.SetResliceAxesOrigin(p[0],p[1],p[2])

    delta_min = min(img.GetSpacing())
    px = delta_min*ext[0]
    py = delta_min*ext[1]

    reslice.SetOutputSpacing((delta_min,delta_min,delta_min))
    reslice.SetOutputOrigin(-0.5*px,-0.5*py,0.0)
    reslice.SetOutputExtent(0,ext[0],0,ext[1],0,0)

    reslice.Update()
    #print asnumpy
    if asnumpy:
         return VTKSPtoNumpy(reslice.GetOutput())
    else:
        return reslice.GetOutput()
    def __init__(self, dimension=3):
        AnnotateFactory.AnnotateFactory.__init__(self)

        self._Transform = None

        self._Shift = 0.0
        self._Scale = 1.0

        self._Input = None
        self._defaultLabel = 'Gray Scale Value'

        self._Reslice = vtk.vtkImageReslice()
        self._Reslice.SetOutputExtent(0, 0, 0, 0, 0, 0)
        self._Reslice.InterpolateOff()
        # HQ: vtkImageReslice doesn't work well for 2D image when interpolate is on.
        # self._Reslice.SetInterpolationModeToLinear()
        self._Dimension = dimension

        self._Point = None
        self._Intensity = None
        self.measurementUnit = 'mm'
    def TransformImageData(self, imageData, transform, infoData=None):
        """
		The properties of infoData (optional) are used for generating the new dataset.
		The default is to use the properties of the given image data.

		:type imageData: vtkImageData
		:type transform: vtkTransform
		:type infoData: vtkImageData
		"""
        range = imageData.GetScalarRange()
        reslicer = vtkImageReslice()
        reslicer.SetInterpolationModeToCubic()
        if infoData:
            reslicer.SetInformationInput(infoData)
        reslicer.SetBackgroundLevel(range[0])
        reslicer.AutoCropOutputOff()
        reslicer.SetInputData(imageData)
        reslicer.SetResliceTransform(transform.GetInverse())
        reslicer.Update()

        return reslicer.GetOutput()
Ejemplo n.º 53
0
    def render(self):
        """
        Returns vtkImageData for pattern
        """
        # XDash is drawn and then rotated (for the sake of performance)
        rot_square = int(((self.width + self.height) * 2 ** .5) / 2)

        o_width, o_height = self.width, self.height
        self.width, self.height = rot_square, rot_square

        image = super(XDash, self).render()

        slicer = vtk.vtkImageReslice()
        slicer.SetInputData(image)

        raw_bounds = image.GetBounds()
        raw_center = ((raw_bounds[0] + raw_bounds[1]) / 2.,
                      (raw_bounds[2] + raw_bounds[3]) / 2.,
                      (raw_bounds[4] + raw_bounds[5]) / 2.)

        transform = vtk.vtkTransform()
        transform.Translate(*raw_center)
        transform.RotateWXYZ(45., 0, 0, 1)
        transform.Translate(*[-1 * p for p in raw_center])

        slicer.SetResliceTransform(transform)
        slicer.SetInterpolationModeToCubic()
        slicer.SetOutputSpacing(image.GetSpacing())
        slicer.SetOutputExtent(0, o_width, 0, o_height, 0, 0)

        x_origin = (rot_square - o_width) / 2
        y_origin = (rot_square - o_height) / 2

        slicer.SetOutputOrigin(x_origin, y_origin, 0)
        slicer.Update()

        self.width, self.height = o_width, o_height
        return slicer.GetOutput()
Ejemplo n.º 54
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()
    def __init__(self,data_reader,origin,normal,camera_normal):
        self.axial=self.get_matrix(data_reader,origin,normal,camera_normal)
                             
        # Extract a slice in the desired orientation
        self.reslice = vtk.vtkImageReslice()
	
        self.reslice.SetInput(data_reader.get_data_set())
        self.reslice.SetOutputDimensionality(2)
        self.reslice.SetResliceAxes(self.axial)
        self.reslice.SetInterpolationModeToLinear()
        
        # Create a colorscale lookup table
        self.lut=vtk.vtkLookupTable()
        self.lut.SetNumberOfColors(256)

        self.lut.SetTableRange(data_reader.get_scalar_range())
        self.lut.SetRange(data_reader.get_scalar_range())

        self.lut.SetHueRange(0,1)
        self.lut.Build()
        
        # Map the image through the lookup table
        self.color = vtk.vtkImageMapToColors()
        self.color.SetLookupTable(self.lut)
        self.color.SetInputConnection(self.reslice.GetOutputPort())
        
        # Display the image
        self.actor = vtk.vtkImageActor()
        self.actor.SetInput(self.color.GetOutput())
        c="c"
        if origin[0]==c or origin[1]==c or origin[2]==c:
			origin=self.center
        
        origin=(float(origin[0]),float(origin[1]),float(origin[2]))
        self.actor.SetOrigin(origin)
        self.actor.PokeMatrix(self.axial)
Ejemplo n.º 56
0
def magnify_single_imagedata(reader, zSpacing=1.0):
    logging.debug("In data.magnify_imagedata()")
    imagedata = reader.GetOutput()
    imagedata.UpdateInformation()

    spacing = imagedata.GetSpacing()

    xAxis = [1.0, 0.0, 0.0]
    yAxis = [0.0, 1.0, 0.0]
    zAxis = [0.0, 0.0, 1.0]

    logging.debug(":: Spacing [{0}, {1}, {2}]".format(spacing[0], spacing[1], spacing[2]))
    logging.debug(":: ZSpacing Computer: {0}".format(zSpacing))

    magnify = vtk.vtkImageReslice()
    magnify.SetInputConnection(reader.GetOutputPort())
    magnify.SetInformationInput(reader.GetOutput())
    magnify.SetOutputSpacing(spacing[0], spacing[1], zSpacing)
    magnify.SetInterpolationModeToCubic()
    magnify.SetOutputDimensionality(3)
    magnify.SetResliceAxesDirectionCosines(xAxis, yAxis, zAxis)
    magnify.SetResliceAxesOrigin(imagedata.GetOrigin())

    return vtk.vtkImageData.SafeDownCast(magnify.GetOutput())
Ejemplo n.º 57
0
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: No input image.')

        if self.Cast:
            cast = vtk.vtkImageCast()
            cast.SetInputData(self.Image)
            cast.SetOutputScalarTypeToFloat()
            cast.Update()
            self.Image = cast.GetOutput()

        resliceFilter = vtk.vtkImageReslice()
        resliceFilter.SetInputData(self.Image)
        if self.ReferenceImage:
            resliceFilter.SetInformationInput(self.ReferenceImage)
        else:
            if self.OutputSpacing:
                resliceFilter.SetOutputSpacing(self.OutputSpacing)
            if self.OutputOrigin:
                resliceFilter.SetOutputOrigin(self.OutputOrigin)
            if self.OutputExtent:
                resliceFilter.SetOutputExtent(self.OutputExtent)
        if self.Interpolation == 'nearestneighbor':
            resliceFilter.SetInterpolationModeToNearestNeighbor()
        elif self.Interpolation == 'linear':
            resliceFilter.SetInterpolationModeToLinear()
        elif self.Interpolation == 'cubic':
            resliceFilter.SetInterpolationModeToCubic()
        else:
            self.PrintError('Error: unsupported interpolation mode')
        resliceFilter.SetBackgroundLevel(self.BackgroundLevel)

        if self.TransformInputSampling:
            resliceFilter.TransformInputSamplingOn()
        else:
            resliceFilter.TransformInputSamplingOff()
 
        if not self.Matrix4x4:
            if self.MatrixCoefficients != []:
                self.PrintLog('Setting up transform matrix using specified coefficients')
                self.Matrix4x4 = vtk.vtkMatrix4x4()
                self.Matrix4x4.DeepCopy(self.MatrixCoefficients)
            elif self.Translation != [0.0,0.0,0.0] or self.Rotation != [0.0,0.0,0.0] or self.Scaling != [1.0,1.0,1.0]:
                self.PrintLog('Setting up transform matrix using specified translation, rotation and/or scaling')
                transform = vtk.vtkTransform()
                transform.RotateX(self.Rotation[0])
                transform.RotateY(self.Rotation[1])
                transform.RotateZ(self.Rotation[2])                       
                transform.Translate(self.Translation[0], self.Translation[1], self.Translation[2])
                transform.Scale(self.Scaling[0], self.Scaling[1], self.Scaling[2])
                self.Matrix4x4 = vtk.vtkMatrix4x4()
                self.Matrix4x4.DeepCopy(transform.GetMatrix())

        if self.InvertMatrix and self.Matrix4x4:
            self.Matrix4x4.Invert()
       
        if self.Matrix4x4:
            transform = vtk.vtkMatrixToLinearTransform()
            transform.SetInput(self.Matrix4x4)
            resliceFilter.SetResliceTransform(transform)

        resliceFilter.Update()

        self.Image = resliceFilter.GetOutput()