def computeImageHessian(
        image=None,
        image_filename=None,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeImageHessian ***")

    image = myVTK.initImage(image, image_filename, verbose-1)

    image_dimensionality = myVTK.computeImageDimensionality(
        image=image,
        verbose=verbose-1)

    image_gradient = vtk.vtkImageGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        image_gradient.SetInputData(image)
    else:
        image_gradient.SetInput(image)
    image_gradient.SetDimensionality(image_dimensionality)
    image_gradient.Update()
    image_w_gradient = image_gradient.GetOutput()

    image_append_components = vtk.vtkImageAppendComponents()
    for k_dim in xrange(image_dimensionality):
        image_extract_components = vtk.vtkImageExtractComponents()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_extract_components.SetInputData(image_w_gradient)
        else:
            image_extract_components.SetInput(image_w_gradient)
        image_extract_components.SetComponents(k_dim)
        image_extract_components.Update()
        image_w_gradient_component = image_extract_components.GetOutput()

        image_gradient = vtk.vtkImageGradient()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_gradient.SetInputData(image_w_gradient_component)
        else:
            image_gradient.SetInput(image_w_gradient_component)
        image_gradient.SetDimensionality(image_dimensionality)
        image_gradient.Update()
        image_w_hessian_component = image_gradient.GetOutput()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_append_components.AddInputData(image_w_hessian_component)
        else:
            image_append_components.AddInput(image_w_hessian_component)

    image_append_components.Update()
    image_w_hessian = image_append_components.GetOutput()

    name = image.GetPointData().GetScalars().GetName()
    image.GetPointData().AddArray(image_w_gradient.GetPointData().GetArray(name+"Gradient"))
    image.GetPointData().AddArray(image_w_hessian.GetPointData().GetArray(name+"GradientGradient"))
    image.GetPointData().SetActiveScalars(name+"GradientGradient")

    return image
Ejemplo n.º 2
0
def computeImageHessian(image=None, image_filename=None, verbose=0):

    myVTK.myPrint(verbose, "*** computeImageHessian ***")

    image = myVTK.initImage(image, image_filename, verbose - 1)

    image_dimensionality = myVTK.computeImageDimensionality(image=image,
                                                            verbose=verbose -
                                                            1)

    image_gradient = vtk.vtkImageGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        image_gradient.SetInputData(image)
    else:
        image_gradient.SetInput(image)
    image_gradient.SetDimensionality(image_dimensionality)
    image_gradient.Update()
    image_w_gradient = image_gradient.GetOutput()

    image_append_components = vtk.vtkImageAppendComponents()
    for k_dim in xrange(image_dimensionality):
        image_extract_components = vtk.vtkImageExtractComponents()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_extract_components.SetInputData(image_w_gradient)
        else:
            image_extract_components.SetInput(image_w_gradient)
        image_extract_components.SetComponents(k_dim)
        image_extract_components.Update()
        image_w_gradient_component = image_extract_components.GetOutput()

        image_gradient = vtk.vtkImageGradient()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_gradient.SetInputData(image_w_gradient_component)
        else:
            image_gradient.SetInput(image_w_gradient_component)
        image_gradient.SetDimensionality(image_dimensionality)
        image_gradient.Update()
        image_w_hessian_component = image_gradient.GetOutput()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_append_components.AddInputData(image_w_hessian_component)
        else:
            image_append_components.AddInput(image_w_hessian_component)

    image_append_components.Update()
    image_w_hessian = image_append_components.GetOutput()

    name = image.GetPointData().GetScalars().GetName()
    image.GetPointData().AddArray(
        image_w_gradient.GetPointData().GetArray(name + "Gradient"))
    image.GetPointData().AddArray(
        image_w_hessian.GetPointData().GetArray(name + "GradientGradient"))
    image.GetPointData().SetActiveScalars(name + "GradientGradient")

    return image
def computeImageGradient(
        image=None,
        image_filename=None,
        image_dimensionality=None,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeImageGradient ***")

    image = myVTK.initImage(image, image_filename, verbose-1)

    if (image_dimensionality is None):
        image_dimensionality = myVTK.computeImageDimensionality(
            image=image,
            verbose=verbose-1)

    image_gradient = vtk.vtkImageGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        image_gradient.SetInputData(image)
    else:
        image_gradient.SetInput(image)
    image_gradient.SetDimensionality(image_dimensionality)
    image_gradient.Update()
    image_w_grad = image_gradient.GetOutput()

    return image_w_grad
Ejemplo n.º 4
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageGradient(), 'Processing.',
         ('vtkImageData',), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 5
0
def gradient2D(image):
    gradient = vtk.vtkImageGradient()
    gradient.SetInput(image)
    gradient.SetDimensionality(2)
    gradient.HandleBoundariesOn()
    gradient.Update()
    return gradient.GetOutput()
Ejemplo n.º 6
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self,
         module_manager,
         vtk.vtkImageGradient(),
         "Processing.",
         ("vtkImageData",),
         ("vtkImageData",),
         replaceDoc=True,
         inputFunctions=None,
         outputFunctions=None,
     )
def addImageGradient(image, image_dimensionality=None, verbose=0):

    mypy.my_print(verbose, "*** addImageGradient ***")

    if (image_dimensionality is None):
        image_dimensionality = myvtk.getImageDimensionality(image=image,
                                                            verbose=verbose -
                                                            1)

    image_gradient = vtk.vtkImageGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        image_gradient.SetInputData(image)
    else:
        image_gradient.SetInput(image)
    image_gradient.SetDimensionality(image_dimensionality)
    image_gradient.Update()
    image_w_grad = image_gradient.GetOutput()

    name = image.GetPointData().GetScalars().GetName()
    image.GetPointData().AddArray(
        image_w_gradient.GetPointData().GetArray(name + "Gradient"))
    image.GetPointData().SetActiveScalars(name + "Gradient")
Ejemplo n.º 8
0
def addImageGradient(
        image,
        image_dimensionality=None,
        verbose=0):

    mypy.my_print(verbose, "*** addImageGradient ***")

    if (image_dimensionality is None):
        image_dimensionality = myvtk.getImageDimensionality(
            image=image,
            verbose=verbose-1)

    image_gradient = vtk.vtkImageGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        image_gradient.SetInputData(image)
    else:
        image_gradient.SetInput(image)
    image_gradient.SetDimensionality(image_dimensionality)
    image_gradient.Update()
    image_w_grad = image_gradient.GetOutput()

    name = image.GetPointData().GetScalars().GetName()
    image.GetPointData().AddArray(image_w_gradient.GetPointData().GetArray(name+"Gradient"))
    image.GetPointData().SetActiveScalars(name+"Gradient")
Ejemplo n.º 9
0
def main():
    fileName = get_program_parameters()
    colors = vtk.vtkNamedColors()

    # Read the CT data of the human head.
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(fileName)
    reader.Update()

    cast = vtk.vtkImageCast()
    cast.SetInputConnection(reader.GetOutputPort())
    cast.SetOutputScalarTypeToFloat()

    # Magnify the image.
    magnify = vtk.vtkImageMagnify()
    magnify.SetInputConnection(cast.GetOutputPort())
    magnify.SetMagnificationFactors(2, 2, 1)
    magnify.InterpolateOn()

    # Smooth the data.
    # Remove high frequency artifacts due to linear interpolation.
    smooth = vtk.vtkImageGaussianSmooth()
    smooth.SetInputConnection(magnify.GetOutputPort())
    smooth.SetDimensionality(2)
    smooth.SetStandardDeviations(1.5, 1.5, 0.0)
    smooth.SetRadiusFactors(2.01, 2.01, 0.0)

    # Compute the 2D gradient.
    gradient = vtk.vtkImageGradient()
    gradient.SetInputConnection(smooth.GetOutputPort())
    gradient.SetDimensionality(2)

    # Convert the data to polar coordinates.
    # The image magnitude is mapped into saturation value,
    # whilst the gradient direction is mapped into hue value.
    polar = vtk.vtkImageEuclideanToPolar()
    polar.SetInputConnection(gradient.GetOutputPort())
    polar.SetThetaMaximum(255.0)

    # Add a third component to the data.
    # This is needed since the gradient filter only generates two components,
    #  and we need three components to represent color.
    pad = vtk.vtkImageConstantPad()
    pad.SetInputConnection(polar.GetOutputPort())
    pad.SetOutputNumberOfScalarComponents(3)
    pad.SetConstant(200.0)

    # At this point we have Hue, Value, Saturation.
    # Permute components so saturation will be constant.
    # Re-arrange components into HSV order.
    permute = vtk.vtkImageExtractComponents()
    permute.SetInputConnection(pad.GetOutputPort())
    permute.SetComponents(0, 2, 1)

    # Convert back into RGB values.
    rgb = vtk.vtkImageHSVToRGB()
    rgb.SetInputConnection(permute.GetOutputPort())
    rgb.SetMaximum(255.0)

    # Set up a viewer for the image.
    # Note that vtkImageViewer and vtkImageViewer2 are convenience wrappers around
    # vtkActor2D, vtkImageMapper, vtkRenderer, and vtkRenderWindow.
    # So all that needs to be supplied is the interactor.
    viewer = vtk.vtkImageViewer()
    viewer.SetInputConnection(rgb.GetOutputPort())
    viewer.SetZSlice(22)
    viewer.SetColorWindow(255.0)
    viewer.SetColorLevel(127.0)
    viewer.GetRenderWindow().SetSize(512, 512)
    viewer.GetRenderer().SetBackground(colors.GetColor3d("Silver"))

    # Create the RenderWindowInteractor.
    iren = vtk.vtkRenderWindowInteractor()
    viewer.SetupInteractor(iren)
    viewer.Render()

    iren.Initialize()
    iren.Start()
Ejemplo n.º 10
0
def main():
    colors = vtk.vtkNamedColors()

    # The Wavelet Source is nice for generating a test vtkImageData set
    rt = vtk.vtkRTAnalyticSource()
    rt.SetWholeExtent(-2, 2, -2, 2, 0, 0)

    # Take the gradient of the only scalar 'RTData' to get a vector attribute
    grad = vtk.vtkImageGradient()
    grad.SetDimensionality(3)
    grad.SetInputConnection(rt.GetOutputPort())

    # Elevation just to generate another scalar attribute that varies nicely over the data range
    elev = vtk.vtkElevationFilter()
    # Elevation values will range from 0 to 1 between the Low and High Points
    elev.SetLowPoint(-2, -2, 0)
    elev.SetHighPoint(2, 2, 0)
    elev.SetInputConnection(grad.GetOutputPort())

    # Create simple PolyData for glyph table
    cs = vtk.vtkCubeSource()
    cs.SetXLength(0.5)
    cs.SetYLength(1)
    cs.SetZLength(2)
    ss = vtk.vtkSphereSource()
    ss.SetRadius(0.25)
    cs2 = vtk.vtkConeSource()
    cs2.SetRadius(0.25)
    cs2.SetHeight(0.5)

    # Set up the glyph filter
    glyph = vtk.vtkGlyph3D()
    glyph.SetInputConnection(elev.GetOutputPort())

    # Here is where we build the glyph table
    # that will be indexed into according to the IndexMode
    glyph.SetSourceConnection(0, cs.GetOutputPort())
    glyph.SetSourceConnection(1, ss.GetOutputPort())
    glyph.SetSourceConnection(2, cs2.GetOutputPort())

    glyph.ScalingOn()
    glyph.SetScaleModeToScaleByScalar()
    glyph.SetVectorModeToUseVector()
    glyph.OrientOn()
    glyph.SetScaleFactor(1)  # Overall scaling factor
    glyph.SetRange(0, 1)  # Default is (0,1)

    # Tell it to index into the glyph table according to scalars
    glyph.SetIndexModeToScalar()

    # Tell glyph which attribute arrays to use for what
    glyph.SetInputArrayToProcess(0, 0, 0, 0, 'Elevation')  # scalars
    glyph.SetInputArrayToProcess(1, 0, 0, 0, 'RTDataGradient')  # vectors

    coloring_by = 'Elevation'
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())
    mapper.SetScalarModeToUsePointFieldData()
    mapper.SetColorModeToMapScalars()
    mapper.ScalarVisibilityOn()

    # GetRange() call doesn't work because attributes weren't copied to glyphs
    # as they should have been...
    # mapper.SetScalarRange(glyph.GetOutputDataObject(0).GetPointData().GetArray(coloring_by).GetRange())

    mapper.SelectColorArray(coloring_by)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    istyle = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(istyle)
    iren.SetRenderWindow(renWin)
    ren.ResetCamera()
    renWin.Render()
    iren.Start()
