Beispiel #1
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkImageLaplacian(),
                                       'Processing.', ('vtkImageData', ),
                                       ('vtkImageData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self,
         module_manager,
         vtk.vtkImageLaplacian(),
         "Processing.",
         ("vtkImageData",),
         ("vtkImageData",),
         replaceDoc=True,
         inputFunctions=None,
         outputFunctions=None,
     )
Beispiel #3
0
    def performLaplaceOfGaussian(self, image):
        gaussian = vtk.vtkImageGaussianSmooth()
        gaussian.SetInputData(image)
        gaussian.Update()

        laplacian = vtk.vtkImageLaplacian()
        laplacian.SetInputData(gaussian.GetOutput())
        laplacian.Update()

        outImageData = vtk.vtkImageData()
        outImageData.DeepCopy(laplacian.GetOutput())

        return outImageData
  def performLaplaceOfGaussian(self, image):
      gaussian = vtk.vtkImageGaussianSmooth()
      gaussian.SetInputData(image)
      gaussian.Update()

      laplacian = vtk.vtkImageLaplacian()
      laplacian.SetInputData(gaussian.GetOutput())
      laplacian.Update()

      outImageData = vtk.vtkImageData()
      outImageData.DeepCopy(laplacian.GetOutput())

      return outImageData
Beispiel #5
0
    def ImageLaplacianFilter(self, image):
        """Returns the image Laplacian"""
        image.SetReleaseDataFlag(1)

        _filter = vtk.vtkImageLaplacian()

        # we need this here because there are two paths into this routine
        if isinstance(image, MVImage.MVImage):
            real_image = image.GetRealImage()
        else:
            real_image = image

        _filter.SetInput(real_image)
        _filter.SetProgressText("Calculating Image Laplacian...")
        _filter.AddObserver('ProgressEvent', self.HandleVTKProgressEvent)
        logging.info("Image Laplacian applied")

        _filter.Update()

        return MVImage.MVImage(_filter.GetOutputPort(), input=image)
    def ImageLaplacianFilter(self, image):
        """Returns the image Laplacian"""
        image.SetReleaseDataFlag(1)

        _filter = vtk.vtkImageLaplacian()

        # we need this here because there are two paths into this routine
        if isinstance(image, MVImage.MVImage):
            real_image = image.GetRealImage()
        else:
            real_image = image

        _filter.SetInput(real_image)
        _filter.SetProgressText("Calculating Image Laplacian...")
        _filter.AddObserver('ProgressEvent', self.HandleVTKProgressEvent)
        logging.info("Image Laplacian applied")

        _filter.Update()

        return MVImage.MVImage(_filter.GetOutputPort(), input=image)
Beispiel #7
0
    def run(self, inputVolume, outputVolume):

        if not self.isValidInputOutputData(inputVolume, outputVolume):
            return False

        logging.info('Processing started')

        laplacian = vtk.vtkImageLaplacian()
        laplacian.SetInputData(inputVolume.GetImageData())
        laplacian.SetDimensionality(3)
        laplacian.Update()

        # Copy image origin, spacing, directions from input
        ijkToRAS = vtk.vtkMatrix4x4()
        inputVolume.GetIJKToRASMatrix(ijkToRAS)
        outputVolume.SetIJKToRASMatrix(ijkToRAS)
        outputVolume.SetAndObserveImageData(laplacian.GetOutput())

        logging.info('Processing completed')

        return True
Beispiel #8
0
    def enhance(self):
        """
        Enhance a b&w picture using the laplacian, enhancing high-freq edges.

        Example:

            .. code-block:: python

                import vedo
                p = vedo.Picture(vedo.dataurl+'images/dog.jpg').bw()
                vedo.show(p, p.clone().enhance(), N=2, mode='image')
        """
        img = self._data
        scalarRange = img.GetPointData().GetScalars().GetRange()

        cast = vtk.vtkImageCast()
        cast.SetInputData(img)
        cast.SetOutputScalarTypeToDouble()
        cast.Update()

        laplacian = vtk.vtkImageLaplacian()
        laplacian.SetInputData(cast.GetOutput())
        laplacian.SetDimensionality(2)
        laplacian.Update()

        subtr = vtk.vtkImageMathematics()
        subtr.SetInputData(0, cast.GetOutput())
        subtr.SetInputData(1, laplacian.GetOutput())
        subtr.SetOperationToSubtract()
        subtr.Update()

        colorWindow = scalarRange[1] - scalarRange[0]
        colorLevel = colorWindow / 2
        originalColor = vtk.vtkImageMapToWindowLevelColors()
        originalColor.SetWindow(colorWindow)
        originalColor.SetLevel(colorLevel)
        originalColor.SetInputData(subtr.GetOutput())
        originalColor.Update()
        return self._update(originalColor.GetOutput())
