Ejemplo n.º 1
0
    def __set_up_drawing_actor(self):
        lut = vtk.vtkLookupTable()
        lut.SetRange(0, 1000)
        lut.SetValueRange(0.0, 1.0)  # from black to white
        lut.SetSaturationRange(0.0, 0.0)  # no color saturation
        lut.SetRampToLinear()
        lut.Build()

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

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

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

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

        self.mask_actor = vtk.vtkImageActor()
        self.mask_actor.GetMapper().SetInputConnection(color.GetOutputPort())
        self.mask_actor.SetOpacity(0.7)
Ejemplo n.º 2
0
    def __init__(self):
        
        self.interactor = None
        self.image_original = None
        self.image_threshold = None
        self.render = None
    
        self.lut = vtk.vtkLookupTable()
        self.lut_original = vtk.vtkLookupTable()
        self.image_color = vtk.vtkImageMapToColors()
        self.blend = blend = vtk.vtkImageBlend()
        self.map = map = vtk.vtkImageMapper()
        
        self.actor = actor = vtk.vtkImageActor()
        self.actor2 = actor2 = vtk.vtkImageActor()
        self.actor3 = actor3 = vtk.vtkImageActor()
        
        self.image_color_o = vtk.vtkImageMapToColors()
        
        self.operation_type = 0
        self.w = None
   
        self.slice = 0
        self.clicked = 0
        self.orientation = AXIAL

        self.w = (200, 1200)
Ejemplo n.º 3
0
    def __init__(self):

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

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

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

        self.image_color_o = vtk.vtkImageMapToColors()

        self.operation_type = 0
        self.w = None

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

        self.w = (200, 1200)
Ejemplo n.º 4
0
 def vtkInitialData(self, read_path, volum = 'GAUSSIAN'):
    """ Creation des donnees initiales """
    self.path = read_path
    #-----------------------------------------
    # Creation de la donnee volumique
    #-----------------------------------------
    self.vtkReadVolumAll(os.path.join(self.path,'image.raw'))
    self.valSagittal = (self.lig-1)/2
    self.valCoronal = (self.col-1)/2
    self.valTransversal = (self.nb_coupe-1)/2
    self.min_pixel_value = self.NumpyData.min()
    self.max_pixel_value = self.NumpyData.max()
    if self.valSeuil >= self.max_pixel_value :
       self.valSeuil = (self.max_pixel_value - self.min_pixel_value)/2
    self.VOI_pt2 = [self.col,self.lig,self.nb_coupe]
    #-----------------------------------------
    # Start by creatin a black/white lookup table.
    #-----------------------------------------
    self.bwLut = vtk.vtkLookupTable()
    self.bwLut.SetTableRange(self.min_pixel_value, self.max_pixel_value)
    self.bwLut.SetSaturationRange(0, 0)
    self.bwLut.SetHueRange(0, 0)
    self.bwLut.SetValueRange(0, 1)
    self.bwLut.Build()
    #-----------------------------------------
    # Creation de la bounding box
    #-----------------------------------------
    self.vtkBoundingBox()
    #-----------------------------------------
    # Creation de la VOI
    #-----------------------------------------
    self.vtkVOIdata(volum = volum)
    self.vtkBoundingVOI()
    #-----------------------------------------
    # Creation des infos geometriques
    #-----------------------------------------
    self.vtkCreateGeometricInformations()
    #-----------------------------------------
    # Creation de la couleur des coupe
    #-----------------------------------------
    self.sliceColors0 = vtk.vtkImageMapToColors()
    self.sliceColors0.SetInputConnection(self.vtkVolumAll.GetOutputPort())
    self.sliceColors0.SetLookupTable(self.bwLut)
    self.sliceColors1 = vtk.vtkImageMapToColors()
    self.sliceColors1.SetInputConnection(self.vtkVolumAll.GetOutputPort())
    self.sliceColors1.SetLookupTable(self.bwLut)
    self.sliceColors2 = vtk.vtkImageMapToColors()
    self.sliceColors2.SetInputConnection(self.vtkVolumAll.GetOutputPort())
    self.sliceColors2.SetLookupTable(self.bwLut)
    #-----------------------------------------
    # Creation de la camera
    #-----------------------------------------
    self.vtkCreateCamera()
    #-----------------------------------------
    # Fin de creation des elements et affichage
    #-----------------------------------------
    self.vtkRedraw()
    def createItemToolbar(self):
        """
		Method to create a toolbar for the window that allows use to select processed channel
		"""
        # Pass flag force which indicates that we do want an item toolbar
        # although we only have one input channel
        n = GUI.FilterBasedTaskPanel.FilterBasedTaskPanel.createItemToolbar(self, force=1)
        for i, tid in enumerate(self.toolIds):
            self.dataUnit.setOutputChannel(i, 0)
            self.toolMgr.toggleTool(tid, 0)

        ctf = vtk.vtkColorTransferFunction()
        ctf.AddRGBPoint(0, 0, 0, 0)
        ctf.AddRGBPoint(255, 1, 1, 1)
        imagedata = self.itemMips[0]

        ctf = vtk.vtkColorTransferFunction()
        ctf.AddRGBPoint(0, 0, 0, 0)
        ctf.AddRGBPoint(255, 1, 1, 1)
        maptocolor = vtk.vtkImageMapToColors()
        maptocolor.SetInput(imagedata)
        maptocolor.SetLookupTable(ctf)
        maptocolor.SetOutputFormatToRGB()
        maptocolor.Update()
        imagedata = maptocolor.GetOutput()

        bmp = lib.ImageOperations.vtkImageDataToWxImage(imagedata).ConvertToBitmap()
        bmp = self.getChannelItemBitmap(bmp, (255, 255, 255))
        toolid = wx.NewId()
        name = "Manipulation"
        self.toolMgr.addChannelItem(name, bmp, toolid, lambda e, x=n, s=self: s.setPreviewedData(e, x))

        self.toolIds.append(toolid)
        self.dataUnit.setOutputChannel(len(self.toolIds), 1)
        self.toolMgr.toggleTool(toolid, 1)
Ejemplo n.º 6
0
def getMIP(imageData, color):
    """
	A function that will take a volume and do a simple
				 maximum intensity projection that will be converted to a
				 wxBitmap
	"""
    maxval = imageData.GetScalarRange()[1]
    imageData.SetUpdateExtent(imageData.GetWholeExtent())

    if maxval > 255:
        shiftscale = vtk.vtkImageShiftScale()
        shiftscale.SetInputConnection(imageData.GetProducerPort())
        shiftscale.SetScale(255.0 / maxval)
        shiftscale.SetOutputScalarTypeToUnsignedChar()
        imageData = shiftscale.GetOutput()

    mip = vtkbxd.vtkImageSimpleMIP()
    mip.SetInputConnection(imageData.GetProducerPort())

    if color == None:
        output = optimize.execute_limited(mip)
        return output

    if mip.GetOutput().GetNumberOfScalarComponents() == 1:
        ctf = getColorTransferFunction(color)

        maptocolor = vtk.vtkImageMapToColors()
        maptocolor.SetInputConnection(mip.GetOutputPort())
        maptocolor.SetLookupTable(ctf)
        maptocolor.SetOutputFormatToRGB()
        imagedata = optimize.execute_limited(maptocolor)

    else:
        imagedata = output = optimize.execute_limited(mip)
    return imagedata
Ejemplo n.º 7
0
    def __init__(self,
                 world_to_slice,
                 image,
                 display_coordinates="physical",
                 colormap=None,
                 opacity=1.0):

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

        self._actor = vtkImageActor()

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

        self._image_map_to_colors = vtkImageMapToColors()

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

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

        self._image_map_to_colors.SetInputConnection(
            self._change_information.GetOutputPort())
        self._actor.SetInput(self._image_map_to_colors.GetOutput())
        self._actor.InterpolateOff()
Ejemplo n.º 8
0
    def do_colour_mask(self, imagedata):
        scalar_range = int(imagedata.GetScalarRange()[1])
        r, g, b = 0, 1, 0

        # map scalar values into colors
        lut_mask = vtk.vtkLookupTable()
        lut_mask.SetNumberOfColors(255)
        lut_mask.SetHueRange(const.THRESHOLD_HUE_RANGE)
        lut_mask.SetSaturationRange(1, 1)
        lut_mask.SetValueRange(0, 1)
        lut_mask.SetNumberOfTableValues(256)
        lut_mask.SetTableValue(0, 0, 0, 0, 0.0)
        lut_mask.SetTableValue(1, 0, 0, 0, 0.0)
        lut_mask.SetTableValue(2, 0, 0, 0, 0.0)
        lut_mask.SetTableValue(255, r, g, b, 1.0)
        lut_mask.SetRampToLinear()
        lut_mask.Build()
        # self.lut_mask = lut_mask

        # map the input image through a lookup table
        img_colours_mask = vtk.vtkImageMapToColors()
        img_colours_mask.SetLookupTable(lut_mask)
        img_colours_mask.SetOutputFormatToRGBA()
        img_colours_mask.SetInputData(imagedata)
        img_colours_mask.Update()
        # self.img_colours_mask = img_colours_mask

        return img_colours_mask.GetOutput()