Ejemplo n.º 11
0
    def operation(self, operation, volume2=None):
        """
        Perform operations with ``Volume`` objects.

        `volume2` can be a constant value.

        Possible operations are: ``+``, ``-``, ``/``, ``1/x``, ``sin``, ``cos``, ``exp``, ``log``,
        ``abs``, ``**2``, ``sqrt``, ``min``, ``max``, ``atan``, ``atan2``, ``median``,
        ``mag``, ``dot``, ``gradient``, ``divergence``, ``laplacian``.

        |volumeOperations| |volumeOperations.py|_
        """
        op = operation.lower()
        image1 = self._data

        if op in ["median"]:
            mf = vtk.vtkImageMedian3D()
            mf.SetInputData(image1)
            mf.Update()
            return Volume(mf.GetOutput())
        elif op in ["mag"]:
            mf = vtk.vtkImageMagnitude()
            mf.SetInputData(image1)
            mf.Update()
            return Volume(mf.GetOutput())
        elif op in ["dot", "dotproduct"]:
            mf = vtk.vtkImageDotProduct()
            mf.SetInput1Data(image1)
            mf.SetInput2Data(volume2._data)
            mf.Update()
            return Volume(mf.GetOutput())
        elif op in ["grad", "gradient"]:
            mf = vtk.vtkImageGradient()
            mf.SetDimensionality(3)
            mf.SetInputData(image1)
            mf.Update()
            return Volume(mf.GetOutput())
        elif op in ["div", "divergence"]:
            mf = vtk.vtkImageDivergence()
            mf.SetInputData(image1)
            mf.Update()
            return Volume(mf.GetOutput())
        elif op in ["laplacian"]:
            mf = vtk.vtkImageLaplacian()
            mf.SetDimensionality(3)
            mf.SetInputData(image1)
            mf.Update()
            return Volume(mf.GetOutput())

        mat = vtk.vtkImageMathematics()
        mat.SetInput1Data(image1)

        K = None

        if isinstance(volume2, (int, float)):
            K = volume2
            mat.SetConstantK(K)
            mat.SetConstantC(K)
        elif volume2 is not None:  # assume image2 is a constant value
            mat.SetInput2Data(volume2._data)

        if op in ["+", "add", "plus"]:
            if K:
                mat.SetOperationToAddConstant()
            else:
                mat.SetOperationToAdd()

        elif op in ["-", "subtract", "minus"]:
            if K:
                mat.SetConstantC(-K)
                mat.SetOperationToAddConstant()
            else:
                mat.SetOperationToSubtract()

        elif op in ["*", "multiply", "times"]:
            if K:
                mat.SetOperationToMultiplyByK()
            else:
                mat.SetOperationToMultiply()

        elif op in ["/", "divide"]:
            if K:
                mat.SetConstantK(1.0 / K)
                mat.SetOperationToMultiplyByK()
            else:
                mat.SetOperationToDivide()

        elif op in ["1/x", "invert"]:
            mat.SetOperationToInvert()
        elif op in ["sin"]:
            mat.SetOperationToSin()
        elif op in ["cos"]:
            mat.SetOperationToCos()
        elif op in ["exp"]:
            mat.SetOperationToExp()
        elif op in ["log"]:
            mat.SetOperationToLog()
        elif op in ["abs"]:
            mat.SetOperationToAbsoluteValue()
        elif op in ["**2", "square"]:
            mat.SetOperationToSquare()
        elif op in ["sqrt", "sqr"]:
            mat.SetOperationToSquareRoot()
        elif op in ["min"]:
            mat.SetOperationToMin()
        elif op in ["max"]:
            mat.SetOperationToMax()
        elif op in ["atan"]:
            mat.SetOperationToATAN()
        elif op in ["atan2"]:
            mat.SetOperationToATAN2()
        else:
            colors.printc("\times Error in volumeOperation: unknown operation",
                          operation,
                          c='r')
            raise RuntimeError()
        mat.Update()
        return self._update(mat.GetOutput())