Beispiel #9
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())
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# This script subtracts the 2D laplacian from an image to enhance the edges.
# Image pipeline
reader = vtk.vtkPNGReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png")
cast = vtk.vtkImageCast()
cast.SetInputConnection(reader.GetOutputPort())
cast.SetOutputScalarTypeToDouble()
cast.Update()
lap = vtk.vtkImageLaplacian()
lap.SetInputConnection(cast.GetOutputPort())
lap.SetDimensionality(2)
lap.Update()
subtract = vtk.vtkImageMathematics()
subtract.SetOperationToSubtract()
subtract.SetInput1Data(cast.GetOutput())
subtract.SetInput2Data(lap.GetOutput())
subtract.ReleaseDataFlagOff()
#subtract BypassOn
viewer = vtk.vtkImageViewer()
#viewer DebugOn
viewer.SetInputConnection(subtract.GetOutputPort())
viewer.SetColorWindow(2000)
viewer.SetColorLevel(1000)
viewer.Render()
# --- end of script --
Beispiel #11
0
def main():
    # colors = vtk.vtkNamedColors()

    fileName = get_program_parameters()

    # Read the image.
    readerFactory = vtk.vtkImageReader2Factory()
    reader = readerFactory.CreateImageReader2(fileName)
    reader.SetFileName(fileName)
    reader.Update()

    scalarRange = [0] * 2
    scalarRange[0] = reader.GetOutput().GetPointData().GetScalars().GetRange()[0]
    scalarRange[1] = reader.GetOutput().GetPointData().GetScalars().GetRange()[1]
    print("Range:", scalarRange)
    middleSlice = 22

    # Work with triple images.
    cast = vtk.vtkImageCast()
    cast.SetInputConnection(reader.GetOutputPort())
    cast.SetOutputScalarTypeToDouble()
    cast.Update()

    laplacian = vtk.vtkImageLaplacian()
    laplacian.SetInputConnection(cast.GetOutputPort())
    laplacian.SetDimensionality(3)

    enhance = vtk.vtkImageMathematics()
    enhance.SetInputConnection(0, cast.GetOutputPort())
    enhance.SetInputConnection(1, laplacian.GetOutputPort())
    enhance.SetOperationToSubtract()

    colorWindow = (scalarRange[1] - scalarRange[0])
    colorLevel = colorWindow / 2

    # Map the image through the lookup table.
    originalColor = vtk.vtkImageMapToWindowLevelColors()
    originalColor.SetWindow(colorWindow)
    originalColor.SetLevel(colorLevel)
    originalColor.SetInputConnection(reader.GetOutputPort())

    originalActor = vtk.vtkImageActor()
    originalActor.GetMapper().SetInputConnection(originalColor.GetOutputPort())
    originalActor.GetProperty().SetInterpolationTypeToNearest()
    originalActor.SetDisplayExtent(
        reader.GetDataExtent()[0], reader.GetDataExtent()[1],
        reader.GetDataExtent()[2], reader.GetDataExtent()[3],
        middleSlice, middleSlice)

    laplacianColor = vtk.vtkImageMapToWindowLevelColors()
    laplacianColor.SetWindow(1000)
    laplacianColor.SetLevel(0)
    laplacianColor.SetInputConnection(laplacian.GetOutputPort())

    laplacianActor = vtk.vtkImageActor()
    laplacianActor.GetMapper().SetInputConnection(laplacianColor.GetOutputPort())
    laplacianActor.GetProperty().SetInterpolationTypeToNearest()
    laplacianActor.SetDisplayExtent(originalActor.GetDisplayExtent())

    enhancedColor = vtk.vtkImageMapToWindowLevelColors()
    enhancedColor.SetWindow(colorWindow)
    enhancedColor.SetLevel(colorLevel)
    enhancedColor.SetInputConnection(enhance.GetOutputPort())

    enhancedActor = vtk.vtkImageActor()
    enhancedActor.GetMapper().SetInputConnection(enhancedColor.GetOutputPort())
    enhancedActor.GetProperty().SetInterpolationTypeToNearest()
    enhancedActor.SetDisplayExtent(originalActor.GetDisplayExtent())

    # Setup the renderers.
    originalRenderer = vtk.vtkRenderer()
    originalRenderer.AddActor(originalActor)
    laplacianRenderer = vtk.vtkRenderer()
    laplacianRenderer.AddActor(laplacianActor)
    enhancedRenderer = vtk.vtkRenderer()
    enhancedRenderer.AddActor(enhancedActor)

    renderers = list()
    renderers.append(originalRenderer)
    renderers.append(laplacianRenderer)
    renderers.append(enhancedRenderer)

    # Setup viewports for the renderers.
    rendererSize = 400
    xGridDimensions = 3
    yGridDimensions = 1

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(rendererSize * xGridDimensions, rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(xGridDimensions):
            index = row * xGridDimensions + col
            # (xmin, ymin, xmax, ymax)
            viewport = [float(col) / xGridDimensions, float(yGridDimensions - (row + 1)) / yGridDimensions,
                        float(col + 1) / xGridDimensions, float(yGridDimensions - row) / yGridDimensions]
            renderers[index].SetViewport(viewport)
            renderWindow.AddRenderer(renderers[index])

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    style = vtk.vtkInteractorStyleImage()

    renderWindowInteractor.SetInteractorStyle(style)
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Renderers share one camera.
    renderWindow.Render()
    renderers[0].GetActiveCamera().Dolly(1.5)
    renderers[0].ResetCameraClippingRange()

    for r in range(1, len(renderers)):
        renderers[r].SetActiveCamera(renderers[0].GetActiveCamera())
    renderWindowInteractor.Initialize()
    renderWindowInteractor.Start()
Beispiel #12
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()