Ejemplo n.º 9
0
    def do_colour_mask(self, imagedata):
        scalar_range = int(imagedata.GetScalarRange()[1])
        r, g, b = self.current_mask.colour

        # map scalar values into colors
        lut_mask = vtk.vtkLookupTable()
        lut_mask.SetNumberOfColors(256)
        lut_mask.SetHueRange(const.THRESHOLD_HUE_RANGE)
        lut_mask.SetSaturationRange(1, 1)
        lut_mask.SetValueRange(0, 255)
        lut_mask.SetRange(0, 255)
        lut_mask.SetNumberOfTableValues(256)
        lut_mask.SetTableValue(0, 0, 0, 0, 0.0)
        lut_mask.SetTableValue(1, 0, 0, 0, 0.0)
        lut_mask.SetTableValue(254, r, g, b, 1.0)
        lut_mask.SetTableValue(255, r, g, b, 1.0)
        lut_mask.SetRampToLinear()
        lut_mask.Build()
        # self.lut_mask = lut_mask

        # map the input image through a lookup table
        img_colours_mask = vtk.vtkImageMapToColors()
        img_colours_mask.SetLookupTable(lut_mask)
        img_colours_mask.SetOutputFormatToRGBA()
        img_colours_mask.SetInput(imagedata)
        img_colours_mask.Update()
        # self.img_colours_mask = img_colours_mask

        return img_colours_mask.GetOutput()
Ejemplo n.º 10
0
    def _set_colour(self, imagedata, colour):
        scalar_range = int(imagedata.GetScalarRange()[1])
        r, g, b = colour

        # map scalar values into colors
        lut_mask = vtk.vtkLookupTable()
        lut_mask.SetNumberOfColors(256)
        lut_mask.SetHueRange(const.THRESHOLD_HUE_RANGE)
        lut_mask.SetSaturationRange(1, 1)
        lut_mask.SetValueRange(0, 255)
        lut_mask.SetRange(0, 255)
        lut_mask.SetNumberOfTableValues(256)
        lut_mask.SetTableValue(0, 0, 0, 0, 0.0)
        lut_mask.SetTableValue(1, 1-r, 1-g, 1-b, 0.50)
        lut_mask.SetRampToLinear()
        lut_mask.Build()

        # map the input image through a lookup table
        img_colours_mask = vtk.vtkImageMapToColors()
        img_colours_mask.SetLookupTable(lut_mask)
        img_colours_mask.SetOutputFormatToRGBA()
        img_colours_mask.SetInput(imagedata)
        img_colours_mask.Update()

        return img_colours_mask.GetOutput()
    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.º 12
0
    def _set_colour(self, imagedata, colour):
        scalar_range = int(imagedata.GetScalarRange()[1])
        r, g, b = colour

        # map scalar values into colors
        lut_mask = vtk.vtkLookupTable()
        lut_mask.SetNumberOfColors(256)
        lut_mask.SetHueRange(const.THRESHOLD_HUE_RANGE)
        lut_mask.SetSaturationRange(1, 1)
        lut_mask.SetValueRange(0, 255)
        lut_mask.SetRange(0, 255)
        lut_mask.SetNumberOfTableValues(256)
        lut_mask.SetTableValue(0, 0, 0, 0, 0.0)
        lut_mask.SetTableValue(1, 1 - r, 1 - g, 1 - b, 0.50)
        lut_mask.SetRampToLinear()
        lut_mask.Build()

        # map the input image through a lookup table
        img_colours_mask = vtk.vtkImageMapToColors()
        img_colours_mask.SetLookupTable(lut_mask)
        img_colours_mask.SetOutputFormatToRGBA()
        img_colours_mask.SetInput(imagedata)
        img_colours_mask.Update()

        return img_colours_mask.GetOutput()
Ejemplo n.º 13
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageMapToColors(), 'Processing.',
         ('vtkImageData',), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 14
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.º 15
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.º 16
0
def setup_brain(renderer, file):
    brain = NiiObject()
    brain.file = file
    brain.reader = read_volume(brain.file)
    brain.labels.append(
        NiiLabel(BRAIN_COLORS[0], BRAIN_OPACITY, BRAIN_SMOOTHNESS))
    brain.labels[0].extractor = create_brain_extractor(brain)
    brain.extent = brain.reader.GetDataExtent()

    scalar_range = brain.reader.GetOutput().GetScalarRange()
    bw_lut = vtk.vtkLookupTable()
    bw_lut.SetTableRange(scalar_range)
    bw_lut.SetSaturationRange(0, 0)
    bw_lut.SetHueRange(0, 0)
    bw_lut.SetValueRange(0, 2)
    bw_lut.Build()

    view_colors = vtk.vtkImageMapToColors()
    view_colors.SetInputConnection(brain.reader.GetOutputPort())
    view_colors.SetLookupTable(bw_lut)
    view_colors.Update()
    brain.image_mapper = view_colors
    brain.scalar_range = scalar_range

    add_surface_rendering(brain, 0,
                          sum(scalar_range) /
                          2)  # render index, default extractor value
    renderer.AddActor(brain.labels[0].actor)
    return brain
def getMIP(imageData, color):
    """
	A function that will take a volume and do a simple
				 maximum intensity projection that will be converted to a
				 wxBitmap
	"""
    maxval = imageData.GetScalarRange()[1]
    imageData.SetUpdateExtent(imageData.GetWholeExtent())

    if maxval > 255:
        shiftscale = vtk.vtkImageShiftScale()
        shiftscale.SetInputConnection(imageData.GetProducerPort())
        shiftscale.SetScale(255.0 / maxval)
        shiftscale.SetOutputScalarTypeToUnsignedChar()
        imageData = shiftscale.GetOutput()

    mip = vtkbxd.vtkImageSimpleMIP()
    mip.SetInputConnection(imageData.GetProducerPort())

    if color == None:
        output = optimize.execute_limited(mip)
        return output

    if mip.GetOutput().GetNumberOfScalarComponents() == 1:
        ctf = getColorTransferFunction(color)

        maptocolor = vtk.vtkImageMapToColors()
        maptocolor.SetInputConnection(mip.GetOutputPort())
        maptocolor.SetLookupTable(ctf)
        maptocolor.SetOutputFormatToRGB()
        imagedata = optimize.execute_limited(maptocolor)

    else:
        imagedata = output = optimize.execute_limited(mip)
    return imagedata
Ejemplo n.º 18
0
def writeAllImageSlices(imgfn,pathfn,ext,output_dir):
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(imgfn)
    reader.Update()
    img = reader.GetOutput()

    parsed_path = parsePathFile(pathfn)
    slices = getAllImageSlices(img,parsed_path,ext)

    writer = vtk.vtkJPEGWriter()

    table = vtk.vtkLookupTable()
    scalar_range = img.GetScalarRange()
    table.SetRange(scalar_range[0], scalar_range[1]) # image intensity range
    table.SetValueRange(0.0, 1.0) # from black to white
    table.SetSaturationRange(0.0, 0.0) # no color saturation
    table.SetRampToLinear()
    table.Build()

    # Map the image through the lookup table
    color = vtk.vtkImageMapToColors()
    color.SetLookupTable(table)

    mkdir(output_dir)
    for i in range(len(slices)):
        color.SetInputData(slices[i])
        writer.SetInputConnection(color.GetOutputPort())
        writer.SetFileName(output_dir+'{}.jpg'.format(i))
        writer.Update()
        writer.Write()
Ejemplo n.º 19
0
def setup_brain(render_window, renderer, name):

    file = name + ".nii.gz"
    # print(file)
    brain = NiiObject()
    brain.file = file
    brain.reader = read_volume(brain.file)
    brain.labels.append(
        NiiLabel(BRAIN_COLORS[0], BRAIN_OPACITY, BRAIN_SMOOTHNESS))
    brain.labels[0].extractor = create_brain_extractor(brain)
    brain.extent = brain.reader.GetDataExtent()
    scalar_range = brain.reader.GetOutput().GetScalarRange()
    bw_lut = vtk.vtkLookupTable()
    bw_lut.SetTableRange(scalar_range)
    bw_lut.SetSaturationRange(0, 0)
    bw_lut.SetHueRange(0, 0)
    bw_lut.SetValueRange(0, 2)
    bw_lut.Build()
    # print('step1')
    view_colors = vtk.vtkImageMapToColors()
    view_colors.SetInputConnection(brain.reader.GetOutputPort())
    view_colors.SetLookupTable(bw_lut)
    view_colors.Update()
    brain.image_mapper = view_colors
    brain.scalar_range = scalar_range
    # print('step2')
    add_surface_rendering(brain, 0,
                          sum(scalar_range) /
                          2)  # render index, default extractor value
    renderer.AddActor(brain.labels[0].actor)
    objWriter = vtk.vtkOBJExporter()
    objWriter.SetFilePrefix(name)
    objWriter.SetInput(render_window)
    objWriter.Write()
    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.º 21