#
intRange = (-100, 900)
max_u_short = 1000
for z in range(dims[2]):
    for y in range(dims[1]):
        for x in range(dims[0]):
            scalardata = img1_data[x][y][z]
            if scalardata < intRange[0]:
                scalardata = intRange[0]
            if scalardata > intRange[1]:
                scalardata = intRange[1]
            scalardata = max_u_short * np.float(
                scalardata - intRange[0]) / np.float(intRange[1] - intRange[0])
            image.SetScalarComponentFromFloat(x, y, z, 0, scalardata)

gradientFilter = vtk.vtkImageGradient()  #生成梯度图
gradientFilter.SetInputData(image)
gradientFilter.SetDimensionality(3)
gradientFilter.Update()

#################################################
magnitude = vtk.vtkImageMagnitude()  #生成梯度模值图
magnitude.SetInputConnection(gradientFilter.GetOutputPort())
magnitude.Update()
imageCast = vtk.vtkImageCast()
imageCast.SetInputConnection(magnitude.GetOutputPort())
imageCast.SetOutputScalarTypeToUnsignedShort()
imageCast.Update()
magimage = imageCast.GetOutput()

# Create transfer mapping scalar value to opacity
Ejemplo n.º 13
0
def main():
    colors = vtk.vtkNamedColors()

    # Generate an image data set with multiple attribute arrays to probe and view
    # We will glyph these points with cones and scale/orient/color them with the
    # various attributes

    # The Wavelet Source is nice for generating a test vtkImageData set
    rt = vtk.vtkRTAnalyticSource()
    rt.SetWholeExtent(-2, 2, -2, 2, 0, 0)

    # Take the gradient of the only scalar 'RTData' to get a vector attribute
    grad = vtk.vtkImageGradient()
    grad.SetDimensionality(3)
    grad.SetInputConnection(rt.GetOutputPort())

    # Elevation just to generate another scalar attribute that varies nicely over the data range
    elev = vtk.vtkElevationFilter()
    # Elevation values will range from 0 to 1 between the Low and High Points
    elev.SetLowPoint(-2, 0, 0)
    elev.SetHighPoint(2, 0, 0)
    elev.SetInputConnection(grad.GetOutputPort())

    # Generate the cone for the glyphs
    sph = vtk.vtkConeSource()
    sph.SetRadius(0.1)
    sph.SetHeight(0.5)

    # Set up the glyph filter
    glyph = vtk.vtkGlyph3D()
    glyph.SetInputConnection(elev.GetOutputPort())
    glyph.SetSourceConnection(sph.GetOutputPort())
    glyph.ScalingOn()
    glyph.SetScaleModeToScaleByScalar()
    glyph.SetVectorModeToUseVector()
    glyph.OrientOn()

    # Tell the filter to 'clamp' the scalar range
    glyph.ClampingOn()

    # Set the overall (multiplicative) scaling factor
    glyph.SetScaleFactor(1)

    # Set the Range to 'clamp' the data to
    #   -- see equations above for nonintuitive definition of 'clamping'
    # The fact that I'm setting the minimum value of the range below
    #   the minimum of my data (real min=0.0) with the equations above
    #   forces a minimum non-zero glyph size.

    glyph.SetRange(-0.5, 1)  # Change these values to see effect on cone sizes

    # Tell glyph which attribute arrays to use for what
    glyph.SetInputArrayToProcess(0, 0, 0, 0, 'Elevation')  # scalars
    glyph.SetInputArrayToProcess(1, 0, 0, 0, 'RTDataGradient')  # vectors
    # glyph.SetInputArrayToProcess(2,0,0,0,'nothing')		# normals
    glyph.SetInputArrayToProcess(3, 0, 0, 0, 'RTData')  # colors

    # Calling update because I'm going to use the scalar range to set the color map range
    glyph.Update()

    coloring_by = 'RTData'
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())
    mapper.SetScalarModeToUsePointFieldData()
    mapper.SetColorModeToMapScalars()
    mapper.ScalarVisibilityOn()
    mapper.SetScalarRange(
        glyph.GetOutputDataObject(0).GetPointData().GetArray(
            coloring_by).GetRange())
    mapper.SelectColorArray(coloring_by)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(colors.GetColor3d('MidnightBlue'))
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetWindowName('ClampGlyphSizes')

    iren = vtk.vtkRenderWindowInteractor()
    istyle = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(istyle)
    iren.SetRenderWindow(renWin)
    ren.ResetCamera()
    renWin.Render()
    iren.Start()
