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

        # setup config
        self._config.resolution = 40

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

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

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

        self._output = vtk.vtkImageData()

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

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

        # setup config
        self._config.resolution = 40

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

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

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

        self._output = vtk.vtkImageData()

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

        self.sync_module_logic_with_config()
Example #3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageEllipsoidSource(), 'Processing.',
         (), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Example #4
0
    def generate_image(self, scalar_type):
        # Create source
        source = vtk.vtkImageEllipsoidSource()
        source.SetWholeExtent(0, 20, 0, 20, 0, 0)
        source.SetCenter(10, 10, 0)
        source.SetRadius(3, 4, 0)
        source.SetOutputScalarType(scalar_type)

        return source
    def generate_image(self, filename, writer):
        # Create source
        source = vtk.vtkImageEllipsoidSource()
        source.SetWholeExtent(0, 20, 0, 20, 0, 0)
        source.SetCenter(10, 10, 0)
        source.SetRadius(3, 4, 0)
        source.SetOutputScalarTypeToFloat()

        writer.SetInputConnection(source.GetOutputPort())
        writer.SetFileName(filename)
        writer.Update()

        self.assertTrue(os.path.isfile(filename))
Example #6
0
def createEllipsoid(extent=(0,99,0,99,0,99), center=(50, 50, 50), radius=(20, 35, 25), coding='uchar',values=(255,0)):
    """
    create a stupid ellipsoid (test purpose)
    """
    ellipse = vtk.vtkImageEllipsoidSource();
    ellipse.SetWholeExtent(*extent); 
    ellipse.SetCenter(*center);
    ellipse.SetRadius(*radius);
    if coding=='uchar':
        ellipse.SetOutputScalarTypeToUnsignedChar();
    elif coding=='ushort':
        ellipse.SetOutputScalarTypeToUnsignedShort();
    else:
        print 'bad coding : %s' % coding
        sys.exit(1)
    ellipse.SetInValue(values[0]);
    ellipse.SetOutValue(values[1]);
    ellipse.Update()
    return ellipse.GetOutput()
    def TextureMappedPlane(self, obj, event):

        # use dummy image data here
        e = vtk.vtkImageEllipsoidSource()

        scene = slicer.mrmlScene

        # Create model node
        model = slicer.vtkMRMLModelNode()
        model.SetScene(scene)
        model.SetName(scene.GenerateUniqueName("2DImageModel"))

        planeSource = vtk.vtkPlaneSource()
        model.SetAndObservePolyData(planeSource.GetOutput())

        # Create display node
        modelDisplay = slicer.vtkMRMLModelDisplayNode()
        modelDisplay.SetColor(1, 1, 0)  # yellow
        # modelDisplay.SetBackfaceCulling(0)
        modelDisplay.SetScene(scene)
        scene.AddNode(modelDisplay)
        model.SetAndObserveDisplayNodeID(modelDisplay.GetID())

        modelDisplay.SetSliceIntersectionVisibility(True)
        modelDisplay.SetVisibility(True)

        # Add to scene
        modelDisplay.SetTextureImageDataConnection(e.GetOutputPort())
        # modelDisplay.SetInputPolyDataConnection(model.GetPolyDataConnection())
        scene.AddNode(model)

        transform = slicer.vtkMRMLLinearTransformNode()
        scene.AddNode(transform)
        model.SetAndObserveTransformNodeID(transform.GetID())

        vTransform = vtk.vtkTransform()
        vTransform.Scale(50, 50, 50)
        vTransform.RotateX(30)
        # transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())
        transform.SetMatrixTransformToParent(vTransform.GetMatrix())