0
    def _on_new_image_attrib(self, attrib):
        ((w, h, num_channels), dtype) = attrib
        if self._image_handler.is_depth_image():
            assert num_channels == 1, num_channels
            assert dtype in (np.uint16, np.float32), dtype
            # TODO(eric.cousineau): Delegate to outside of `ImageWidget`?
            # This is depth-image specific.
            # For now, just set arbitrary values.

            depth_range = self._get_depth_range()
            lower_color = (1, 1, 1)  # White
            upper_color = (0, 0, 0)  # Black
            nan_color = (0.5, 0.5, 1)  # Light blue - No return.
            inf_color = (0.5, 0, 0.)  # Dark red - Too far / too close.

            # Use `vtkColorTransferFunction` as it provides a more intuitive
            # interpolating interface for me (Eric) than `vtkLookupTable`,
            # since it permits direct specification of RGB values.
            coloring = vtk.vtkColorTransferFunction()
            coloring.AddRGBPoint(depth_range[0], *lower_color)
            coloring.AddRGBPoint(depth_range[1], *upper_color)
            coloring.SetNanColor(*nan_color)
            # @note `coloring.SetAboveRangeColor` doesn't seem to work?
            coloring.AddRGBPoint(depth_range[1] + 10000, *inf_color)
            coloring.SetClamping(True)
            coloring.SetScaleToLinear()

            self._depth_mapper = vtk.vtkImageMapToColors()
            self._depth_mapper.SetLookupTable(coloring)
            vtk_SetInputData(self._depth_mapper, self._image)
            vtk_SetInputData(self._image_actor, self._depth_mapper.GetOutput())
            self._image_actor.GetMapper().SetInputConnection(
                self._depth_mapper.GetOutputPort())
        else:
            # Direct connection.
            self._depth_mapper = None
            vtk_SetInputData(self._image_actor, self._image)

        # Must render first.
        self._view.render()

        # Fit image to view.
        # TODO(eric.cousineau): No idea why this is needed; it worked for
        # VTK 5, but no longer for VTK 6+?
        camera = self._view.camera()
        camera.ParallelProjectionOn()
        camera.SetFocalPoint(0, 0, 0)
        camera.SetPosition(0, 0, -1)
        camera.SetViewUp(0, -1, 0)
        self._view.resetCamera()

        image_height, image_width = get_vtk_image_shape(self._image)[:2]
        view_width, view_height = self._view.renderWindow().GetSize()

        aspect_ratio = float(view_width) / view_height
        parallel_scale = max(image_width / aspect_ratio, image_height) / 2.0
        camera.SetParallelScale(parallel_scale)