Ejemplo n.º 14
0
tube.SetCapping(0)
tube.SetVaryRadius(0)
tube.SetRadius(0.6)
tube.SetRadiusFactor(10)

bondMapper = vtk.vtkPolyDataMapper()
bondMapper.SetInputConnection(tube.GetOutputPort())
bondMapper.SetImmediateModeRendering(1)
bondMapper.UseLookupTableScalarRangeOff()
bondMapper.SetScalarVisibility(1)
bondMapper.SetScalarModeToDefault()

bondActor = vtk.vtkActor()
bondActor.SetMapper(bondMapper)

grad = vtk.vtkImageGradient()
grad.SetDimensionality(3)
grad.SetInputData(potential_cation.GetGridOutput())

attrib = vtk.vtkAssignAttribute()
attrib.SetInputConnection(grad.GetOutputPort())
attrib.Assign(vtk.vtkDataSetAttributes.SCALARS,
              vtk.vtkDataSetAttributes.VECTORS,
              vtk.vtkAssignAttribute.POINT_DATA)

center = potential_cation.GetOutput().GetPoint(0)

seeds = vtk.vtkPointSource()
seeds.SetRadius(3.0)
seeds.SetCenter(center)
seeds.SetNumberOfPoints(150)
def main():
    # Generate an image data set with multiple attribute arrays to probe and view
    rt = vtk.vtkRTAnalyticSource()
    rt.SetWholeExtent(-3, 3, -3, 3, -3, 3)
    grad = vtk.vtkImageGradient()
    grad.SetDimensionality(3)
    grad.SetInputConnection(rt.GetOutputPort())
    brown = vtk.vtkBrownianPoints()
    brown.SetMinimumSpeed(0.5)
    brown.SetMaximumSpeed(1.0)
    brown.SetInputConnection(grad.GetOutputPort())
    elev = vtk.vtkElevationFilter()
    elev.SetLowPoint(-3, -3, -3)
    elev.SetHighPoint(3, 3, 3)
    elev.SetInputConnection(brown.GetOutputPort())

    # Updating here because I will need to probe scalar ranges before
    # the render window updates the pipeline
    elev.Update()

    # Set up parallel coordinates representation to be used in View
    rep = vtk.vtkParallelCoordinatesRepresentation()
    rep.SetInputConnection(elev.GetOutputPort())
    rep.SetInputArrayToProcess(0, 0, 0, 0, 'RTDataGradient')
    rep.SetInputArrayToProcess(1, 0, 0, 0, 'RTData')
    rep.SetInputArrayToProcess(2, 0, 0, 0, 'Elevation')
    rep.SetInputArrayToProcess(3, 0, 0, 0, 'BrownianVectors')
    rep.SetUseCurves(0)  # set to 1 to use smooth curves
    rep.SetLineOpacity(0.5)

    # Set up the Parallel Coordinates View and hook in representation
    view = vtk.vtkParallelCoordinatesView()
    view.SetRepresentation(rep)
    view.SetInspectMode(view.VTK_INSPECT_SELECT_DATA)
    view.SetBrushOperatorToReplace()
    view.SetBrushModeToLasso()

    # Create a annotation link to access selection in parallel coordinates view
    annotationLink = 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
    annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1)  # Point
    annotationLink.GetCurrentSelection().GetNode(0).SetContentType(
        4)  # Indices
    # Update before passing annotationLink to vtkExtractSelection
    annotationLink.Update()
    # Connect the annotation link to the parallel coordinates representation
    rep.SetAnnotationLink(annotationLink)

    # Extract portion of data corresponding to parallel coordinates selection
    extract = vtk.vtkExtractSelection()
    extract.SetInputConnection(0, elev.GetOutputPort())
    extract.SetInputConnection(1, annotationLink.GetOutputPort(2))

    def update_render_windows(obj, event):
        """
        Handle updating of RenderWindow since it's not a "View"
        and so not covered by vtkViewUpdater

        :param obj:
        :param event:
        :return:
        """
        # ren.ResetCamera()
        renWin.Render()

    # Set up callback to update 3d render window when selections are changed in
    # parallel coordinates view
    annotationLink.AddObserver("AnnotationChangedEvent", update_render_windows)

    def toggle_inspectors(obj, event):

        if view.GetInspectMode() == 0:
            view.SetInspectMode(1)
        else:
            view.SetInspectMode(0)

    # Set up callback to toggle between inspect modes (manip axes & select data)
    view.GetInteractor().AddObserver("UserEvent", toggle_inspectors)

    # 3D outline of image data bounds
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(elev.GetOutputPort())
    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())
    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)

    # Build the lookup table for the 3d data scalar colors (brown to white)
    lut = vtk.vtkLookupTable()
    lut.SetTableRange(0, 256)
    lut.SetHueRange(0.1, 0.1)
    lut.SetSaturationRange(1.0, 0.1)
    lut.SetValueRange(0.4, 1.0)
    lut.Build()

    # Set up the 3d rendering parameters
    # of the image data which is selected in parallel coordinates
    coloring_by = 'Elevation'
    dataMapper = vtk.vtkDataSetMapper()
    dataMapper.SetInputConnection(extract.GetOutputPort())
    dataMapper.SetScalarModeToUsePointFieldData()
    dataMapper.SetColorModeToMapScalars()
    data = elev.GetOutputDataObject(0).GetPointData()
    dataMapper.ScalarVisibilityOn()
    dataMapper.SetScalarRange(data.GetArray(coloring_by).GetRange())
    dataMapper.SetLookupTable(lut)
    dataMapper.SelectColorArray(coloring_by)
    dataActor = vtk.vtkActor()
    dataActor.SetMapper(dataMapper)
    dataActor.GetProperty().SetRepresentationToPoints()
    dataActor.GetProperty().SetPointSize(10)

    # Set up the 3d render window and add both actors
    ren = vtk.vtkRenderer()
    ren.AddActor(outlineActor)
    ren.AddActor(dataActor)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    ren.ResetCamera()
    renWin.Render()

    # Finalize parallel coordinates view and start interaction event loop
    view.GetRenderWindow().SetSize(600, 300)
    view.ResetCamera()
    view.Render()
    view.GetInteractor().Start()
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")
def main():
    colors = vtk.vtkNamedColors()

    # Generate an example image data set with multiple attribute arrays to probe
    # and view.
    # This is where you would put your reader instead of this rt->elev pipeline...
    rt = vtk.vtkRTAnalyticSource()
    rt.SetWholeExtent(-3, 3, -3, 3, -3, 3)
    grad = vtk.vtkImageGradient()
    grad.SetDimensionality(3)
    grad.SetInputConnection(rt.GetOutputPort())
    brown = vtk.vtkBrownianPoints()
    brown.SetMinimumSpeed(0.5)
    brown.SetMaximumSpeed(1.0)
    brown.SetInputConnection(grad.GetOutputPort())
    elev = vtk.vtkElevationFilter()
    elev.SetLowPoint(-3, -3, -3)
    elev.SetHighPoint(3, 3, 3)
    elev.SetInputConnection(brown.GetOutputPort())

    # Set up the parallel coordinates Representation to be used in the View
    rep = vtk.vtkParallelCoordinatesRepresentation()

    # Plug your reader in here for your own data
    rep.SetInputConnection(elev.GetOutputPort())

    # List all of the attribute arrays you want plotted in parallel coordinates
    rep.SetInputArrayToProcess(0, 0, 0, 0, 'RTDataGradient')
    rep.SetInputArrayToProcess(1, 0, 0, 0, 'RTData')
    rep.SetInputArrayToProcess(2, 0, 0, 0, 'Elevation')
    rep.SetInputArrayToProcess(3, 0, 0, 0, 'BrownianVectors')

    rep.SetUseCurves(0)  # set to 1 to use smooth curves
    rep.SetLineOpacity(0.5)
    rep.SetAxisColor(colors.GetColor3d('Gold'))
    rep.SetLineColor(colors.GetColor3d('MistyRose'))

    # Set up the Parallel Coordinates View and hook in the Representation
    view = vtk.vtkParallelCoordinatesView()
    view.SetRepresentation(rep)

    # Inspect Mode determines whether your interactions manipulate the axes or
    # select data
    # view.SetInspectMode(view.VTK_INSPECT_MANIPULATE_AXES)    # VTK_INSPECT_MANIPULATE_AXES = 0,
    view.SetInspectMode(
        view.VTK_INSPECT_SELECT_DATA)  # VTK_INSPECT_SELECT_DATA = 1

    # Brush Mode determines the type of interaction you perform to select data
    view.SetBrushModeToLasso()
    # view.SetBrushModeToAngle()
    # view.SetBrushModeToFunction()
    # view.SetBrushModeToAxisThreshold()  # not implemented yet (as of 21 Feb 2010)

    # Brush Operator determines how each new selection interaction changes
    # selected lines
    # view.SetBrushOperatorToAdd()
    # view.SetBrushOperatorToSubtract()
    # view.SetBrushOperatorToIntersect()
    view.SetBrushOperatorToReplace()

    def ToggleInspectors(obj, event):
        # Define the callback routine which toggles between 'Inspect Modes'
        if view.GetInspectMode() == 0:
            view.SetInspectMode(1)
        else:
            view.SetInspectMode(0)

    # Hook up the callback to toggle between inspect modes
    # (manip axes & select data)
    view.GetInteractor().AddObserver('UserEvent', ToggleInspectors)

    # Set up render window
    view.GetRenderWindow().SetSize(600, 300)
    view.GetRenderWindow().SetWindowName('ParallelCoordinatesView')
    view.GetRenderer().GradientBackgroundOn()
    view.GetRenderer().SetBackground2(colors.GetColor3d('DarkBlue'))
    view.GetRenderer().SetBackground(colors.GetColor3d('MidnightBlue'))
    view.ResetCamera()
    view.Render()

    # Start interaction event loop
    view.GetInteractor().Start()
