Ejemplo n.º 1
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageLuminance(), 'Processing.',
         ('vtkImageData',), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 2
0
 def onApply(self):
   inputVolume = self.inputSelector.currentNode()
   outputVolume = self.outputSelector.currentNode()
   # check for input data
   if not (inputVolume and outputVolume):
     slicer.util.errorDisplay('Input and output volumes are required for conversion', windowTitle='Luminance')
     return
   # check that data has enough components
   inputImage = inputVolume.GetImageData()
   if not inputImage or inputImage.GetNumberOfScalarComponents() < 3:
     slicer.util.errorDisplay('Input does not have enough components for conversion',
                              windowTitle='Vector to Scalar Volume')
     return
   # run the filter
   # - extract the RGB portions
   extract = vtk.vtkImageExtractComponents()
   extract.SetComponents(0,1,2)
   luminance = vtk.vtkImageLuminance()
   extract.SetInputConnection(inputVolume.GetImageDataConnection())
   luminance.SetInputConnection(extract.GetOutputPort())
   luminance.Update()
   ijkToRAS = vtk.vtkMatrix4x4()
   inputVolume.GetIJKToRASMatrix(ijkToRAS)
   outputVolume.SetIJKToRASMatrix(ijkToRAS)
   outputVolume.SetImageDataConnection(luminance.GetOutputPort())
   # make the output volume appear in all the slice views
   selectionNode = slicer.app.applicationLogic().GetSelectionNode()
   selectionNode.SetReferenceActiveVolumeID(outputVolume.GetID())
   slicer.app.applicationLogic().PropagateVolumeSelection(0)
Ejemplo n.º 3
0
 def onApply(self):
     inputVolume = self.inputSelector.currentNode()
     outputVolume = self.outputSelector.currentNode()
     # check for input data
     if not (inputVolume and outputVolume):
         slicer.util.errorDisplay(
             'Input and output volumes are required for conversion',
             windowTitle='Luminance')
         return
     # check that data has enough components
     inputImage = inputVolume.GetImageData()
     if not inputImage or inputImage.GetNumberOfScalarComponents() < 3:
         slicer.util.errorDisplay(
             'Input does not have enough components for conversion',
             windowTitle='Vector to Scalar Volume')
         return
     # run the filter
     # - extract the RGB portions
     extract = vtk.vtkImageExtractComponents()
     extract.SetComponents(0, 1, 2)
     luminance = vtk.vtkImageLuminance()
     extract.SetInputConnection(inputVolume.GetImageDataConnection())
     luminance.SetInputConnection(extract.GetOutputPort())
     luminance.Update()
     ijkToRAS = vtk.vtkMatrix4x4()
     inputVolume.GetIJKToRASMatrix(ijkToRAS)
     outputVolume.SetIJKToRASMatrix(ijkToRAS)
     outputVolume.SetImageDataConnection(luminance.GetOutputPort())
     # make the output volume appear in all the slice views
     selectionNode = slicer.app.applicationLogic().GetSelectionNode()
     selectionNode.SetReferenceActiveVolumeID(outputVolume.GetID())
     slicer.app.applicationLogic().PropagateVolumeSelection(0)