Ejemplo n.º 22
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkImageMapToColors(),
                                       'Processing.', ('vtkImageData', ),
                                       ('vtkImageData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Ejemplo n.º 23
0
    def _on_new_image_attrib(self, attrib):
        ((w, h, num_channels), dtype) = attrib
        if self._image_handler.is_depth_image():
            assert num_channels == 1, num_channels
            assert dtype in (np.uint16, np.float32), dtype
            # TODO(eric.cousineau): Delegate to outside of `ImageWidget`?
            # This is depth-image specific.
            # For now, just set arbitrary values.

            depth_range = self._get_depth_range()
            lower_color = (1, 1, 1)  # White
            upper_color = (0, 0, 0)  # Black
            nan_color = (0.5, 0.5, 1)  # Light blue - No return.
            inf_color = (0.5, 0, 0.)  # Dark red - Too far / too close.

            # Use `vtkColorTransferFunction` as it provides a more intuitive
            # interpolating interface for me (Eric) than `vtkLookupTable`,
            # since it permits direct specification of RGB values.
            coloring = vtk.vtkColorTransferFunction()
            coloring.AddRGBPoint(depth_range[0], *lower_color)
            coloring.AddRGBPoint(depth_range[1], *upper_color)
            coloring.SetNanColor(*nan_color)
            # @note `coloring.SetAboveRangeColor` doesn't seem to work?
            coloring.AddRGBPoint(depth_range[1] + 10000, *inf_color)
            coloring.SetClamping(True)
            coloring.SetScaleToLinear()

            self._depth_mapper = vtk.vtkImageMapToColors()
            self._depth_mapper.SetLookupTable(coloring)
            vtk_SetInputData(self._depth_mapper, self._image)
            vtk_SetInputData(self._image_actor, self._depth_mapper.GetOutput())
            self._image_actor.GetMapper().SetInputConnection(
                self._depth_mapper.GetOutputPort())
        else:
            # Direct connection.
            self._depth_mapper = None
            vtk_SetInputData(self._image_actor, self._image)

        # Must render first.
        self._view.render()

        # Fit image to view.
        # TODO(eric.cousineau): No idea why this is needed; it worked for
        # VTK 5, but no longer for VTK 6+?
        camera = self._view.camera()
        camera.ParallelProjectionOn()
        camera.SetFocalPoint(0, 0, 0)
        camera.SetPosition(0, 0, -1)
        camera.SetViewUp(0, -1, 0)
        self._view.resetCamera()

        image_height, image_width = get_vtk_image_shape(self._image)[:2]
        view_width, view_height = self._view.renderWindow().GetSize()

        aspect_ratio = float(view_width) / view_height
        parallel_scale = max(image_width / aspect_ratio, image_height) / 2.0
        camera.SetParallelScale(parallel_scale)
Ejemplo n.º 24
0
def vtkImageDataToPreviewBitmap(dataunit,
                                timepoint,
                                color,
                                width=0,
                                height=0,
                                getvtkImage=0):
    """
	A function that will take a volume and do a simple
				 Maximum Intensity Projection that will be converted to a
				 wxBitmap
	"""
    imagedata = dataunit.getMIP(timepoint, None, small=1, noColor=1)
    vtkImg = imagedata

    if not color:
        color = dataunit.getColorTransferFunction()

    ctf = getColorTransferFunction(color)
    minval, maxval = ctf.GetRange()
    imax = imagedata.GetScalarRange()[1]
    if maxval > imax:
        step = float((maxval - minval) / imax)
        ctf2 = vtk.vtkColorTransferFunction()
        Logging.info("Creating CTF in range %d, %d with steps %d" %
                     (int(minval), int(maxval), int(step)))
        for i in range(int(minval), int(maxval), int(step)):
            red, green, blue = ctf.GetColor(i)
            ctf2.AddRGBPoint(i / step, red, green, blue)
        ctf = ctf2
    maptocolor = vtk.vtkImageMapToColors()
    maptocolor.SetInputConnection(imagedata.GetProducerPort())
    maptocolor.SetLookupTable(ctf)
    maptocolor.SetOutputFormatToRGB()
    maptocolor.Update()
    imagedata = maptocolor.GetOutput()

    image = vtkImageDataToWxImage(imagedata)
    xSize, ySize = image.GetWidth(), image.GetHeight()
    if not width and height:
        aspect = float(xSize) / ySize
        width = aspect * height
    if not height and width:
        aspect = float(ySize) / xSize
        height = aspect * width
    if not width and not height:
        width = height = 64
    image.Rescale(width, height)

    bitmap = image.ConvertToBitmap()
    ret = [bitmap]
    if getvtkImage:
        ret.append(vtkImg)
        return ret
    return bitmap
Ejemplo n.º 25
0
    def updateRendering(self):
        """
		Update the Rendering of this module
		"""
        data = self.getInput(1)
        x, y, z = self.dataUnit.getDimensions()
        data = optimize.optimize(image=data,
                                 updateExtent=(0, x - 1, 0, y - 1, 0, z - 1))
        if data.GetNumberOfScalarComponents() > 3:
            extract = vtk.vtkImageExtractComponents()
            extract.SetInput(data)
            extract.SetComponents(1, 1, 1)
            data = extract.GetOutput()
        if data.GetNumberOfScalarComponents() > 1:
            self.luminance.SetInput(data)
            data = self.luminance.GetOutput()

        z = self.parameters["Slice"]
        ext = (0, x - 1, 0, y - 1, z, z)

        voi = vtk.vtkExtractVOI()
        voi.SetVOI(ext)
        voi.SetInput(data)
        slice = voi.GetOutput()
        self.geometry.SetInput(slice)

        self.warp.SetInput(self.geometry.GetOutput())
        self.warp.SetScaleFactor(self.parameters["Scale"])
        self.merge.SetGeometry(self.warp.GetOutput())

        if slice.GetNumberOfScalarComponents() == 1:
            maptocol = vtk.vtkImageMapToColors()
            ctf = self.getInputDataUnit(1).getColorTransferFunction()
            maptocol.SetInput(slice)
            maptocol.SetLookupTable(ctf)
            maptocol.Update()
            scalars = maptocol.GetOutput()
        else:
            scalars = slice

        self.merge.SetScalars(scalars)
        data = self.merge.GetOutput()

        if self.parameters["Normals"]:
            self.normals.SetInput(data)
            self.normals.SetFeatureAngle(self.parameters["FeatureAngle"])
            print "Feature angle=", self.parameters["FeatureAngle"]
            data = self.normals.GetOutput()

        self.mapper.SetInput(data)
        self.mapper.Update()
        VisualizationModule.updateRendering(self)
        self.parent.Render()
Ejemplo n.º 26
0
    def __init__(self):
        super(camphorVOIs, self).__init__()

        # data objects
        self.data = []  # reference to the data array

        # Other objects
        self.image = [vtk.vtkImageMapToColors()]

        # Output objects
        self.output = self.image[0]
        self.sliceOutput = self.slice[0]
Ejemplo n.º 27
0
    def setImage(self, dicomfile):
        logging.debug("In VTKImageView::setImage()")
        if dicomfile:
            if os.path.exists(dicomfile):
                self.reader = vtkgdcm.vtkGDCMImageReader()
                self.reader.SetFileName(dicomfile)
                self.reader.Update()

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

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

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

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

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

                self.render.RemoveActor(self.actor)
                self.actor = vtk.vtkImageActor()
                self.actor.SetInput(self.cast.GetOutput())
                self.render.AddActor(self.actor)
                self.render.ResetCamera()
                self.Render()
            else:
                self.render.RemoveActor(self.actor)
                self.Render()
        else:
            self.render.RemoveActor(self.actor)
            self.Render()
	def updateRendering(self):
		"""
		Update the Rendering of this module
		"""
		data = self.getInput(1)
		x,y,z = self.dataUnit.getDimensions()
		data = optimize.optimize(image = data, updateExtent = (0, x-1, 0, y-1, 0, z-1))
		if data.GetNumberOfScalarComponents() > 3:
			extract = vtk.vtkImageExtractComponents()
			extract.SetInput(data)
			extract.SetComponents(1, 1, 1)
			data = extract.GetOutput()
		if data.GetNumberOfScalarComponents() > 1:
			self.luminance.SetInput(data)
			data = self.luminance.GetOutput()
		
		z = self.parameters["Slice"]
		ext = (0, x - 1, 0, y - 1, z, z)

		voi = vtk.vtkExtractVOI()
		voi.SetVOI(ext)
		voi.SetInput(data)
		slice = voi.GetOutput()
		self.geometry.SetInput(slice)         
		
		self.warp.SetInput(self.geometry.GetOutput())
		self.warp.SetScaleFactor(self.parameters["Scale"])		
		self.merge.SetGeometry(self.warp.GetOutput())
		
		if slice.GetNumberOfScalarComponents() == 1:
			maptocol = vtk.vtkImageMapToColors()
			ctf = self.getInputDataUnit(1).getColorTransferFunction()
			maptocol.SetInput(slice)
			maptocol.SetLookupTable(ctf)
			maptocol.Update()
			scalars = maptocol.GetOutput()
		else:
			scalars = slice
			
		self.merge.SetScalars(scalars)
		data = self.merge.GetOutput()
		
		if self.parameters["Normals"]:
			self.normals.SetInput(data)
			self.normals.SetFeatureAngle(self.parameters["FeatureAngle"])
			print "Feature angle=", self.parameters["FeatureAngle"]            
			data = self.normals.GetOutput()
		
		self.mapper.SetInput(data)
		self.mapper.Update()
		VisualizationModule.updateRendering(self)
		self.parent.Render()
Ejemplo n.º 29
0
def CreateImageActor(actor, colorWindow, colorLevel):
    wlut = vtk.vtkWindowLevelLookupTable()
    wlut.SetWindow(colorWindow)
    wlut.SetLevel(colorLevel)
    wlut.Build()

    # Map the image through the lookup table.
    color = vtk.vtkImageMapToColors()
    color.SetLookupTable(wlut)
    color.SetInputData(actor.GetMapper().GetInput())

    actor.GetMapper().SetInputConnection(color.GetOutputPort())
    return
Ejemplo n.º 30
0
def dumpImage(filename):
    toImage = vtk.vtkWindowToImageFilter()
    toImage.SetInput(renWin)
    toImage.Modified()
    writer = vtk.vtkPNGWriter()
    writer.SetInput(toImage.GetOutput())
    writer.SetFileName(filename)
    writer.Modified()
    print "writing to ", filename
    writer.Write()

    Fractal0 = vtk.vtkImageMandelbrotSource()
    Fractal0.SetWholeExtent(0, 247, 0, 247, 0, 0)
    Fractal0.SetProjectionAxes(0, 1, 2)
    Fractal0.SetOriginCX(-1.75, -1.25, 0, 0)
    Fractal0.SetSizeCX(2.5, 2.5, 2, 1.5)
    Fractal0.SetMaximumNumberOfIterations(1000)

    cast = vtk.vtkImageCast()
    cast.SetInputConnection(Fractal0.GetOutputPort())
    cast.SetOutputScalarTypeToUnsignedChar()

    table = vtk.vtkLookupTable()
    table.SetTableRange(0, 100)
    table.SetNumberOfColors(100)
    table.Build()
    table.SetTableValue(99, 0, 0, 0, 0)

    colorize = vtk.vtkImageMapToColors()
    colorize.SetOutputFormatToRGB()
    colorize.SetLookupTable(table)
    colorize.SetInputConnection(cast.GetOutputPort())

    mpeg = vtk.vtkMPEG2Writer()
    #mpeg.SetInputConnection(toImage.GetOutputPort())
    #mpeg.SetFileName("TestMovie.mpg")
    #print "writing File TestMovie.mpg "
    #mpeg.Start()

    itr = 1
    for itr in range(1, 10):
        Fractal0.SetMaximumNumberOfIterations(itr)
        table.SetTableRange(0, itr)
        table.SetNumberOfColors(itr)
        table.ForceBuild()
        table.SetTableValue(itr - 1, 0, 0, 0, 0)
        mpeg.Write()
        itr += 1
    err = 0
    exists = 0
Ejemplo n.º 31
0
def vtkRemapImageColor(img, ranges=[0,2000],mapRange=[0,1.0],satRange=[0.0,0.0]):
    table = vtk.vtkLookupTable()
    table.SetRange(ranges) # image intensity range
    table.SetValueRange(mapRange) # from black to white
    table.SetSaturationRange(satRange) # no color saturation
    table.SetRampToLinear()
    table.Build()

    # Map the image through the lookup table
    color = vtk.vtkImageMapToColors()
    color.SetLookupTable(table)
    color.SetInputData(img)
    color.Update()
    return color.GetOutput()
def vtkImageDataToPreviewBitmap(dataunit, timepoint, color, width=0, height=0, getvtkImage=0):
    """
	A function that will take a volume and do a simple
				 Maximum Intensity Projection that will be converted to a
				 wxBitmap
	"""
    imagedata = dataunit.getMIP(timepoint, None, small=1, noColor=1)
    vtkImg = imagedata

    if not color:
        color = dataunit.getColorTransferFunction()

    ctf = getColorTransferFunction(color)
    minval, maxval = ctf.GetRange()
    imax = imagedata.GetScalarRange()[1]
    if maxval > imax:
        step = float((maxval - minval) / imax)
        ctf2 = vtk.vtkColorTransferFunction()
        Logging.info("Creating CTF in range %d, %d with steps %d" % (int(minval), int(maxval), int(step)))
        for i in range(int(minval), int(maxval), int(step)):
            red, green, blue = ctf.GetColor(i)
            ctf2.AddRGBPoint(i / step, red, green, blue)
        ctf = ctf2
    maptocolor = vtk.vtkImageMapToColors()
    maptocolor.SetInputConnection(imagedata.GetProducerPort())
    maptocolor.SetLookupTable(ctf)
    maptocolor.SetOutputFormatToRGB()
    maptocolor.Update()
    imagedata = maptocolor.GetOutput()

    image = vtkImageDataToWxImage(imagedata)
    xSize, ySize = image.GetWidth(), image.GetHeight()
    if not width and height:
        aspect = float(xSize) / ySize
        width = aspect * height
    if not height and width:
        aspect = float(ySize) / xSize
        height = aspect * width
    if not width and not height:
        width = height = 64
    image.Rescale(width, height)

    bitmap = image.ConvertToBitmap()
    ret = [bitmap]
    if getvtkImage:
        ret.append(vtkImg)
        return ret
    return bitmap
Ejemplo n.º 33
0
def set_image_color(vtkimagedata,max_value,color):
    lut = vtk.vtkLookupTable()
    lut.SetTableRange(0, max_value)
    for k in range(max_value):
        val = k/(max_value-1)
        lut.SetTableValue(k,val*color[0],val*color[1],val*color[2],val*color[3])
    lut.Build()
    
    colormapper = vtk.vtkImageMapToColors()
    colormapper.SetLookupTable(lut)
    colormapper.SetInputData(vtkimagedata)
    
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(colormapper.GetOutputPort())
    
    return actor
Ejemplo n.º 34
0
def main():
    filename = get_program_parameters()
    colors = vtk.vtkNamedColors()

    # Read the file
    reader = vtk.vtkDEMReader()
    reader.SetFileName(filename)
    reader.Update()

    lut = vtk.vtkLookupTable()
    lut.SetHueRange(0.6, 0)
    lut.SetSaturationRange(1.0, 0)
    lut.SetValueRange(0.5, 1.0)
    lut.SetTableRange(reader.GetOutput().GetScalarRange())

    # Visualize
    map_colors = vtk.vtkImageMapToColors()
    map_colors.SetLookupTable(lut)
    map_colors.SetInputConnection(reader.GetOutputPort())

    # Create an actor
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(map_colors.GetOutputPort())

    # Setup renderer
    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.ResetCamera()
    renderer.SetBackground(colors.GetColor3d("Azure"))

    # Setup render window
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    # Setup render window interactor
    render_window_interactor = vtk.vtkRenderWindowInteractor()

    style = vtk.vtkInteractorStyleImage()

    render_window_interactor.SetInteractorStyle(style)

    # Render and start interaction
    render_window_interactor.SetRenderWindow(render_window)
    render_window.Render()
    render_window_interactor.Initialize()

    render_window_interactor.Start()
Ejemplo n.º 35
0
    def do_colour_image(self, imagedata):
        # map scalar values into colors
        lut_bg = vtk.vtkLookupTable()
        lut_bg.SetTableRange(imagedata.GetScalarRange())
        lut_bg.SetSaturationRange(self.saturation_range)
        lut_bg.SetHueRange(self.hue_range)
        lut_bg.SetValueRange(self.value_range)
        lut_bg.Build()

        # map the input image through a lookup table
        img_colours_bg = vtk.vtkImageMapToColors()
        img_colours_bg.SetOutputFormatToRGB()
        img_colours_bg.SetLookupTable(lut_bg)
        img_colours_bg.SetInput(imagedata)
        img_colours_bg.Update()

        return img_colours_bg.GetOutput()
Ejemplo n.º 36
0
    def formatImageData(self, data):
        if data.GetNumberOfScalarComponents() == 1:
            imageToRgb = vtk.vtkImageMapToColors()
            imageToRgb.SetOutputFormatToRGB()
            imageToRgb.SetLookupTable(vtk.vtkScalarsToColors())
            imageToRgb.SetInputData(data)
            imageToRgb.Update()
            data = imageToRgb.GetOutput()

        if data.GetScalarType() != vtk.VTK_UNSIGNED_CHAR:
            shift = vtk.vtkImageShiftScale()
            shift.SetOutputScalarTypeToUnsignedChar()
            shift.SetInputData(data)
            shift.Update()
            data = shift.GetOutput()

        self.image_data.DeepCopy(data)
Ejemplo n.º 37
0
    def set_lookup_table_min_max(self, min, max):
        #pylint:disable=redefined-builtin
        """ Set the minimum/maximum values for the VTK lookup table i.e.
            change displayed range of intensity values. """

        self.lut = vtk.vtkLookupTable()
        self.lut.SetTableRange(min, max)
        self.lut.SetHueRange(0, 0)
        self.lut.SetSaturationRange(0, 0)
        self.lut.SetValueRange(0, 1)
        self.lut.Build()

        self.colours = vtk.vtkImageMapToColors()
        self.colours.SetInputConnection(self.reader.GetOutputPort())
        self.colours.SetLookupTable(self.lut)
        self.colours.Update()

        self.actor.GetMapper().SetInputConnection(self.colours.GetOutputPort())
Ejemplo n.º 38
0
    def showSlice(self, vtkImageData, preserveState):
        '''Shows slice of image.'''
        self.producer.SetOutput(vtkImageData)
        self.reslice.SetInputConnection(self.producer.GetOutputPort())
        self.reslice.SetResliceAxesDirectionCosines((1,0,0), (0,1,0), (0,0,1))
        self.reslice.SetOutputDimensionality(2)
        self.reslice.SetInterpolationModeToLinear()

        flip = vtk.vtkImageFlip()
        # flip over y axis
        flip.SetFilteredAxis(1)
        flip.SetInputConnection(self.reslice.GetOutputPort())

        # create lookup table for intensity -> color
        table = vtk.vtkLookupTable()
        table.SetRange(vtkImageData.GetScalarRange())
        table.SetValueRange(0, 1)
        # no saturation
        table.SetSaturationRange(0, 0)
        table.SetRampToLinear()
        table.Build()

        # map lookup table to colors
        colors = vtk.vtkImageMapToColors()
        colors.SetLookupTable(table)
        colors.SetInputConnection(flip.GetOutputPort())

        # preserve image property
        imageProperty = None
        if preserveState and self.sliceActor:
            imageProperty = self.sliceActor.GetProperty()

        self.sliceActor = vtk.vtkImageActor()
        self.sliceActor.GetMapper().SetInputConnection(colors.GetOutputPort())

        # restore image property
        if preserveState and imageProperty:
            self.sliceActor.SetProperty(imageProperty)

        self.sliceRenderer.RemoveAllViewProps()
        self.sliceRenderer.AddActor(self.sliceActor)

        self.sliceRenderer.ResetCamera()
Ejemplo n.º 39
0
    def __create_background(self, imagedata):
        thresh_min, thresh_max = imagedata.GetScalarRange()
        Publisher.sendMessage("Update threshold limits list", (thresh_min, thresh_max))

        # map scalar values into colors
        lut_bg = self.lut_bg = vtk.vtkLookupTable()
        lut_bg.SetTableRange(thresh_min, thresh_max)
        lut_bg.SetSaturationRange(0, 0)
        lut_bg.SetHueRange(0, 0)
        lut_bg.SetValueRange(0, 1)
        lut_bg.Build()

        # map the input image through a lookup table
        img_colours_bg = self.img_colours_bg = vtk.vtkImageMapToColors()
        img_colours_bg.SetOutputFormatToRGBA()
        img_colours_bg.SetLookupTable(lut_bg)
        img_colours_bg.SetInput(imagedata)

        return img_colours_bg.GetOutput()
Ejemplo n.º 40
0
    def __build_mask(self, imagedata, create=True):
        # create new mask instance and insert it into project
        if create:
            self.CreateMask(imagedata=imagedata)
        current_mask = self.current_mask

        # properties to be inserted into pipeline
        scalar_range = int(imagedata.GetScalarRange()[1])
        r, g, b = current_mask.colour

        # map scalar values into colors
        lut_mask = vtk.vtkLookupTable()
        lut_mask.SetNumberOfTableValues(1)
        lut_mask.SetNumberOfColors(1)
        lut_mask.SetHueRange(const.THRESHOLD_HUE_RANGE)
        lut_mask.SetSaturationRange(1, 1)
        lut_mask.SetValueRange(1, 1)
        lut_mask.SetNumberOfTableValues(scalar_range)
        lut_mask.SetTableValue(1, r, g, b, 1.0)
        lut_mask.SetTableValue(scalar_range - 1, r, g, b, 1.0)
        lut_mask.SetRampToLinear()
        lut_mask.Build()
        self.lut_mask = lut_mask

        mask_thresh_imagedata = self.__create_mask_threshold(imagedata)

        if create:
            # threshold pipeline
            current_mask.imagedata.DeepCopy(mask_thresh_imagedata)
        else:
            mask_thresh_imagedata = self.current_mask.imagedata

        # map the input image through a lookup table
        img_colours_mask = vtk.vtkImageMapToColors()
        img_colours_mask.SetOutputFormatToRGBA()
        img_colours_mask.SetLookupTable(lut_mask)

        img_colours_mask.SetInput(mask_thresh_imagedata)

        self.img_colours_mask = img_colours_mask

        return img_colours_mask.GetOutput()
Ejemplo n.º 41
0
def render(im, dim):

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

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

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

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

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

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

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

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

    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 42
0
    def __create_background(self, imagedata):

        thresh_min, thresh_max = imagedata.GetScalarRange()

        # map scalar values into colors
        lut_bg = vtk.vtkLookupTable()
        lut_bg.SetTableRange(thresh_min, thresh_max)
        lut_bg.SetSaturationRange(0, 0)
        lut_bg.SetHueRange(0, 0)
        lut_bg.SetValueRange(0, 1)
        lut_bg.Build()

        # map the input image through a lookup table
        img_colours_bg = vtk.vtkImageMapToColors()
        img_colours_bg.SetOutputFormatToRGBA()
        img_colours_bg.SetLookupTable(lut_bg)
        img_colours_bg.SetInputData(imagedata)
        img_colours_bg.Update()

        return img_colours_bg.GetOutput()
Ejemplo n.º 43
0
 def _getRGBVolume(self):
     """
     Calculates the RBG volume from the indexed volume. Note that the input
     volume has to be 1 channel, 16bpp indexed volume.
     
     @rtype: C{vtkImageData}
     @return: RGB colored, 24bpp volume
     
     """
     # input volume has to 
     srcRead = self._inputVolume
     
     # Create and configure proper vtk fiter:
     map = vtk.vtkImageMapToColors()
     map.SetInput(srcRead)
     map.SetOutputFormatToRGB()
     map.SetLookupTable(self._makeLut())
     map.Update()
     
     # and return the result
     return map.GetOutput()
Ejemplo n.º 44
0
    def display_axis_slice(self, axis, index):
        slice_colors = vtk.vtkImageMapToColors()
        slice_colors.SetInputData(self.volume)
        slice_colors.SetLookupTable(self.greyscale_lut)
        #slice_colors.SetLookupTable(self.hue_lut)
        #slice_colors.SetLookupTable(self.sat_lut)
        slice_colors.Update()

        slice = vtk.vtkImageActor()
        slice.GetMapper().SetInputData(slice_colors.GetOutput())

        if axis == 'i':
            imin = index
            imax = index
            jmin = 0
            jmax = self.height
            kmin = 0
            kmax = self.depth

        elif axis == 'j':
            imin = 0
            imax = self.width
            jmin = index
            jmax = index
            kmin = 0
            kmax = self.depth

        elif axis == 'k':
            imin = 0
            imax = self.width
            jmin = 0
            jmax = self.height
            kmin = index
            kmax = index

        slice.SetDisplayExtent(imin, imax, jmin, jmax, kmin, kmax)
        slice.ForceOpaqueOn()
        slice.PickableOff()
        self.graphics.add_actor(slice)
Ejemplo n.º 45
0
	def createItemToolbar(self):
		"""
		Method to create a toolbar for the window that allows use to select processed channel
		"""		 
		n = TaskPanel.createItemToolbar(self)		 
		
		coloc = vtkbxd.vtkImageColocalizationFilter()
		coloc.SetOutputDepth(8)
		i = 0
		for data in self.itemMips:
			coloc.AddInput(data)
			coloc.SetColocalizationLowerThreshold(i, 100)
			coloc.SetColocalizationUpperThreshold(i, 255)
			i = i + 1
		coloc.Update()
		ctf = vtk.vtkColorTransferFunction()
		ctf.AddRGBPoint(0, 0, 0, 0)
		ctf.AddRGBPoint(255, 1, 1, 1)
		maptocolor = vtk.vtkImageMapToColors()
		maptocolor.SetInput(coloc.GetOutput())
		maptocolor.SetLookupTable(ctf)
		maptocolor.SetOutputFormatToRGB()
		maptocolor.Update()
		imagedata = maptocolor.GetOutput()
		bmp = ImageOperations.vtkImageDataToWxImage(imagedata).ConvertToBitmap()
		
		bmp = self.getChannelItemBitmap(bmp, (255, 255, 0))
		toolid = wx.NewId()
		name = "Colocalization"
		self.toolMgr.addChannelItem(name, bmp, toolid, lambda e, x = n, s = self:s.setPreviewedData(e, x))		  
		
		for i, tid in enumerate(self.toolIds):
			self.dataUnit.setOutputChannel(i, 0)
			self.toolMgr.toggleTool(tid, 0)
		
		self.dataUnit.setOutputChannel(len(self.toolIds), 1)
		self.toolIds.append(toolid)
		self.toolMgr.toggleTool(toolid, 1)
		self.restoreFromCache()
Ejemplo n.º 46
0
    def __init__( self, color, plane, reslice, range ):
        
        self._color = color
    
        self._source = plane
                
        self._mapper = vtk.vtkPolyDataMapper()
        self._mapper.SetInput( self._source.GetOutput() )
        self.SetMapper( self._mapper )

        self._lut = vtk.vtkWindowLevelLookupTable()
        self._lut.SetNumberOfColors( 256 )
        self._lut.SetTableRange( range[0], range[1] )
        self._lut.SetHueRange( 0.0, 0.0 )
        self._lut.SetSaturationRange( 0.0, 0.0 )
        self._lut.SetValueRange( 0.0, 1.0 )
        self._lut.SetAlphaRange( 0.0, 1.0 )
        self._lut.Build()

        self._colormap = vtk.vtkImageMapToColors()
        self._colormap.SetInputConnection( reslice.GetOutputPort() )
        self._colormap.SetLookupTable( self._lut )
        self._colormap.SetOutputFormatToRGBA()
        self._colormap.PassAlphaToOutputOn()

        self._texture = vtk.vtkTexture()
        self._texture.SetInterpolate( True )
        self._texture.SetQualityTo32Bit()
        self._texture.MapColorScalarsThroughLookupTableOff()
        self._texture.RepeatOff()
        self._texture.SetInput( self._colormap.GetOutput() )
        self._texture.SetLookupTable( self._lut )
        self.SetTexture( self._texture )

        self._property = vtk.vtkProperty()
        self._property.SetOpacity( 0.9 )
        self._property.EdgeVisibilityOn()
        self._property.SetEdgeColor( self._color[0], self._color[1], self._color[2] )
        self.SetProperty( self._property )
Ejemplo n.º 47
0
    def createItemToolbar(self):
        """
		Method to create a toolbar for the window that allows use to select processed channel
		"""
        # Pass flag force which indicates that we do want an item toolbar
        # although we only have one input channel
        n = GUI.FilterBasedTaskPanel.FilterBasedTaskPanel.createItemToolbar(
            self, force=1)
        for i, tid in enumerate(self.toolIds):
            self.dataUnit.setOutputChannel(i, 0)
            self.toolMgr.toggleTool(tid, 0)

        ctf = vtk.vtkColorTransferFunction()
        ctf.AddRGBPoint(0, 0, 0, 0)
        ctf.AddRGBPoint(255, 1, 1, 1)
        imagedata = self.itemMips[0]

        ctf = vtk.vtkColorTransferFunction()
        ctf.AddRGBPoint(0, 0, 0, 0)
        ctf.AddRGBPoint(255, 1, 1, 1)
        maptocolor = vtk.vtkImageMapToColors()
        maptocolor.SetInput(imagedata)
        maptocolor.SetLookupTable(ctf)
        maptocolor.SetOutputFormatToRGB()
        maptocolor.Update()
        imagedata = maptocolor.GetOutput()

        bmp = lib.ImageOperations.vtkImageDataToWxImage(
            imagedata).ConvertToBitmap()
        bmp = self.getChannelItemBitmap(bmp, (255, 255, 255))
        toolid = wx.NewId()
        name = "Manipulation"
        self.toolMgr.addChannelItem(
            name, bmp, toolid, lambda e, x=n, s=self: s.setPreviewedData(e, x))

        self.toolIds.append(toolid)
        self.dataUnit.setOutputChannel(len(self.toolIds), 1)
        self.toolMgr.toggleTool(toolid, 1)
def imageDataTo3Component(image, ctf):
    """
	Processes image data to get it to proper 3 component RGB data
	"""
    image.UpdateInformation()
    ncomps = image.GetNumberOfScalarComponents()

    if ncomps == 1:
        maptocolor = vtk.vtkImageMapToColors()
        maptocolor.SetInputConnection(image.GetProducerPort())
        maptocolor.SetLookupTable(ctf)
        maptocolor.SetOutputFormatToRGB()
        imagedata = maptocolor.GetOutput()
    elif ncomps > 3:
        Logging.info("Data has %d components, extracting" % ncomps, kw="imageop")
        extract = vtk.vtkImageExtractComponents()
        extract.SetComponents(0, 1, 2)
        extract.SetInputConnection(image.GetProducerPort())
        imagedata = extract.GetOutput()

    else:
        imagedata = image
    return imagedata
	def processOutputData(self, data):
		"""
		Process the data before it's send to the preview
		"""
		data.UpdateInformation()
		ncomps = data.GetNumberOfScalarComponents()
		if ncomps > 3:
			extract = vtk.vtkImageExtractComponents()
			extract.SetComponents(0, 1, 2)
			extract.SetInput(data)
			data = extract.GetOutput()

		if ncomps == 1:
			Logging.info("Mapping trough ctf", kw = "preview")
			self.mapToColors = vtk.vtkImageMapToColors()
			self.mapToColors.SetInput(data)
			self.updateColor()
			colorImage = self.mapToColors.GetOutput()

			outdata  = colorImage
			return outdata

		return data
    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)