Ejemplo n.º 18
0
# load in the texture map
#
imageIn = vtk.vtkPNMReader()
imageIn.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/earth.ppm")
il = vtk.vtkImageLuminance()
il.SetInputConnection(imageIn.GetOutputPort())
ic = vtk.vtkImageCast()
ic.SetOutputScalarTypeToFloat()
ic.SetInputConnection(il.GetOutputPort())
# smooth the image
gs = vtk.vtkImageGaussianSmooth()
gs.SetInputConnection(ic.GetOutputPort())
gs.SetDimensionality(2)
gs.SetRadiusFactors(1, 1, 0)
# gradient the image
imgGradient = vtk.vtkImageGradient()
imgGradient.SetInputConnection(gs.GetOutputPort())
imgGradient.SetDimensionality(2)
imgMagnitude = vtk.vtkImageMagnitude()
imgMagnitude.SetInputConnection(imgGradient.GetOutputPort())
imgMagnitude.Update()
# non maximum suppression
nonMax = vtk.vtkImageNonMaximumSuppression()
nonMax.SetMagnitudeInputData(imgMagnitude.GetOutput())
nonMax.SetVectorInputData(imgGradient.GetOutput())
nonMax.SetDimensionality(2)
pad = vtk.vtkImageConstantPad()
pad.SetInputConnection(imgGradient.GetOutputPort())
pad.SetOutputNumberOfScalarComponents(3)
pad.SetConstant(0)
pad.Update()
Ejemplo n.º 19
0
tube.SetNumberOfSides(16)
tube.SetCapping(0)
tube.SetVaryRadius(0)
tube.SetRadius(0.6)
tube.SetRadiusFactor(10)