Ejemplo n.º 4
0
  def run(self, inputFile, enableScreenshots=0):
    """
    Run the actual algorithm
    """
    #parse logfile
    logging.info('Processing started')
    imageLogFile = LogDataObject()   #initialize log object 
    imageLogFile.ImportFromFile(inputFile)  #import image parameters of log object
    
    if not(imageLogFile.VerifyParameters()): #check that all parameters were set 
      logging.info('Failed: Log file parameters not set')
      return False
    if not(self.isValidImageFileType(imageLogFile.FileType)): #check for valid file type
      logging.info('Failed: Invalid image type')
      logging.info(imageLogFile.FileType)
      return False
    
    # read image 
    (inputDirectory,logPath) = os.path.split(inputFile)
    imageFileTemplate = os.path.join(inputDirectory, imageLogFile.Prefix + imageLogFile.SequenceStart + "." + imageLogFile.FileType)
    readVolumeNode = slicer.util.loadVolume(imageFileTemplate) 
    #calculate image spacing
    spacing = [imageLogFile.Resolution, imageLogFile.Resolution, imageLogFile.Resolution]
    
    # if vector image, convert to scalar using luminance (0.30*R + 0.59*G + 0.11*B + 0.0*A)
    #check if loaded volume is vector type, if so convert to scalar
    if readVolumeNode.GetClassName() =='vtkMRMLVectorVolumeNode':
      scalarVolumeNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLScalarVolumeNode', imageLogFile.Prefix)
      ijkToRAS = vtk.vtkMatrix4x4()
      readVolumeNode.GetIJKToRASMatrix(ijkToRAS)
      scalarVolumeNode.SetIJKToRASMatrix(ijkToRAS)
          
      scalarVolumeNode.SetSpacing(spacing)
      extractVTK = vtk.vtkImageExtractComponents()
      extractVTK.SetInputConnection(readVolumeNode.GetImageDataConnection())
      extractVTK.SetComponents(0, 1, 2)
      luminance = vtk.vtkImageLuminance()
      luminance.SetInputConnection(extractVTK.GetOutputPort())
      luminance.Update()
      scalarVolumeNode.SetImageDataConnection(luminance.GetOutputPort()) # apply
      slicer.mrmlScene.RemoveNode(readVolumeNode)
      
    else:
      scalarVolumeNode = readVolumeNode    
      scalarVolumeNode.SetSpacing(spacing)
      scalarVolumeNode.SetName(imageLogFile.Prefix)
    
    self.applySkyscanTransform(scalarVolumeNode)  
    slicer.util.resetSliceViews() #update the field of view 
    
    # Capture screenshot      
    if enableScreenshots:
      self.takeScreenshot('SkyscanReconImportTest-Start','MyScreenshot',-1)
    logging.info('Processing completed')

    return True
    def runConversionMethodLuminance(self, inputVolumeNode, outputVolumeNode):
        ijkToRAS = vtk.vtkMatrix4x4()
        inputVolumeNode.GetIJKToRASMatrix(ijkToRAS)
        outputVolumeNode.SetIJKToRASMatrix(ijkToRAS)

        extract = vtk.vtkImageExtractComponents()
        extract.SetInputConnection(inputVolumeNode.GetImageDataConnection())
        extract.SetComponents(0, 1, 2)
        luminance = vtk.vtkImageLuminance()
        luminance.SetInputConnection(extract.GetOutputPort())
        luminance.Update()
        outputVolumeNode.SetImageDataConnection(luminance.GetOutputPort())
Ejemplo n.º 6
0
def VtkRead(filepath, t):
    if not const.VTK_WARNING:
        log_path = os.path.join(const.USER_LOG_DIR, 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path.encode(const.FS_ENCODE))
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)

    global no_error

    if t == "bmp":
        reader = vtk.vtkBMPReader()

    elif t == "tiff" or t == "tif":
        reader = vtk.vtkTIFFReader()

    elif t == "png":
        reader = vtk.vtkPNGReader()

    elif t == "jpeg" or t == "jpg":
        reader = vtk.vtkJPEGReader()

    else:
        return False

    print ">>>> bmp reader", type(filepath)

    reader.AddObserver("ErrorEvent", VtkErrorToPy)
    reader.SetFileName(filepath.encode(const.FS_ENCODE))
    reader.Update()

    if no_error:
        image = reader.GetOutput()
        dim = image.GetDimensions()

        if reader.GetNumberOfScalarComponents() > 1:
            luminanceFilter = vtk.vtkImageLuminance()
            luminanceFilter.SetInputData(image)
            luminanceFilter.Update()

            image = vtk.vtkImageData()
            image.DeepCopy(luminanceFilter.GetOutput())

        img_array = numpy_support.vtk_to_numpy(
            image.GetPointData().GetScalars())
        img_array.shape = (dim[1], dim[0])

        return img_array
    else:
        no_error = True
        return False