# that image into a different orientation for viewing.  It uses
# vtkImageReslice for reformatting the image, and uses vtkImageActor
# and vtkInteractorStyleImage to display the image.  This InteractorStyle
# forces the camera to stay perpendicular to the XY plane.

import vtk

# these globals are needed for this to work. perhaps create a class
# later.  the below code was modified from a vtk example, to create a
# function to call for rendering.
reslice = vtk.vtkImageReslice()
window = vtk.vtkRenderWindow()
interactorStyle = vtk.vtkInteractorStyleImage()
interactor = vtk.vtkRenderWindowInteractor()
table = vtk.vtkLookupTable()
color = vtk.vtkImageMapToColors()
actor = vtk.vtkImageActor()
renderer = vtk.vtkRenderer()
actions = {}
    
def ButtonCallback(obj, event):
    #print "button"
    if event == "LeftButtonPressEvent":
        actions["Slicing"] = 1
    else:
        actions["Slicing"] = 0

def MouseMoveCallback(obj, event):
    #print "mouse move"
    (lastX, lastY) = interactor.GetLastEventPosition()
    (mouseX, mouseY) = interactor.GetEventPosition()
Ejemplo n.º 52
0
def display(image, image_pos_pat, image_ori_pat):
	global xMin, xMax, yMin, yMax, zMin, zMax, xSpacing, ySpacing, zSpacing, interactor, actions, reslice, interactorStyle
	# The box widget observes the events invoked by the render window
	# interactor.  These events come from user interaction in the render
	# window.
	# boxWidget = vtk.vtkBoxWidget()
	# boxWidget.SetInteractor(iren1)
	# boxWidget.SetPlaceFactor(1)
	
	# Initialize Image orienation
	IO = matrix(	[[0, 0,-1, 0],
			[1, 0, 0, 0],
			[0,-1, 0, 0],
			[0, 0, 0, 1]])
	# Assign the 6-Image orientation patient coordinates (from Dicomtags)
	IO[0,0] = image_ori_pat[0]; IO[1,0] = image_ori_pat[1]; IO[2,0] = image_ori_pat[2]; 
	IO[0,1] = image_ori_pat[3]; IO[1,1] = image_ori_pat[4]; IO[2,1] = 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[0,2] = IO_col3[0]; IO[1,2] = 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 "image_pos_pat :"
	print image_pos_pat
	print "image_ori_pat:"
	print image_ori_pat
	
	origin = IP*IO.I
	print "Volume Origin:"
	print origin[0,0], origin[0,1], origin[0,2]
	
	# 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()
	
	##########################
	# Calculate the center of the volume
	(xMin, xMax, yMin, yMax, zMin, zMax) = image.GetWholeExtent()
	(xSpacing, ySpacing, zSpacing) = image.GetSpacing()
	(x0, y0, z0) = image.GetOrigin()
	
	center = [x0 + xSpacing * 0.5 * (xMin + xMax),
		  y0 + ySpacing * 0.5 * (yMin + yMax),
		  z0 + zSpacing * 0.5 * (zMin + zMax)]
	
	# Matrices for axial, coronal, sagittal, oblique view orientations
	axial = vtk.vtkMatrix4x4()
	axial.DeepCopy((1, 0, 0, center[0],
			0, 1, 0, center[1],
			0, 0, 1, center[2],
			0, 0, 0, 1))
	
	coronal = vtk.vtkMatrix4x4()
	coronal.DeepCopy((1, 0, 0, center[0],
			  0, 0, 1, center[1],
			  0,-1, 0, center[2],
			  0, 0, 0, 1))
	
	sagittal = vtk.vtkMatrix4x4()
	sagittal.DeepCopy((0, 0,-1, center[0],
			   1, 0, 0, center[1],
			   0,-1, 0, center[2],
			   0, 0, 0, 1))
	
	oblique = vtk.vtkMatrix4x4()
	oblique.DeepCopy((1, 0, 0, center[0],
			  0, 0.866025, -0.5, center[1],
			  0, 0.5, 0.866025, center[2],
			  0, 0, 0, 1))
	
	# Extract a slice in the desired orientation
	reslice = vtk.vtkImageReslice()
	reslice.SetInput(image)
	reslice.SetOutputDimensionality(2)
	reslice.SetResliceAxes(sagittal)
	reslice.SetInterpolationModeToLinear()
	
	# Create a greyscale lookup table
	table = vtk.vtkLookupTable()
	table.SetRange(0, 2000) # image intensity range
	table.SetValueRange(0.0, 1.0) # from black to white
	table.SetSaturationRange(0.0, 0.0) # no color saturation
	table.SetRampToLinear()
	table.Build()
	
	# Map the image through the lookup table
	color = vtk.vtkImageMapToColors()
	color.SetLookupTable(table)
	color.SetInputConnection(reslice.GetOutputPort())

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

	renderer1 = vtk.vtkRenderer()
	renderer1.AddActor(actor)
	################
	    
	
	# set up cube actor with Orientation(R-L, A-P, S-O) using transform_cube
	# Set up to ALS (+X=A, +Y=S, +Z=L) source:
	cube = vtk.vtkAnnotatedCubeActor()
	cube.SetXPlusFaceText( "S" );
	cube.SetXMinusFaceText( "I" );
	cube.SetYPlusFaceText( "L" );
	cube.SetYMinusFaceText( "R" );
	cube.SetZPlusFaceText( "A" );
	cube.SetZMinusFaceText( "P" );
	cube.SetFaceTextScale( 0.5 );
	cube.GetAssembly().SetUserTransform( transform_cube );
		
	# Set UP the axes
	axes2 = vtk.vtkAxesActor()
	axes2.SetShaftTypeToCylinder();
	#axes2.SetUserTransform( transform_cube );		 
	axes2.SetTotalLength( 1.5, 1.5, 1.5 );
	axes2.SetCylinderRadius( 0.500 * axes2.GetCylinderRadius() );
	axes2.SetConeRadius( 1.025 * axes2.GetConeRadius() );
	axes2.SetSphereRadius( 1.500 * axes2.GetSphereRadius() );

	tprop2 = axes2.GetXAxisCaptionActor2D()
	tprop2.GetCaptionTextProperty();

	assembly = vtk.vtkPropAssembly();
	assembly.AddPart( axes2 );
	assembly.AddPart( cube );
	
	widget = vtk.vtkOrientationMarkerWidget();
	widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 );
	widget.SetOrientationMarker( assembly );
	widget.SetInteractor( iren1 );
	widget.SetViewport( 0.0, 0.0, 0.4, 0.4 );
	widget.SetEnabled( 1 );
	widget.InteractiveOff();
			
	# Set Up Camera view
	renderer1.SetBackground(0.0, 0.0, 0.0)
	camera = renderer1.GetActiveCamera()

	# bounds and initialize camera
	b = image.GetBounds()
	renderer1.ResetCamera(b)	
	renderer1.ResetCameraClippingRange()
	camera.SetViewUp(0.0,-1.0,0.0)
	camera.Azimuth(315)
	
	# Create a text property for both cube axes
	tprop = vtk.vtkTextProperty()
	tprop.SetColor(1, 1, 1)
	tprop.ShadowOff()
	
	# Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
	# draw the axes.  Add the actor to the renderer.
	axes = vtk.vtkCubeAxesActor2D()
	axes.SetInput(image)
	axes.SetCamera(renderer1.GetActiveCamera())
	axes.SetLabelFormat("%6.4g")
	axes.SetFlyModeToOuterEdges()
	axes.SetFontFactor(1.2)
	axes.SetAxisTitleTextProperty(tprop)
	axes.SetAxisLabelTextProperty(tprop)      
	renderer1.AddViewProp(axes)
	
	############
	# Place the interactor initially. The input to a 3D widget is used to
	# initially position and scale the widget. The "EndInteractionEvent" is
  	# observed which invokes the SelectPolygons callback.
    	# boxWidget.SetInput(image)
	# boxWidget.PlaceWidget()
	# boxWidget.AddObserver("InteractionEvent", SelectPolygons)
	# boxWidget.On()
	# Initizalize
	# Set up the interaction
	interactorStyle = vtk.vtkInteractorStyleImage()
	interactor = vtk.vtkRenderWindowInteractor()
	interactor.SetInteractorStyle(interactorStyle)
	renWin1.SetInteractor(interactor)
	renWin1.Render()
	
	renderer1.Render()
	interactor.Start()
	renderer1.RemoveViewProp(axes)
						
	return transform_cube, zImagePlaneWidget.GetSliceIndex()
	def __init__(self, parent, **kws):
		"""
		Initialize the panel
		"""
		self.graySize = (0, 0)
		self.bgcolor = (127, 127, 127)
		self.maxClientSizeX, self.maxClientSizeY = 512, 512
		self.dataWidth, self.dataHeight = 512 , 512
		self.lastEventSize = None
		self.paintSize = (512, 512)
		self.parent = parent
		self.blackImage = None
		self.finalImage = None
		self.xdiff, self.ydiff = 0, 0
		self.oldZoomFactor = 1
		self.selectedItem = -1
		self.show = {}
		self.rawImages = []
		self.rawImage = None
		
		self.oldx, self.oldy = 0, 0
		self.curPos = (-1,-1)
		Logging.info("kws=", kws, kw = "preview")
		self.fixedSize = kws.get("previewsize", None)
		size = kws.get("previewsize", (1024, 1024))

		self.zoomFactor = kws.get("zoom_factor", 1)
		self.zoomx = kws.get("zoomx", 1)
		self.zoomy = kws.get("zoomy", 1)
		
		self.show["SCROLL"] = kws.get("scrollbars", 0)
		
		self.rgbMode = 0
		self.currentImage = None
		self.currentCt = None
		
		# The preview can be no larger than these
		
		self.dataDimX, self.dataDimY, self.dataDimZ = 0, 0, 0
		self.running = 0

		self.rgb = (255, 255, 0)

		self.timePoint = 0
		
		self.mapToColors = vtk.vtkImageMapToColors()
		self.mapToColors.SetLookupTable(self.currentCt)
		self.mapToColors.SetOutputFormatToRGB()
			
		self.renewNext = 0
		
		self.fitLater = 0
		self.imagedata = None
		self.bmp = None
		self.parent = parent
		self.scroll = 1
		Logging.info("preview panel size=", size, kw = "preview")
		
		x, y = size
		self.buffer = wx.EmptyBitmap(x, y)
		
		if kws.has_key("zoomx"):
			del kws["zoomx"]
		if kws.has_key("zoomy"):
			del kws["zoomy"]
			
		Logging.info("zoom xf=%f, yf=%f" % (self.zoomx, self.zoomy), kw = "preview")

		self.size = size
		self.slice = None
		self.z = 0
		self.zooming = 0
		self.scrollTo = None
		
		InteractivePanel.__init__(self, parent, size = size, bgColor = self.bgcolor, **kws)
		
		self.annotationsEnabled = True
		self.calculateBuffer()
		self.paintSize = self.GetClientSize()
		self.paintPreview()
		
		self.addListener(wx.EVT_RIGHT_DOWN, self.onRightClick)
		
		self.Bind(wx.EVT_SIZE, self.onSize)
		self.Bind(wx.EVT_LEFT_DOWN, self.onLeftDown)
		self.Bind(wx.EVT_MOTION, self.onMouseMotion)
		self.SetHelpText("This window displays the selected dataset slice by slice.")
		
		if not self.show["SCROLL"]:
			Logging.info("Disabling scrollbars", kw="preview")
			self.SetScrollbars(0, 0, 0, 0)
		self.updateAnnotations()
		self.drawableRect = self.GetClientRect()
		lib.messenger.connect(None, "zslice_changed", self.setPreviewedSlice)
		lib.messenger.connect(None, "renew_preview", self.setRenewFlag)