bondMapper = vtk.vtkPolyDataMapper()
bondMapper.SetInputConnection(tube.GetOutputPort())
bondMapper.UseLookupTableScalarRangeOff()
bondMapper.SetScalarVisibility(1)
bondMapper.SetScalarModeToDefault()

bondActor = vtk.vtkActor()
bondActor.SetMapper(bondMapper)

denGrad = vtk.vtkImageGradient()
denGrad.SetDimensionality(3)
denGrad.SetInputData(density.GetGridOutput())
denGrad.Update()
denGradOut = denGrad.GetOutput()
# Get rid of the original data
denGradOut.GetPointData().RemoveArray(1)

potGrad = vtk.vtkImageGradient()
potGrad.SetDimensionality(3)
potGrad.SetInputData(potential.GetGridOutput())
potGrad.Update()
potGradOut = potGrad.GetOutput()
# Get rid of the original data
potGradOut.GetPointData().RemoveArray(1)
    vtkImageMask.SetInValue(1.0)
    vtkImageMask.SetOutputScalarTypeToDouble()
    try:
        #default look for a user defined image mask
        maskFileName = "%s/SNRuncert.%04d.vtk" % (
            FileNameTemplate[:FileNameTemplate.rfind("/")], timeID)
        vtkMaskReader = vtk.vtkDataSetReader()
        vtkMaskReader.SetFileName(maskFileName)
        vtkMaskReader.Update()
        # set threshold
        vtkImageMask.ThresholdByLower(100.0)
        vtkImageMask.SetInput(vtkMaskReader.GetOutput())
    except:  # if nothing available threshold the phase image
        # take gradient
        vtkPhaseData = ConvertNumpyVTKImage(phase_curr)
        vtkGradientImage = vtk.vtkImageGradient()
        vtkGradientImage.SetInput(vtkPhaseData)
        vtkGradientImage.Update()

        # take magnitude of gradient
        vtkImageNorm = vtk.vtkImageMagnitude()
        vtkImageNorm.SetInput(vtkGradientImage.GetOutput())
        vtkImageNorm.Update()
        # set threshold
        vtkImageMask.ThresholdByLower(100.0 * tmap_factor * 2.0 * numpy.pi /
                                      4095.)
        vtkImageMask.SetInput(vtkImageNorm.GetOutput())
    vtkImageMask.Update()
    # check output
    vtkWriter = vtk.vtkXMLImageDataWriter()
    vtkWriter.SetFileName("threshold.%04d.vti" % timeID)