Ejemplo n.º 7
0
    def bw(self):
        """Make it black and white"""
        n = self._data.GetPointData().GetNumberOfComponents()
        if n==4:
            ecr = vtk.vtkImageExtractComponents()
            ecr.SetInputData(self._data)
            ecr.SetComponents(0,1,2)
            ecr.Update()
            img = ecr.GetOutput()
        else:
            img = self._data

        ecr = vtk.vtkImageLuminance()
        ecr.SetInputData(img)
        ecr.Update()
        return self._update(ecr.GetOutput())
Ejemplo n.º 8
0
    def __init__(self):
        super(camphorBlendedVOIs, self).__init__()

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

        # Blenders
        self.blender = vtk.vtkImageBlend()
        self.sliceBlender = vtk.vtkImageBlend()

        # Other objects
        self.image = []
        self.append = vtk.vtkImageAppendComponents()
        self.luminance = vtk.vtkImageLuminance()

        # Output objects
        self.output = self.blender
        self.sliceOutput = self.append
Ejemplo n.º 9
0
    def processOutputData(self, data):
        """
		Process the data before it's send to the preview
		"""
        data.UpdateInformation()
        if self.mode == 0:  # MIP mode
            if not self.mip:
                self.mip = vtkbxd.vtkImageSimpleMIP()
            else:
                self.mip.RemoveAllInputs()
            self.mip.SetInput(data)
            data = self.mip.GetOutput()
        else:  # AIP mode
            scalarType = data.GetScalarType()
            imgType = "IUC"
            if scalarType == 5:
                imgType = "IUS"
            elif scalarType == 9:
                imgType = "IUL"
            elif scalarType == 10:
                imgType = "IF"

            self.convVTKtoITK = eval("itk.VTKImageToImageFilter.%s3.New()" %
                                     imgType)
            if data.GetNumberOfScalarComponents() > 1:
                imageLuminance = vtk.vtkImageLuminance()
                imageLuminance.SetInput(data)
                data = imageLuminance.GetOutput()
            self.convVTKtoITK.SetInput(data)
            self.convVTKtoITK.Update()
            itkImg = self.convVTKtoITK.GetOutput()

            self.pif = eval("itk.MeanProjectionImageFilter.%s3%s2.New()" %
                            (imgType, imgType))
            self.pif.SetInput(itkImg)
            output = self.pif.GetOutput()

            self.convITKtoVTK = itk.ImageToVTKImageFilter[output].New()
            self.convITKtoVTK.SetInput(output)
            self.convITKtoVTK.Update()
            data = self.convITKtoVTK.GetOutput()

        return PreviewFrame.PreviewFrame.processOutputData(self, data)
Ejemplo n.º 10
0
    def getScalarNodeFrom2DNode(self, vectorNode):
        """ Get a 3D vtkMRMLScalarVolumeNode (1 slice) from a vtkMRMLVectorVolumeNode
        :param vectorNode:
        :return: output volume
        """
        extract = vtk.vtkImageExtractComponents()
        extract.SetComponents(0, 1, 2)
        luminance = vtk.vtkImageLuminance()
        extract.SetInputConnection(vectorNode.GetImageDataConnection())
        luminance.SetInputConnection(extract.GetOutputPort())
        luminance.Update()
        ijkToRAS = vtk.vtkMatrix4x4()
        vectorNode.GetIJKToRASMatrix(ijkToRAS)

        outputVolume = slicer.mrmlScene.CreateNodeByClass(
            "vtkMRMLScalarVolumeNode")
        slicer.mrmlScene.AddNode(outputVolume)
        outputVolume.SetName(vectorNode.GetName() + "_3D")
        outputVolume.SetIJKToRASMatrix(ijkToRAS)
        outputVolume.SetImageDataConnection(luminance.GetOutputPort())
        return outputVolume