Ejemplo n.º 54
0
satLut.SetTableRange(0, 2000)
satLut.SetHueRange(.6, .6)
satLut.SetSaturationRange(0, 1)
satLut.SetValueRange(1, 1)
satLut.Build()

# Create the first of the three planes. The filter vtkImageMapToColors
# maps the data through the corresponding lookup table created above.
# The vtkImageActor is a type of vtkProp and conveniently displays an
# image on a single quadrilateral plane. It does this using texture
# mapping and as a result is quite fast. (Note: the input image has to
# be unsigned char values, which the vtkImageMapToColors produces.)
# Note also that by specifying the DisplayExtent, the pipeline
# requests data of this extent and the vtkImageMapToColors only
# processes a slice of data.
sagittalColors = vtk.vtkImageMapToColors()
sagittalColors.SetInputConnection(v16.GetOutputPort())
sagittalColors.SetLookupTable(bwLut)
sagittal = vtk.vtkImageActor()
sagittal.GetMapper().SetInputConnection(sagittalColors.GetOutputPort())
sagittal.SetDisplayExtent(32, 32, 0, 63, 0, 92)

# Create the second (axial) plane of the three planes. We use the same
# approach as before except that the extent differs.
axialColors = vtk.vtkImageMapToColors()
axialColors.SetInputConnection(v16.GetOutputPort())
axialColors.SetLookupTable(hueLut)
axial = vtk.vtkImageActor()
axial.GetMapper().SetInputConnection(axialColors.GetOutputPort())
axial.SetDisplayExtent(0, 63, 0, 63, 46, 46)
boneProperty.SetColor(1.0, 1.0, 0.9)