Ejemplo n.º 21
0
def imageOperation(image1, operation='+', image2=None):
    '''
    Perform operations with vtkImageData objects. Image2 can contain a constant value.
    Possible operations are: +, -, /, 1/x, sin, cos, exp, log, abs, **2, sqrt, min, 
      max, atan, atan2, median, mag, dot, gradient, divergence, laplacian.

    [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/volumetric/imageOperations.py)

    ![gradient](https://user-images.githubusercontent.com/32848391/48198940-d1ba2800-e35a-11e8-96a7-ffbff797f165.jpg)
    '''
    op = operation.lower()

    if op in ['median']:
        mf = vtk.vtkImageMedian3D()
        mf.SetInputData(image1)
        mf.Update()
        return mf.GetOutput()
    elif op in ['mag']:
        mf = vtk.vtkImageMagnitude()
        mf.SetInputData(image1)
        mf.Update()
        return mf.GetOutput()
    elif op in ['dot', 'dotproduct']:
        mf = vtk.vtkImageDotProduct()
        mf.SetInput1Data(image1)
        mf.SetInput2Data(image2)
        mf.Update()
        return mf.GetOutput()
    elif op in ['grad', 'gradient']:
        mf = vtk.vtkImageGradient()
        mf.SetDimensionality(3)
        mf.SetInputData(image1)
        mf.Update()
        return mf.GetOutput()
    elif op in ['div', 'divergence']:
        mf = vtk.vtkImageDivergence()
        mf.SetInputData(image1)
        mf.Update()
        return mf.GetOutput()
    elif op in ['laplacian']:
        mf = vtk.vtkImageLaplacian()
        mf.SetDimensionality(3)
        mf.SetInputData(image1)
        mf.Update()
        return mf.GetOutput()

    mat = vtk.vtkImageMathematics()
    mat.SetInput1Data(image1)
    K = None
    if image2:
        if isinstance(image2, vtk.vtkImageData):
            mat.SetInput2Data(image2)
        else:  # assume image2 is a constant value
            K = image2
            mat.SetConstantK(K)
            mat.SetConstantC(K)

    if op in ['+', 'add', 'plus']:
        if K:
            mat.SetOperationToAddConstant()
        else:
            mat.SetOperationToAdd()

    elif op in ['-', 'subtract', 'minus']:
        if K:
            mat.SetConstantC(-K)
            mat.SetOperationToAddConstant()
        else:
            mat.SetOperationToSubtract()

    elif op in ['*', 'multiply', 'times']:
        if K:
            mat.SetOperationToMultiplyByK()
        else:
            mat.SetOperationToMultiply()

    elif op in ['/', 'divide']:
        if K:
            mat.SetConstantK(1.0/K)
            mat.SetOperationToMultiplyByK()
        else:
            mat.SetOperationToDivide()

    elif op in ['1/x', 'invert']:
        mat.SetOperationToInvert()
    elif op in ['sin']:
        mat.SetOperationToSin()
    elif op in ['cos']:
        mat.SetOperationToCos()
    elif op in ['exp']:
        mat.SetOperationToExp()
    elif op in ['log']:
        mat.SetOperationToLog()
    elif op in ['abs']:
        mat.SetOperationToAbsoluteValue()
    elif op in ['**2', 'square']:
        mat.SetOperationToSquare()
    elif op in ['sqrt', 'sqr']:
        mat.SetOperationToSquareRoot()
    elif op in ['min']:
        mat.SetOperationToMin()
    elif op in ['max']:
        mat.SetOperationToMax()
    elif op in ['atan']:
        mat.SetOperationToATAN()
    elif op in ['atan2']:
        mat.SetOperationToATAN2()
    else:
        vc.printc('Error in imageOperation: unknown operation', operation, c=1)
        exit()
    mat.Update()
    return mat.GetOutput()