Example #8
0
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# A script to test the mask filter.
#  replaces a circle with a color
# Image pipeline
reader = vtk.vtkPNMReader()
reader.ReleaseDataFlagOff()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/earth.ppm")
reader.Update()
sphere = vtk.vtkImageEllipsoidSource()
sphere.SetWholeExtent(0,511,0,255,0,0)
sphere.SetCenter(128,128,0)
sphere.SetRadius(80,80,1)
sphere.Update()
mask = vtk.vtkImageMask()
mask.SetImageInputData(reader.GetOutput())
mask.SetMaskInputData(sphere.GetOutput())
mask.SetMaskedOutputValue(100,128,200)
mask.NotMaskOn()
mask.ReleaseDataFlagOff()
mask.Update()
sphere2 = vtk.vtkImageEllipsoidSource()
sphere2.SetWholeExtent(0,511,0,255,0,0)
sphere2.SetCenter(328,128,0)
sphere2.SetRadius(80,50,1)
sphere2.Update()
# Test the wrapping of the output masked value
mask2 = vtk.vtkImageMask()
    def testAllMathematics(self):

        # append multiple displaced spheres into an RGB image.

        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        sphere1 = vtk.vtkImageEllipsoidSource()
        sphere1.SetCenter(40, 20, 0)
        sphere1.SetRadius(30, 30, 0)
        sphere1.SetInValue(.75)
        sphere1.SetOutValue(.3)
        sphere1.SetOutputScalarTypeToFloat()
        sphere1.SetWholeExtent(0, 99, 0, 74, 0, 0)
        sphere1.Update()

        sphere2 = vtk.vtkImageEllipsoidSource()
        sphere2.SetCenter(60, 30, 0)
        sphere2.SetRadius(20, 20, 20)
        sphere2.SetInValue(.2)
        sphere2.SetOutValue(.5)
        sphere2.SetOutputScalarTypeToFloat()
        sphere2.SetWholeExtent(0, 99, 0, 74, 0, 0)
        sphere2.Update()

        mathematics = [
            "Add", "Subtract", "Multiply", "Divide", "Invert", "Sin", "Cos",
            "Exp", "Log", "AbsoluteValue", "Square", "SquareRoot", "Min",
            "Max", "ATAN", "ATAN2", "MultiplyByK", "ReplaceCByK", "AddConstant"
        ]

        mathematic = list()
        mapper = list()
        actor = list()
        imager = list()

        for idx, operator in enumerate(mathematics):
            mathematic.append(vtk.vtkImageMathematics())
            mathematic[idx].SetInput1Data(sphere1.GetOutput())
            mathematic[idx].SetInput2Data(sphere2.GetOutput())
            eval('mathematic[idx].SetOperationTo' + operator + '()')
            mathematic[idx].SetConstantK(.3)
            mathematic[idx].SetConstantC(.75)
            mapper.append(vtk.vtkImageMapper())
            mapper[idx].SetInputConnection(mathematic[idx].GetOutputPort())
            mapper[idx].SetColorWindow(2.0)
            mapper[idx].SetColorLevel(.75)
            actor.append(vtk.vtkActor2D())
            actor[idx].SetMapper(mapper[idx])
            imager.append(vtk.vtkRenderer())
            imager[idx].AddActor2D(actor[idx])
            renWin.AddRenderer(imager[idx])

        column = 1
        row = 1
        deltaX = 1.0 / 6.0
        deltaY = 1.0 / 4.0

        for idx, operator in enumerate(mathematics):
            imager[idx].SetViewport((column - 1) * deltaX, (row - 1) * deltaY,
                                    column * deltaX, row * deltaY)
            column += 1
            if column > 6:
                column = 1
                row += 1

        # Make the last operator finish the row
        vp = imager[len(mathematics) - 1].GetViewport()
        imager[len(mathematics) - 1].SetViewport(vp[0], vp[1], 1, 1)

        renWin.SetSize(600, 300)

        # render and interact with data

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

        img_file = "TestAllMathematics.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