bone = vtk.vtkActor()
bone.SetMapper(boneMapper)
bone.SetProperty(boneProperty)

# ---------------------------------------------------------
# Create an image actor
table = vtk.vtkLookupTable()
table.SetRange(0, 2000)
table.SetRampToLinear()
table.SetValueRange(0, 1)
table.SetHueRange(0, 0)
table.SetSaturationRange(0, 0)

mapToColors = vtk.vtkImageMapToColors()
mapToColors.SetInputConnection(reader.GetOutputPort())
mapToColors.SetLookupTable(table)
mapToColors.Update()

imageActor = vtk.vtkImageActor()
imageActor.GetMapper().SetInputConnection(mapToColors.GetOutputPort())
imageActor.SetDisplayExtent(32, 32, 0, 63, 0, 92)

# ---------------------------------------------------------
# make a transform and some clipping planes
transform = vtk.vtkTransform()
transform.RotateWXYZ(-20, 0.0, -0.7, 0.7)

volume.SetUserTransform(transform)
bone.SetUserTransform(transform)
Ejemplo n.º 56
0
	def __init__(self, data_source, input_link):
		"""Parallel coordinates view constructor needs a valid DataSource plus
		and external annotation link (from the icicle view).
		"""		
		
		self.ds = data_source
		self.input_link = input_link
		
		# Set up callback to listen for changes in IcicleView selections
		self.input_link.AddObserver("AnnotationChangedEvent", self.InputSelectionCallback)
		
		# Set up an annotation link for other views to monitor selected image
		self.output_link = vtk.vtkAnnotationLink()
		# If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
		# See vtkSelectionNode doc for field and content type enum values
		self.output_link.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		# The chart seems to force INDEX selection, so I'm using vtkConvertSelection below to get
		# out PedigreeIds...
		self.output_link.GetCurrentSelection().GetNode(0).SetContentType(2)   # 2 = PedigreeIds, 4 = Indices
		# Going to manually create output_link selection list, so not setting up callback for it...
		
		if os.path.isfile(os.path.abspath('BlankImage.png')):
			blank_file = 'BlankImage.png'
		else:
			# For use in app bundles
			blank_file = os.path.join(sys.path[0],'BlankImage.png')
			
		self.blankImageReader = vtk.vtkPNGReader()
		self.blankImageReader.SetFileName(blank_file)
		self.blankImageReader.Update()
		
		tmp = self.blankImageReader.GetOutput().GetBounds()
		self.flowSpacing = float(tmp[1]-tmp[0])*1.1

		# Create a greyscale lookup table
		self.lut = self.ds.GetGrayscaleLUT('gray')
		self.lut.SetRange(self.blankImageReader.GetOutput().GetPointData().GetArray('PNGImage').GetRange()) # image intensity range
		
		# Map the image through the lookup table
		self.color = vtk.vtkImageMapToColors()
		self.color.SetLookupTable(self.lut)
		self.color.SetInput(self.blankImageReader.GetOutput())
		
		self.resliceList = []
		self.actorList = []
		self.numImages = 1

		# Map between indices of images and their Pedigree ID
		self.pedigree_id_dict = {}
		
		blankImageActor = vtk.vtkImageActor()
		blankImageActor.SetInput(self.color.GetOutput())
		blankImageActor.SetPickable(False)
		blankImageActor.SetOpacity(0.1)
		
		self.actorList.append(blankImageActor)

		self.expSpread = 0.5
		self.maxAngle = 80.0
		
		self.renderer = vtk.vtkRenderer()
		self.cam = self.renderer.GetActiveCamera()

		# renderer.SetBackground(0.15, 0.12, 0.1)
		# cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [68,57,53]]
		# self.renderer.SetBackground(cc0,cc1,cc2)
		# cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [60,60,60]]
		cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [160, 160, 160]]
		self.renderer.SetBackground(cc0,cc1,cc2)

		self.renderer.AddActor(self.actorList[0])
				
		self.highlightRect = vtk.vtkOutlineSource()
		self.highlightRect.SetBounds(self.actorList[0].GetBounds())
		self.highlightMapper = vtk.vtkPolyDataMapper()
		self.highlightMapper.SetInputConnection(self.highlightRect.GetOutputPort(0))
		self.highlightActor = vtk.vtkActor()
		self.highlightActor.SetMapper(self.highlightMapper)
		self.highlightActor.GetProperty().SetColor(0,0.5,1.0)
		self.highlightActor.GetProperty().SetLineWidth(6.0)
		self.highlightActor.GetProperty().SetOpacity(0.5)
		self.highlightActor.SetOrientation(self.actorList[0].GetOrientation())
		tmpPos = self.actorList[0].GetPosition()
		usePos = (tmpPos[0],tmpPos[1],tmpPos[2]+0.01)
		self.highlightActor.SetPosition(usePos)
		# Setting as if nothing picked even though initialized position & orientation to actor0
		self.highlightIndex = -1
		self.highlightActor.SetPickable(False)
		self.highlightActor.SetVisibility(False)
		self.renderer.AddActor(self.highlightActor)

		# Create the slider which will control the image positions
		self.sliderRep = vtk.vtkSliderRepresentation2D()
		self.sliderRep.SetMinimumValue(0)
		self.sliderRep.SetMaximumValue(self.numImages-1)
		self.sliderRep.SetValue(0)
		
		self.window = vtk.vtkRenderWindow()
		self.window.SetSize(600,300)

		self.window.AddRenderer(self.renderer)
				
		# Set up the interaction
		self.interactorStyle = vtk.vtkInteractorStyleImage()
		self.interactor = vtk.vtkRenderWindowInteractor()
		self.interactor.SetInteractorStyle(self.interactorStyle)
		self.window.SetInteractor(self.interactor)
				
		self.sliderWidget = vtk.vtkSliderWidget()
		self.sliderWidget.SetInteractor(self.interactor)
		self.sliderWidget.SetRepresentation(self.sliderRep)
		self.sliderWidget.SetAnimationModeToAnimate()
		self.sliderWidget.EnabledOn()
		
		self.sliderWidget.AddObserver("InteractionEvent", self.sliderCallback)
		self.sliderWidget.AddObserver("EndInteractionEvent", self.endSliderCallback)
		
		# Default flow direction Horizontal
		self.FlowDirection = Direction.Horizontal
		self.SetFlowDirection(self.FlowDirection)
				
		# Set up callback to toggle between inspect modes (manip axes & select data)
		# self.interactorStyle.AddObserver("SelectionChangedEvent", self.selectImage)

		# Create callbacks for mouse events
		self.mouseActions = {}
		self.mouseActions["LeftButtonDown"] = 0
		self.mouseActions["Picking"] = 0
		
		self.interactorStyle.AddObserver("MouseMoveEvent", self.MouseMoveCallback)
		self.interactorStyle.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
		self.interactorStyle.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback)

		self.cam.ParallelProjectionOn()
		self.renderer.ResetCamera(self.actorList[0].GetBounds())
		self.cam.Elevation(10)
		self.renderer.ResetCameraClippingRange()