Ejemplo n.º 11
0
    def __init__(self, parent, visualizer, **kws):
        """
		Initialization
		"""
        VisualizationModule.__init__(self, parent, visualizer, **kws)

        self.descs = {
            "Normals": "Smooth surface with normals",
            "FeatureAngle": "Feature angle of normals",
            "Slice": "Select slice to be warped",
            "Scale": "Scale factor for warping"
        }

        self.luminance = vtk.vtkImageLuminance()

        #DataGeometry filter, image to polygons
        self.geometry = vtk.vtkImageDataGeometryFilter()

        self.colorMapper = None
        #warp scalars!
        self.warp = vtk.vtkWarpScalar()
        self.warp.SetScaleFactor(-0.1)

        #merge image and new warped data
        self.merge = vtk.vtkMergeFilter()

        self.normals = vtk.vtkPolyDataNormals()
        self.normals.SetFeatureAngle(90)
        #first the mapper
        self.mapper = vtk.vtkPolyDataMapper()

        #make the actor from the mapper
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)

        self.renderer = self.parent.getRenderer()
        self.renderer.AddActor(self.actor)

        #        iactor = self.wxrenwin.GetRenderWindow().GetInteractor()
        self.filterDesc = "Visualize 2D slice as 3D map"
Ejemplo n.º 12
0
 def onApply(self):
   inputVolume = self.inputSelector.currentNode()
   outputVolume = self.outputSelector.currentNode()
   # check for input data
   if not (inputVolume and outputVolume):
     qt.QMessageBox.critical(
         slicer.util.mainWindow(),
         'Luminance', 'Input and output volumes are required for conversion')
     return
   # check that data has enough components
   inputImage = inputVolume.GetImageData()
   if not inputImage or inputImage.GetNumberOfScalarComponents() < 3:
     qt.QMessageBox.critical(
         slicer.util.mainWindow(),
         'Vector to Scalar Volume', 'Input does not have enough components for conversion')
     return
   # run the filter
   # - extract the RGB portions
   extract = vtk.vtkImageExtractComponents()
   extract.SetComponents(0,1,2)
   luminance = vtk.vtkImageLuminance()
   if vtk.VTK_MAJOR_VERSION <= 5:
     extract.SetInput(inputVolume.GetImageData())
     luminance.SetInput(extract.GetOutput())
     luminance.GetOutput().Update()
   else:
     extract.SetInputConnection(inputVolume.GetImageDataConnection())
     luminance.SetInputConnection(extract.GetOutputPort())
     luminance.Update()
   ijkToRAS = vtk.vtkMatrix4x4()
   inputVolume.GetIJKToRASMatrix(ijkToRAS)
   outputVolume.SetIJKToRASMatrix(ijkToRAS)
   if vtk.VTK_MAJOR_VERSION <= 5:
     outputVolume.SetAndObserveImageData(luminance.GetOutput())
   else:
     outputVolume.SetImageDataConnection(luminance.GetOutputPort())
   # make the output volume appear in all the slice views
   selectionNode = slicer.app.applicationLogic().GetSelectionNode()
   selectionNode.SetReferenceActiveVolumeID(outputVolume.GetID())
   slicer.app.applicationLogic().PropagateVolumeSelection(0)
Ejemplo n.º 13
0
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())
Ejemplo n.º 14
0
#!/usr/bin/env python

# This example shows how to combine data from both the imaging and
# graphics pipelines. The vtkMergeFilter is used to merge the data
# from each together.

import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Read in an image and compute a luminance value. The image is
# extracted as a set of polygons (vtkImageDataGeometryFilter). We then
# will warp the plane using the scalar (luminance) values.
reader = vtk.vtkBMPReader()
reader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")
luminance = vtk.vtkImageLuminance()
luminance.SetInputConnection(reader.GetOutputPort())
geometry = vtk.vtkImageDataGeometryFilter()
geometry.SetInputConnection(luminance.GetOutputPort())
warp = vtk.vtkWarpScalar()
warp.SetInputConnection(geometry.GetOutputPort())
warp.SetScaleFactor(-0.1)