#
# display text over an image
#
ellipse = vtk.vtkImageEllipsoidSource()
mapImage = vtk.vtkImageMapper()
mapImage.SetInputConnection(ellipse.GetOutputPort())
mapImage.SetColorWindow(255)
mapImage.SetColorLevel(127.5)
img = vtk.vtkActor2D()
img.SetMapper(mapImage)
mapText = vtk.vtkTextMapper()
mapText.SetInput("Text Overlay")
mapText.GetTextProperty().SetFontSize(15)
mapText.GetTextProperty().SetColor(0,1,1)
mapText.GetTextProperty().BoldOn()
mapText.GetTextProperty().ShadowOn()
txt = vtk.vtkActor2D()
txt.SetMapper(mapText)
txt.SetPosition(138,128)
ren1 = vtk.vtkRenderer()
ren1.AddActor2D(img)
ren1.AddActor2D(txt)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
Example #11
0
def ExtractFields(input_model,
                  output_image,
                  field_name,
                  outside_value=0.0,
                  lower_threshold=0.0,
                  upper_threshold=0.0,
                  output_type='float'):

    # Python 2/3 compatible input
    from six.moves import input

    # Check requested output type
    output_type = output_type.lower()
    if output_type not in EXTRACT_FIELDS_SUPPORTED_TYPES.keys():
        print('Valid output types: {}'.format(', '.join(
            EXTRACT_FIELDS_SUPPORTED_TYPES.keys())))
        os.sys.exit(
            '[ERROR] Requested type {} not supported'.format(output_type))

    # Read input
    if not os.path.isfile(input_model):
        os.sys.exit('[ERROR] Cannot find file \"{}\"'.format(input_model))

    # Test field name
    if field_name not in valid_fields():
        print('Valid field names: {}'.format(valid_fields()))
        os.sys.exit('[ERROR] Please provide a valid field name')

    print('Reading elements into image array')
    image, spacing, origin, n_elements = field_to_image(
        input_model, field_name, outside_value)
    print('  Spacing:            {}'.format(spacing))
    print('  Origin:             {}'.format(origin))
    print('  Dimensions:         {}'.format(image.shape))
    print('  Number of elements: {}'.format(n_elements))
    print('')

    # Convert to VTK
    print('Converting to vtkImageData')
    vtkImage = numpy_to_vtkImageData(image, spacing, origin)
    print('')

    if output_type == 'float':
        print('Not rescaling data')
    else:
        print('Rescaling data into {} dynamic range'.format(output_type))
        # Hack to get data type range
        source = vtk.vtkImageEllipsoidSource()
        source.SetWholeExtent(0, 1, 0, 1, 0, 0)
        source.SetCenter(0, 0, 0)
        source.SetRadius(0, 0, 0)
        source.SetOutputScalarType(EXTRACT_FIELDS_SUPPORTED_TYPES[output_type])
        source.Update()

        # Compute min/max
        if lower_threshold == upper_threshold:
            scalar_range = vtkImage.GetScalarRange()
        else:
            scalar_range = [lower_threshold, upper_threshold]
        dtype_range = [0, source.GetOutput().GetScalarTypeMax()]
        print(' Image range:  {}'.format(vtkImage.GetScalarRange()))
        print(' Input range:  {}'.format(scalar_range))
        print(' Output range: {}'.format(dtype_range))

        # Note the equation for shift/scale:
        #   u = (v + ScalarShift)*ScalarScale
        m = float(dtype_range[1] - dtype_range[0]) / float(scalar_range[1] -
                                                           scalar_range[0])
        b = float(dtype_range[1] - m * scalar_range[1])
        b = b / m

        print(' Shift: {}'.format(b))
        print(' Scale: {}'.format(m))

        scaler = vtk.vtkImageShiftScale()
        scaler.SetInputData(vtkImage)
        scaler.SetShift(b)
        scaler.SetScale(m)
        scaler.ClampOverflowOn()
        scaler.SetOutputScalarType(EXTRACT_FIELDS_SUPPORTED_TYPES[output_type])
        scaler.Update()
        vtkImage = scaler.GetOutput()

        print(' Output image range:  {}'.format(vtkImage.GetScalarRange()))
    print('')

    # Write image
    print('Saving image ' + output_image)
    writer = get_vtk_writer(output_image)
    if writer is None:
        os.sys.exit(
            '[ERROR] Cannot find writer for file \"{}\"'.format(output_image))
    writer.SetInputData(vtkImage)
    writer.SetFileName(output_image)
    writer.Update()
Example #12
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# A script to test the mask filter.
#  replaces a circle with a color
# Image pipeline
reader = vtk.vtkPNMReader()
reader.ReleaseDataFlagOff()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/earth.ppm")
reader.Update()
sphere = vtk.vtkImageEllipsoidSource()
sphere.SetWholeExtent(0,511,0,255,0,0)
sphere.SetCenter(128,128,0)
sphere.SetRadius(80,80,1)
sphere.Update()
mask = vtk.vtkImageMask()
mask.SetImageInputData(reader.GetOutput())
mask.SetMaskInputData(sphere.GetOutput())
mask.SetMaskedOutputValue(100,128,200)
mask.NotMaskOn()
mask.ReleaseDataFlagOff()
mask.Update()
sphere2 = vtk.vtkImageEllipsoidSource()
sphere2.SetWholeExtent(0,511,0,255,0,0)
sphere2.SetCenter(328,128,0)
sphere2.SetRadius(80,50,1)
sphere2.Update()
# Test the wrapping of the output masked value
Example #13
0
extent = (0, size, 0, size, 0, size)