Ejemplo n.º 57
0
    def testAllBlends(self):

        # This script calculates the luminance of an image

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

        # Image pipeline

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

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

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

        # shrink the images to a reasonable size

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

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

        # create a greyscale version

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

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

        # create an alpha mask

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

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

        # make luminanceAlpha and colorAlpha versions

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

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

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

        deltaX = 1.0 / 4.0
        deltaY = 1.0 / 2.0

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

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

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

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

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

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

                column += 1

        # render and interact with data

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

        img_file = "TestAllBlends.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Ejemplo n.º 58
0
# warp an image with a thin plate spline
# first, create an image to warp
imageGrid = vtk.vtkImageGridSource()
imageGrid.SetGridSpacing(16,16,0)
imageGrid.SetGridOrigin(0,0,0)
imageGrid.SetDataExtent(0,255,0,255,0,0)
imageGrid.SetDataScalarTypeToUnsignedChar()
table = vtk.vtkLookupTable()
table.SetTableRange(0,1)
table.SetValueRange(1.0,0.0)
table.SetSaturationRange(0.0,0.0)
table.SetHueRange(0.0,0.0)
table.SetAlphaRange(0.0,1.0)
table.Build()
alpha = vtk.vtkImageMapToColors()
alpha.SetInputConnection(imageGrid.GetOutputPort())
alpha.SetLookupTable(table)
reader1 = vtk.vtkBMPReader()
reader1.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/masonry.bmp")
blend = vtk.vtkImageBlend()
blend.AddInputConnection(0,reader1.GetOutputPort())
blend.AddInputConnection(0,alpha.GetOutputPort())
# next, create a ThinPlateSpline transform
p1 = vtk.vtkPoints()
p1.SetNumberOfPoints(8)
p1.SetPoint(0,0,0,0)
p1.SetPoint(1,0,255,0)
p1.SetPoint(2,255,0,0)
p1.SetPoint(3,255,255,0)
p1.SetPoint(4,96,96,0)