# Use vtkMergeFilter to combine the original image with the warped
# geometry.
merge = vtk.vtkMergeFilter()
merge.SetGeometryConnection(warp.GetOutputPort())
merge.SetScalarsConnection(reader.GetOutputPort())
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(merge.GetOutputPort())
mapper.SetScalarRange(0, 255)
Ejemplo n.º 15
0
# Convert a 3-component VTI to single component.
import vtk

# Read the file.
file_name = 'image.vti'
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(file_name)
reader.Update()

# Get the image data.
image = reader.GetOutput()
dims = image.GetDimensions()
extent = image.GetExtent()
origin = image.GetOrigin()
spacing = image.GetSpacing()
scalars = image.GetPointData().GetScalars()

# Convert RGB to grayscale.
luminance_filter = vtk.vtkImageLuminance()
luminance_filter.SetInputData(image)
luminance_filter.Update()

# Write converted VTI.
file_name = 'converted.vti'
writer = vtk.vtkXMLImageDataWriter()
writer.SetFileName(file_name)
writer.SetInputData(luminance_filter.GetOutput())
writer.Write()

Ejemplo n.º 16
0
def setupPipeline():
    #read file
    global reader
    reader = vtk.vtkOBJReader()
    reader.SetFileName(filename)

    #map 3d model
    global mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(reader.GetOutputPort())

    #set actor
    global actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Create a rendering window and renderer
    global ren
    ren = vtk.vtkRenderer()
    ren.SetBackground(0, 0, 0)
    ren.AddActor(actor)

    global intermediateWindow
    intermediateWindow = vtk.vtkRenderWindow()
    intermediateWindow.AddRenderer(ren)

    #render image
    global renImage
    renImage = vtk.vtkRenderLargeImage()
    renImage.SetInput(ren)
    renImage.SetMagnification(magnificationFactor)

    #Canny edge detector inspired by
    #https://vtk.org/Wiki/VTK/Examples/Cxx/Images/CannyEdgeDetector

    #to grayscale
    global lumImage
    lumImage = vtk.vtkImageLuminance()
    lumImage.SetInputConnection(renImage.GetOutputPort())

    #to float
    global floatImage
    floatImage = vtk.vtkImageCast()
    floatImage.SetOutputScalarTypeToFloat()
    floatImage.SetInputConnection(lumImage.GetOutputPort())

    #gaussian convolution
    global smoothImage
    smoothImage = vtk.vtkImageGaussianSmooth()
    smoothImage.SetInputConnection(floatImage.GetOutputPort())
    smoothImage.SetDimensionality(2)
    smoothImage.SetRadiusFactors(1, 1, 0)

    #gradient
    global gradientImage
    gradientImage = vtk.vtkImageGradient()
    gradientImage.SetInputConnection(smoothImage.GetOutputPort())
    gradientImage.SetDimensionality(2)

    #gradient magnitude
    global magnitudeImage
    magnitudeImage = vtk.vtkImageMagnitude()
    magnitudeImage.SetInputConnection(gradientImage.GetOutputPort())

    #non max suppression
    global nonmaxSuppr
    nonmaxSuppr = vtk.vtkImageNonMaximumSuppression()
    nonmaxSuppr.SetDimensionality(2)

    #padding
    global padImage
    padImage = vtk.vtkImageConstantPad()
    padImage.SetInputConnection(gradientImage.GetOutputPort())
    padImage.SetOutputNumberOfScalarComponents(3)
    padImage.SetConstant(0)

    #to structured points
    global i2sp1
    i2sp1 = vtk.vtkImageToStructuredPoints()
    i2sp1.SetInputConnection(nonmaxSuppr.GetOutputPort())

    #link edges
    global linkImage
    linkImage = vtk.vtkLinkEdgels()
    linkImage.SetInputConnection(i2sp1.GetOutputPort())
    linkImage.SetGradientThreshold(2)

    #thresholds links
    global thresholdEdgels
    thresholdEdgels = vtk.vtkThreshold()
    thresholdEdgels.SetInputConnection(linkImage.GetOutputPort())
    thresholdEdgels.ThresholdByUpper(10)
    thresholdEdgels.AllScalarsOff()

    #filter
    global gf
    gf = vtk.vtkGeometryFilter()
    gf.SetInputConnection(thresholdEdgels.GetOutputPort())

    #to structured points
    global i2sp
    i2sp = vtk.vtkImageToStructuredPoints()
    i2sp.SetInputConnection(magnitudeImage.GetOutputPort())

    #subpixel
    global spe
    spe = vtk.vtkSubPixelPositionEdgels()
    spe.SetInputConnection(gf.GetOutputPort())

    #stripper
    global strip
    strip = vtk.vtkStripper()
    strip.SetInputConnection(spe.GetOutputPort())

    global dsm
    dsm = vtk.vtkPolyDataMapper()
    dsm.SetInputConnection(strip.GetOutputPort())
    dsm.ScalarVisibilityOff()

    global planeActor
    planeActor = vtk.vtkActor()
    planeActor.SetMapper(dsm)
    planeActor.GetProperty().SetAmbient(1.0)
    planeActor.GetProperty().SetDiffuse(0.0)

    global edgeRender
    edgeRender = vtk.vtkRenderer()
    edgeRender.AddActor(planeActor)
    global renderWindow
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(edgeRender)

    global finalImage
    finalImage = vtk.vtkRenderLargeImage()
    finalImage.SetMagnification(magnificationFactor)
    finalImage.SetInput(edgeRender)

    global revImage
    revImage = vtk.vtkImageThreshold()
    revImage.SetInputConnection(finalImage.GetOutputPort())
    revImage.ThresholdByUpper(127)
    revImage.ReplaceInOn()
    revImage.ReplaceOutOn()
    revImage.SetOutValue(255)
    revImage.SetInValue(0)

    #write image
    global imgWriter
    imgWriter = vtk.vtkPNGWriter()
    imgWriter.SetInputConnection(revImage.GetOutputPort())
    imgWriter.SetFileName("test.png")