# make image reader and get image
reader = vtk.vtkJPEGReader()
reader.SetDataExtent(extent)
reader.SetFilePattern(pattern)
reader.SetDataSpacing(1, 1, 1)
image = reader.GetOutput()
image.Update()

# add a component
extractor = vtk.vtkImageExtractComponents()
extractor.SetInput(image)
extractor.SetComponents(0)

ellipsoid = vtk.vtkImageEllipsoidSource()
ellipsoid.SetCenter(size / 2, size / 2, size / 2)
ellipsoid.SetWholeExtent(0, size + 1, 0, size + 1, 0, size + 1)
ellipsoid.SetOutputScalarTypeToUnsignedChar()
ellipsoid.SetRadius(20, 30, 40)
# remember that this is opacity per length, so the same value for the
# ellipsoid will seem much more transclucent than that for the outer
# portion of the cube.  What's weird is that with the inner cube set
# to 0 (totally opaque) and the outer cube set to something like 220,
# we get the expected effect.  But with the inner cube set to slightly
# translucent, about 10, the outer cube disappears.  When the values
# are too close, everything disappears.

# This is because we cannot have intermixing translucent
# geometries.  If one portion is translucent, the other portion must
# be either fully transparent or fully opaque.
Example #14
0
    def testAllLogic(self):

        # append multiple displaced spheres into an RGB image.

        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        logics = ["And", "Or", "Xor", "Nand", "Nor", "Not"]
        types = [
            "Float", "Double", "UnsignedInt", "UnsignedLong", "UnsignedShort",
            "UnsignedChar"
        ]

        sphere1 = list()
        sphere2 = list()
        logic = list()
        mapper = list()
        actor = list()
        imager = list()

        for idx, operator in enumerate(logics):
            ScalarType = types[idx]

            sphere1.append(vtk.vtkImageEllipsoidSource())
            sphere1[idx].SetCenter(95, 100, 0)
            sphere1[idx].SetRadius(70, 70, 70)
            eval('sphere1[idx].SetOutputScalarTypeTo' + ScalarType + '()')
            sphere1[idx].Update()

            sphere2.append(vtk.vtkImageEllipsoidSource())
            sphere2[idx].SetCenter(161, 100, 0)
            sphere2[idx].SetRadius(70, 70, 70)
            eval('sphere2[idx].SetOutputScalarTypeTo' + ScalarType + '()')
            sphere2[idx].Update()

            logic.append(vtk.vtkImageLogic())
            logic[idx].SetInput1Data(sphere1[idx].GetOutput())
            if operator != "Not":
                logic[idx].SetInput2Data(sphere2[idx].GetOutput())

            logic[idx].SetOutputTrueValue(150)
            eval('logic[idx].SetOperationTo' + operator + '()')

            mapper.append(vtk.vtkImageMapper())
            mapper[idx].SetInputConnection(logic[idx].GetOutputPort())
            mapper[idx].SetColorWindow(255)
            mapper[idx].SetColorLevel(127.5)

            actor.append(vtk.vtkActor2D())
            actor[idx].SetMapper(mapper[idx])

            imager.append(vtk.vtkRenderer())
            imager[idx].AddActor2D(actor[idx])

            renWin.AddRenderer(imager[idx])

        imager[0].SetViewport(0, .5, .33, 1)
        imager[1].SetViewport(.33, .5, .66, 1)
        imager[2].SetViewport(.66, .5, 1, 1)
        imager[3].SetViewport(0, 0, .33, .5)
        imager[4].SetViewport(.33, 0, .66, .5)
        imager[5].SetViewport(.66, 0, 1, .5)

        renWin.SetSize(768, 512)

        # render and interact with data

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

        img_file = "TestAllLogic.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