Ejemplo n.º 22
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# This Script test the euclidean to polar by coverting 2D vectors
# from a gradient into polar, which is converted into HSV, and then to RGB.
# Image pipeline
gauss = vtk.vtkImageGaussianSource()
gauss.SetWholeExtent(0,255,0,255,0,44)
gauss.SetCenter(127,127,22)
gauss.SetStandardDeviation(50.0)
gauss.SetMaximum(10000.0)
gradient = vtk.vtkImageGradient()
gradient.SetInputConnection(gauss.GetOutputPort())
gradient.SetDimensionality(2)
polar = vtk.vtkImageEuclideanToPolar()
polar.SetInputConnection(gradient.GetOutputPort())
polar.SetThetaMaximum(255)
viewer = vtk.vtkImageViewer()
#viewer DebugOn
viewer.SetInputConnection(polar.GetOutputPort())
viewer.SetZSlice(22)
viewer.SetColorWindow(255)
viewer.SetColorLevel(127.5)
#make interface
viewer.Render()
# --- end of script --
 vtkImageMask.SetInValue(1.0)
 vtkImageMask.SetOutputScalarTypeToDouble()
 try:
   #default look for a user defined image mask
   maskFileName = "%s/SNRuncert.%04d.vtk" %  (
                 FileNameTemplate[:FileNameTemplate.rfind("/")],timeID)
   vtkMaskReader = vtk.vtkDataSetReader() 
   vtkMaskReader.SetFileName( maskFileName ) 
   vtkMaskReader.Update() 
   # set threshold
   vtkImageMask.ThresholdByLower( 100.0)
   vtkImageMask.SetInput(vtkMaskReader.GetOutput())
 except: # if nothing available threshold the phase image
   # take gradient
   vtkPhaseData = ConvertNumpyVTKImage( phase_curr )
   vtkGradientImage = vtk.vtkImageGradient() 
   vtkGradientImage.SetInput(vtkPhaseData) 
   vtkGradientImage.Update() 
   
   # take magnitude of gradient
   vtkImageNorm = vtk.vtkImageMagnitude() 
   vtkImageNorm.SetInput(vtkGradientImage.GetOutput())
   vtkImageNorm.Update() 
   # set threshold
   vtkImageMask.ThresholdByLower( 100.0* tmap_factor * 2.0*numpy.pi/4095.)
   vtkImageMask.SetInput(vtkImageNorm.GetOutput())
 vtkImageMask.Update( )
 # check output
 vtkWriter = vtk.vtkXMLImageDataWriter()
 vtkWriter.SetFileName("threshold.%04d.vti" % timeID )
 vtkWriter.SetInput( vtkImageMask.GetOutput() )