Ejemplo n.º 17
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.º 18
0
def main():
    fileName = get_program_parameters()

    colors = vtk.vtkNamedColors()
    # Set the background color. Match those in VTKTextbook.pdf.
    bkg = map(lambda x: x / 256.0, [60, 93, 144])
    colors.SetColor("BkgColor", *bkg)

    # Read in an image and compute a luminance value. The image is extracted
    # as a set of polygons (vtkImageDataGeometryFilter). We then will
    # warp the plane using the scalar (luminance) values.
    #
    reader = vtk.vtkBMPReader()
    reader.SetFileName(fileName)
    # Convert the image to a grey scale.
    luminance = vtk.vtkImageLuminance()
    luminance.SetInputConnection(reader.GetOutputPort())
    # Pass the data to the pipeline as polygons.
    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInputConnection(luminance.GetOutputPort())
    # Warp the data in a direction perpendicular to the image plane.
    warp = vtk.vtkWarpScalar()
    warp.SetInputConnection(geometry.GetOutputPort())
    warp.SetScaleFactor(-0.1)

    # Use vtkMergeFilter to combine the original image with the warped geometry.
    merge = vtk.vtkMergeFilter()
    merge.SetGeometryConnection(warp.GetOutputPort())
    merge.SetScalarsConnection(reader.GetOutputPort())
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(merge.GetOutputPort())
    mapper.SetScalarRange(0, 255)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Create the rendering window, renderer, and interactive renderer.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size.
    ren.AddActor(actor)
    ren.ResetCamera()
    ren.SetBackground(colors.GetColor3d("BkgColor"))
    # ren.GetActiveCamera().Azimuth(20)
    # ren.GetActiveCamera().Elevation(30)
    # ren.ResetCameraClippingRange()
    # ren.GetActiveCamera().Zoom(1.3)
    ren.GetActiveCamera().SetPosition(-100, -130, 325)
    ren.GetActiveCamera().SetFocalPoint(105, 114, -29)
    ren.GetActiveCamera().SetViewUp(0.51, 0.54, 0.67)
    ren.ResetCameraClippingRange()

    renWin.SetSize(512, 512)

    # Render the image.
    iren.Initialize()
    renWin.Render()
    iren.Start()