Example #15
0
def handle_supported_types(writer, typelist, output_type=vtk.VTK_FLOAT):
    '''Cast to required type

    If the type sent to writer is not in typelist, it will be converted
    to output_type.

    Args:
        writer (vtk.vtkImageWriter):    The file writer
        typelist (list):                List of types supported by this writer
        output_type (int):              Output type request as fall back

    Returns:
        Nothing
    '''

    # Determine input scalar type
    input_algorithm = writer.GetInputAlgorithm()
    # Input set with SetInputData?
    if type(input_algorithm) == type(vtk.vtkTrivialProducer()):
        scalar_type = writer.GetInput().GetScalarType()
    # Input set with SetInputConnection
    else:
        input_algorithm.Update()
        scalar_type = input_algorithm.GetOutput().GetScalarType()

    # Cast if not appropriate
    if scalar_type not in typelist:
        # If we can cast to float, just cast to float. Otherwise, rescale
        # the datatypes.
        if output_type != vtk.VTK_FLOAT:
            # Hack to get data type range
            source = vtk.vtkImageEllipsoidSource()
            source.SetWholeExtent(0, 1, 0, 1, 0, 0)
            source.SetCenter(10, 10, 0)
            source.SetRadius(3, 4, 0)
            source.SetOutputScalarType(output_type)
            source.Update()

            # Compute min/max
            scalar_range = input_algorithm.GetOutput().GetScalarRange()
            dtype_range = [
                source.GetOutput().GetScalarTypeMin(),
                source.GetOutput().GetScalarTypeMax()
            ]

            # Note the equation for shift/scale:
            #   u = (v + ScalarShift)*ScalarScale
            m = float(dtype_range[1] -
                      dtype_range[0]) / float(scalar_range[1] -
                                              scalar_range[0])
            b = float(dtype_range[1] - m * scalar_range[1])
            b = b / m

            caster = vtk.vtkImageReslice()
            caster.SetScalarShift(b)
            caster.SetScalarScale(m)
        else:
            caster = vtk.vtkImageCast()
        caster.SetInputConnection(input_algorithm.GetOutputPort())
        caster.SetOutputScalarType(output_type)
        caster.Update()

        writer.SetInputConnection(caster.GetOutputPort())
Example #16
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create the RenderWindow, Renderer and both Actors
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# First one tests the changing display extent without
# changing the size of the display extent (so it
# reuses a texture, but not a contiguous one)
gsOne = vtk.vtkImageEllipsoidSource()
gsOne.SetWholeExtent(0,999,0,999,0,0)
gsOne.SetCenter(500,500,0)
gsOne.SetRadius(300,400,0)
gsOne.SetInValue(0)
gsOne.SetOutValue(255)
gsOne.SetOutputScalarTypeToUnsignedChar()
ssOne = vtk.vtkImageShiftScale()
ssOne.SetInputConnection(gsOne.GetOutputPort())
ssOne.SetOutputScalarTypeToUnsignedChar()
ssOne.SetShift(0)
ssOne.SetScale(1)
ssOne.UpdateWholeExtent()
iaOne = vtk.vtkImageActor()
iaOne.GetMapper().SetInputConnection(ssOne.GetOutputPort())
ren1.AddActor(iaOne)
Example #17
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create the RenderWindow, Renderer and both Actors
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# First one tests the changing display extent without
# changing the size of the display extent (so it
# reuses a texture, but not a contiguous one)
gsOne = vtk.vtkImageEllipsoidSource()
gsOne.SetWholeExtent(0, 999, 0, 999, 0, 0)
gsOne.SetCenter(500, 500, 0)
gsOne.SetRadius(300, 400, 0)
gsOne.SetInValue(0)
gsOne.SetOutValue(255)
gsOne.SetOutputScalarTypeToUnsignedChar()
ssOne = vtk.vtkImageShiftScale()
ssOne.SetInputConnection(gsOne.GetOutputPort())
ssOne.SetOutputScalarTypeToUnsignedChar()
ssOne.SetShift(0)
ssOne.SetScale(1)
ssOne.UpdateWholeExtent()
iaOne = vtk.vtkImageActor()
iaOne.GetMapper().SetInputConnection(ssOne.GetOutputPort())
ren1.AddActor(iaOne)
    def testAllMathematics(self):

        # append multiple displaced spheres into an RGB image.


        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        sphere1 = vtk.vtkImageEllipsoidSource()
        sphere1.SetCenter(40, 20, 0)
        sphere1.SetRadius(30, 30, 0)
        sphere1.SetInValue(.75)
        sphere1.SetOutValue(.3)
        sphere1.SetOutputScalarTypeToFloat()
        sphere1.SetWholeExtent(0, 99, 0, 74, 0, 0)
        sphere1.Update()

        sphere2 = vtk.vtkImageEllipsoidSource()
        sphere2.SetCenter(60, 30, 0)
        sphere2.SetRadius(20, 20, 20)
        sphere2.SetInValue(.2)
        sphere2.SetOutValue(.5)
        sphere2.SetOutputScalarTypeToFloat()
        sphere2.SetWholeExtent(0, 99, 0, 74, 0, 0)
        sphere2.Update()

        mathematics = [ "Add", "Subtract", "Multiply", "Divide", "Invert", "Sin", "Cos",
                        "Exp", "Log", "AbsoluteValue", "Square", "SquareRoot", "Min",
                        "Max", "ATAN", "ATAN2", "MultiplyByK", "ReplaceCByK", "AddConstant"]

        mathematic = list()
        mapper = list()
        actor = list()
        imager = list()

        for idx, operator in enumerate(mathematics):
            mathematic.append(vtk.vtkImageMathematics())
            mathematic[idx].SetInput1Data(sphere1.GetOutput())
            mathematic[idx].SetInput2Data(sphere2.GetOutput())
            eval('mathematic[idx].SetOperationTo' + operator + '()')
            mathematic[idx].SetConstantK(.3)
            mathematic[idx].SetConstantC(.75)
            mapper.append(vtk.vtkImageMapper())
            mapper[idx].SetInputConnection(mathematic[idx].GetOutputPort())
            mapper[idx].SetColorWindow(2.0)
            mapper[idx].SetColorLevel(.75)
            actor.append(vtk.vtkActor2D())
            actor[idx].SetMapper(mapper[idx])
            imager.append(vtk.vtkRenderer())
            imager[idx].AddActor2D(actor[idx])
            renWin.AddRenderer(imager[idx])

        column = 1
        row = 1
        deltaX = 1.0 / 6.0
        deltaY = 1.0 / 4.0

        for idx, operator in enumerate(mathematics):
            imager[idx].SetViewport((column - 1) * deltaX, (row - 1) * deltaY, column * deltaX, row * deltaY)
            column += 1
            if column > 6:
                column = 1
                row += 1

        # Make the last operator finish the row
        vp = imager[len(mathematics) - 1].GetViewport()
        imager[len(mathematics) - 1].SetViewport(vp[0], vp[1], 1, 1)

        renWin.SetSize(600, 300)

        # render and interact with data

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

        img_file = "TestAllMathematics.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Example #19
0
    def testAllLogic(self):

        # append multiple displaced spheres into an RGB image.


        # Image pipeline

        renWin = vtk.vtkRenderWindow()

        logics = ["And", "Or", "Xor", "Nand", "Nor", "Not"]
        types = ["Float", "Double", "UnsignedInt", "UnsignedLong", "UnsignedShort", "UnsignedChar"]

        sphere1 = list()
        sphere2 = list()
        logic = list()
        mapper = list()
        actor = list()
        imager = list()

        for idx, operator in enumerate(logics):
            ScalarType = types[idx]

            sphere1.append(vtk.vtkImageEllipsoidSource())
            sphere1[idx].SetCenter(95, 100, 0)
            sphere1[idx].SetRadius(70, 70, 70)
            eval('sphere1[idx].SetOutputScalarTypeTo' + ScalarType + '()')
            sphere1[idx].Update()

            sphere2.append(vtk.vtkImageEllipsoidSource())
            sphere2[idx].SetCenter(161, 100, 0)
            sphere2[idx].SetRadius(70, 70, 70)
            eval('sphere2[idx].SetOutputScalarTypeTo' + ScalarType + '()')
            sphere2[idx].Update()

            logic.append(vtk.vtkImageLogic())
            logic[idx].SetInput1Data(sphere1[idx].GetOutput())
            if operator != "Not":
                logic[idx].SetInput2Data(sphere2[idx].GetOutput())

            logic[idx].SetOutputTrueValue(150)
            eval('logic[idx].SetOperationTo' + operator + '()')

            mapper.append(vtk.vtkImageMapper())
            mapper[idx].SetInputConnection(logic[idx].GetOutputPort())
            mapper[idx].SetColorWindow(255)
            mapper[idx].SetColorLevel(127.5)

            actor.append(vtk.vtkActor2D())
            actor[idx].SetMapper(mapper[idx])

            imager.append(vtk.vtkRenderer())
            imager[idx].AddActor2D(actor[idx])

            renWin.AddRenderer(imager[idx])



        imager[0].SetViewport(0, .5, .33, 1)
        imager[1].SetViewport(.33, .5, .66, 1)
        imager[2].SetViewport(.66, .5, 1, 1)
        imager[3].SetViewport(0, 0, .33, .5)
        imager[4].SetViewport(.33, 0, .66, .5)
        imager[5].SetViewport(.66, 0, 1, .5)

        renWin.SetSize(768, 512)

        # render and interact with data

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

        img_file = "TestAllLogic.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()