Exemple #1
0
def read_slc_file(filename):
    print("Reading SLC file")
    reader = vtk.vtkSLCReader()
    reader.SetFileName(filename)
    reader.Update()

    return reader
Exemple #2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkSLCReader(), 'Reading vtkSLC.',
         (), ('vtkSLC',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemple #3
0
def loadImageData(filename, spacing=()):
    """Read and return a ``vtkImageData`` object from file.
    Use ``load`` instead.
    E.g. `img = load('myfile.tif').imagedata()`
    """
    if ".tif" in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif ".slc" in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            colors.printc("~prohibited Sorry bad slc file " + filename, c=1)
            return None
    elif ".vti" in filename.lower():
        reader = vtk.vtkXMLImageDataReader()
    elif ".mhd" in filename.lower():
        reader = vtk.vtkMetaImageReader()
    elif ".dem" in filename.lower():
        reader = vtk.vtkDEMReader()
    elif ".nii" in filename.lower():
        reader = vtk.vtkNIFTIImageReader()
    elif ".nrrd" in filename.lower():
        reader = vtk.vtkNrrdReader()
        if not reader.CanReadFile(filename):
            colors.printc("~prohibited Sorry bad nrrd file " + filename, c=1)
            return None
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()
    if len(spacing) == 3:
        image.SetSpacing(spacing[0], spacing[1], spacing[2])
    return image
Exemple #4
0
def read_SLC_file(filename):
    # vtkSLCReader to read.
    read = vtk.vtkSLCReader()
    read.SetFileName(filename)
    read.Update()

    return read
Exemple #5
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkSLCReader(),
                                       'Reading vtkSLC.', (), ('vtkSLC', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Exemple #6
0
def main():
    InputFilename = get_program_parameters()

    colors = vtk.vtkNamedColors()

    # vtkSLCReader to read.
    reader = vtk.vtkSLCReader()
    reader.SetFileName(InputFilename)
    reader.Update()

    # Create a mapper.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(reader.GetOutputPort())

    # Implementing Marching Cubes Algorithm to create the surface using vtkContourFilter object.
    contourFilter = vtk.vtkContourFilter()
    contourFilter.SetInputConnection(reader.GetOutputPort())
    contourFilter.SetValue(0, 72.0)

    outliner = vtk.vtkOutlineFilter()
    outliner.SetInputConnection(reader.GetOutputPort())
    outliner.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(contourFilter.GetOutputPort())
    mapper.SetScalarVisibility(0)

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

    # Create a rendering window and renderer.
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(500, 500)

    # Create a renderwindowinteractor.
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Assign actor to the renderer.
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("lemon_chiffon"))

    # Pick a good view
    renderer.GetActiveCamera().SetPosition(-382.606608, -3.308563, 223.475751)
    renderer.GetActiveCamera().SetFocalPoint(77.311562, 72.821162, 100.000000)
    renderer.GetActiveCamera().SetViewUp(0.235483, 0.137775, 0.962063)
    renderer.GetActiveCamera().SetDistance(482.25171)
    renderer.GetActiveCamera().SetClippingRange(27.933848, 677.669341)
    renderWindow.Render()

    # Enable user interface interactor.
    renderWindowInteractor.Initialize()
    renderWindow.Render()
    renderWindowInteractor.Start()
Exemple #7
0
def load_slc(filename):
    """ Load a slc file and return its content
    Args:
        source: Path and filename
    Returns:
        vtkSLCReader
    """

    slc = vtk.vtkSLCReader()
    slc.SetFileName(filename)
    slc.Update()

    return slc
Exemple #8
0
def loadImageData(filename, spacing=[]):

    if not os.path.isfile(filename):
        vc.printc('File not found:', filename, c=1)
        return None

    if '.tif' in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif '.slc' in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            vc.printc('Sorry bad SLC/TIFF file ' + filename, c=1)
            exit(1)
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()
    if len(spacing) == 3:
        image.SetSpacing(spacing[0], spacing[1], spacing[2])
    vc.printc('voxel spacing is', image.GetSpacing(), c='b', bold=0)
    return image
Exemple #9
0
def loadImageData(filename, spacing=[]):

    if not os.path.isfile(filename):
        colors.printc('File not found:', filename, c=1)
        return None

    if '.tif' in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif '.slc' in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            colors.printc('Sorry bad slc file ' + filename, c=1)
            exit(1)
    elif '.vti' in filename.lower():
        reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()
    if len(spacing) == 3:
        image.SetSpacing(spacing[0], spacing[1], spacing[2])
    return image
Exemple #10
0
def load_image_data():
    '''
    Used to load the knee image data. It is possible to choose if we want to downsample it with the write_file 
    boolean declared above
    '''

    # Loading image data from file
    reader = vtk.vtkSLCReader()
    reader.SetFileName('vw_knee.slc')
    reader.Update()

    spacing = reader.GetDataSpacing()

    # resampling if we want to
    if low_res:
        resample = vtk.vtkImageResample()
        resample.SetMagnificationFactors(0.2, 0.2, 0.2)
        resample.SetInputConnection(reader.GetOutputPort())
        resample.Update()
        reader = resample

    # return the space between each point too
    return (reader, spacing)
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Simple volume rendering example.
reader = vtk.vtkSLCReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/sphere.slc")
reader.Update()
# Create transfer functions for opacity and color
opacityTransferFunction = vtk.vtkPiecewiseFunction()
opacityTransferFunction.AddPoint(20,0.0)
opacityTransferFunction.AddPoint(255,1.0)
colorTransferFunction = vtk.vtkColorTransferFunction()
# Improve coverage
colorTransferFunction.SetColorSpaceToRGB()
colorTransferFunction.AddRGBPoint(100,1,1,1)
colorTransferFunction.AddRGBPoint(0,0,0,0)
colorTransferFunction.AddRGBPoint(200,1,0,1)
colorTransferFunction.AddRGBPoint(100,0,0,0)
colorTransferFunction.RemovePoint(100)
colorTransferFunction.RemovePoint(0)
colorTransferFunction.RemovePoint(200)
colorTransferFunction.AddHSVPoint(100,1,1,1)
colorTransferFunction.AddHSVPoint(0,0,0,0)
colorTransferFunction.AddHSVPoint(200,1,0,1)
colorTransferFunction.AddHSVPoint(100,0,0,0)
colorTransferFunction.RemovePoint(0)
colorTransferFunction.RemovePoint(200)
colorTransferFunction.RemovePoint(100)
Exemple #12
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Simple volume rendering example.
reader = vtk.vtkSLCReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/sphere.slc")
# Create transfer functions for opacity and color
opacityTransferFunction = vtk.vtkPiecewiseFunction()
opacityTransferFunction.AddPoint(0,0.0)
opacityTransferFunction.AddPoint(30,0.0)
opacityTransferFunction.AddPoint(80,0.5)
opacityTransferFunction.AddPoint(255,0.5)
colorTransferFunction = vtk.vtkColorTransferFunction()
colorTransferFunction.AddRGBPoint(0.0,0.0,0.0,0.0)
colorTransferFunction.AddRGBPoint(64.0,1.0,0.0,0.0)
colorTransferFunction.AddRGBPoint(128.0,0.0,0.0,1.0)
colorTransferFunction.AddRGBPoint(192.0,0.0,1.0,0.0)
colorTransferFunction.AddRGBPoint(255.0,0.0,0.2,0.0)
# Create properties, mappers, volume actors, and ray cast function
volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(colorTransferFunction)
volumeProperty.SetScalarOpacity(opacityTransferFunction)
volumeProperty.SetInterpolationTypeToLinear()
volumeProperty.ShadeOn()
compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
 def __init__(self):
     vtkImageReaderBase.vtkImageReaderBase.__init__(self)
     self.SetImageReader(vtk.vtkSLCReader())
Exemple #14
0
    def SetUp(self):
        '''
        Set up cursor3D
        '''
        def OnClosing():
            self.root.quit()

        def ViewerDown(tkvw):
            viewer = tkvw.GetImageViewer()
            ViewerSetZSlice(tkvw, viewer.GetZSlice() - 1)

        def ViewerUp(tkvw):
            viewer = tkvw.GetImageViewer()
            ViewerSetZSlice(tkvw, viewer.GetZSlice() + 1)

        def ViewerSetZSlice(tkvw, z):
            viewer = tkvw.GetImageViewer()
            viewer.SetZSlice(z)
            txt = 'slice: ' + str(z)
            sliceLabel.configure(text=txt)
            tkvw.Render()

        def SetCursorFromViewer(event):
            x = int(event.x)
            y = int(event.y)
            # We have to flip y axis because tk uses upper right origin.
            self.root.update_idletasks()
            height = int(self.tkvw.configure()['height'][4])
            y = height - y
            z = self.tkvw.GetImageViewer().GetZSlice()
            SetCursor(x / IMAGE_MAG_X, y / IMAGE_MAG_Y, z / IMAGE_MAG_Z)

        def SetCursor(x, y, z):

            CURSOR_X = x
            CURSOR_Y = y
            CURSOR_Z = z

            axes.SetOrigin(CURSOR_X, CURSOR_Y, CURSOR_Z)
            imageCursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X,
                                          CURSOR_Y * IMAGE_MAG_Y,
                                          CURSOR_Z * IMAGE_MAG_Z)

            self.viewer.Render()
            self.tkrw.Render()

        # Pipeline stuff.
        reader = vtk.vtkSLCReader()
        reader.SetFileName(VTK_DATA_ROOT + "/Data/neghip.slc")
        # Cursor stuff

        magnify = vtk.vtkImageMagnify()
        magnify.SetInputConnection(reader.GetOutputPort())
        magnify.SetMagnificationFactors(IMAGE_MAG_X, IMAGE_MAG_Y, IMAGE_MAG_Z)

        imageCursor = vtk.vtkImageCursor3D()
        imageCursor.SetInputConnection(magnify.GetOutputPort())
        imageCursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X,
                                      CURSOR_Y * IMAGE_MAG_Y,
                                      CURSOR_Z * IMAGE_MAG_Z)
        imageCursor.SetCursorValue(255)
        imageCursor.SetCursorRadius(50 * IMAGE_MAG_X)

        axes = vtk.vtkAxes()
        axes.SymmetricOn()
        axes.SetOrigin(CURSOR_X, CURSOR_Y, CURSOR_Z)
        axes.SetScaleFactor(50.0)

        axes_mapper = vtk.vtkPolyDataMapper()
        axes_mapper.SetInputConnection(axes.GetOutputPort())

        axesActor = vtk.vtkActor()
        axesActor.SetMapper(axes_mapper)
        axesActor.GetProperty().SetAmbient(0.5)

        # Image viewer stuff.
        viewer = vtk.vtkImageViewer()
        viewer.SetInputConnection(imageCursor.GetOutputPort())
        viewer.SetZSlice(CURSOR_Z * IMAGE_MAG_Z)
        viewer.SetColorWindow(256)
        viewer.SetColorLevel(128)

        # Create transfer functions for opacity and color.
        opacity_transfer_function = vtk.vtkPiecewiseFunction()
        opacity_transfer_function.AddPoint(20, 0.0)
        opacity_transfer_function.AddPoint(255, 0.2)

        color_transfer_function = vtk.vtkColorTransferFunction()
        color_transfer_function.AddRGBPoint(0, 0, 0, 0)
        color_transfer_function.AddRGBPoint(64, 1, 0, 0)
        color_transfer_function.AddRGBPoint(128, 0, 0, 1)
        color_transfer_function.AddRGBPoint(192, 0, 1, 0)
        color_transfer_function.AddRGBPoint(255, 0, .2, 0)

        # Create properties, mappers, volume actors, and ray cast function.
        volume_property = vtk.vtkVolumeProperty()
        volume_property.SetColor(color_transfer_function)
        #         volume_property.SetColor(color_transfer_function[0],
        #                                  color_transfer_function[1],
        #                                  color_transfer_function[2])
        volume_property.SetScalarOpacity(opacity_transfer_function)

        volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volume_mapper.SetInputConnection(reader.GetOutputPort())

        volume = vtk.vtkVolume()
        volume.SetMapper(volume_mapper)
        volume.SetProperty(volume_property)

        # Create outline.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(reader.GetOutputPort())

        outline_mapper = vtk.vtkPolyDataMapper()
        outline_mapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outline_mapper)
        outlineActor.GetProperty().SetColor(1, 1, 1)

        # Create the renderer.
        ren = vtk.vtkRenderer()
        ren.AddActor(axesActor)
        ren.AddVolume(volume)
        ren.SetBackground(0.1, 0.2, 0.4)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.SetSize(256, 256)

        # Create the GUI: two renderer widgets and a quit button.
        self.root = tkinter.Tk()
        self.root.title("cursor3D")
        # Define what to do when the user explicitly closes a window.
        self.root.protocol("WM_DELETE_WINDOW", OnClosing)

        # Help label, frame and quit button
        helpLabel = tkinter.Label(
            self.root,
            text=
            "MiddleMouse (or shift-LeftMouse) in image viewer to place cursor")
        displayFrame = tkinter.Frame(self.root)
        quitButton = tkinter.Button(self.root, text="Quit", command=OnClosing)

        # Pack the GUI.
        helpLabel.pack()
        displayFrame.pack(fill=BOTH, expand=TRUE)
        quitButton.pack(fill=X)

        # Create the viewer widget.
        viewerFrame = tkinter.Frame(displayFrame)
        viewerFrame.pack(padx=3,
                         pady=3,
                         side=LEFT,
                         anchor=N,
                         fill=BOTH,
                         expand=FALSE)
        self.tkvw = vtkTkImageViewerWidget(viewerFrame,
                                           iv=viewer,
                                           width=264,
                                           height=264)
        viewerControls = tkinter.Frame(viewerFrame)
        viewerControls.pack(side=BOTTOM, anchor=S, fill=BOTH, expand=TRUE)
        self.tkvw.pack(side=TOP, anchor=N, fill=BOTH, expand=FALSE)
        downButton = tkinter.Button(viewerControls,
                                    text="Down",
                                    command=[ViewerDown, self.tkvw])
        upButton = tkinter.Button(viewerControls,
                                  text="Up",
                                  command=[ViewerUp, self.tkvw])
        sliceLabel = tkinter.Label(viewerControls,
                                   text="slice: " +
                                   str(CURSOR_Z * IMAGE_MAG_Z))
        downButton.pack(side=LEFT, expand=TRUE, fill=BOTH)
        upButton.pack(side=LEFT, expand=TRUE, fill=BOTH)
        sliceLabel.pack(side=LEFT, expand=TRUE, fill=BOTH)

        # Create the render widget
        renderFrame = tkinter.Frame(displayFrame)
        renderFrame.pack(padx=3,
                         pady=3,
                         side=LEFT,
                         anchor=N,
                         fill=BOTH,
                         expand=TRUE)
        self.tkrw = vtkTkRenderWidget(renderFrame,
                                      rw=renWin,
                                      width=264,
                                      height=264)

        self.tkrw.pack(side=TOP, anchor=N, fill=BOTH, expand=TRUE)

        # Bindings
        self.tkvw.BindTkImageViewer()
        self.tkrw.BindTkRenderWidget()

        # Lets add an extra binding of the middle button in the image viewer
        # to set the cursor location.
        self.tkvw.bind('<Button-2>', SetCursorFromViewer)
        self.tkvw.bind('<Shift-Button-1>', SetCursorFromViewer)

        # Associate the functions with the buttons and label.
        #
        downButton.config(command=partial(ViewerDown, self.tkvw))
        upButton.config(command=partial(ViewerUp, self.tkvw))
Exemple #15
0
def loadVolume(filename, c, alpha, wire, bc, edges, legend, texture, smoothing,
               threshold, connectivity, scaling):
    '''Return vtkActor from a TIFF stack or SLC file'''
    if not os.path.exists(filename):
        vc.printc(('Error in loadVolume: Cannot find file', filename), c=1)
        return None

    print('..reading file:', filename)
    if '.tif' in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif '.slc' in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            vc.printc('Sorry bad SLC file ' + filename, 1)
            exit(1)
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()

    if smoothing:
        print('  gaussian smoothing data with volume_smoothing =', smoothing)
        smImg = vtk.vtkImageGaussianSmooth()
        smImg.SetDimensionality(3)
        vu.setInput(smImg, image)
        smImg.SetStandardDeviations(smoothing, smoothing, smoothing)
        smImg.Update()
        image = smImg.GetOutput()

    scrange = image.GetScalarRange()
    if not threshold:
        threshold = (2 * scrange[0] + scrange[1]) / 3.
        a = '  isosurfacing volume with automatic iso_threshold ='
    else:
        a = '  isosurfacing volume with iso_threshold ='
    print(a, round(threshold, 2), scrange)
    cf = vtk.vtkContourFilter()
    vu.setInput(cf, image)
    cf.UseScalarTreeOn()
    cf.ComputeScalarsOff()
    cf.SetValue(0, threshold)
    cf.Update()

    clp = vtk.vtkCleanPolyData()
    vu.setInput(clp, cf.GetOutput())
    clp.Update()
    image = clp.GetOutput()

    if connectivity:
        print('  applying connectivity filter, select largest region')
        conn = vtk.vtkPolyDataConnectivityFilter()
        conn.SetExtractionModeToLargestRegion()
        vu.setInput(conn, image)
        conn.Update()
        image = conn.GetOutput()

    if scaling:
        print('  scaling xyz by factors', scaling)
        tf = vtk.vtkTransformPolyDataFilter()
        vu.setInput(tf, image)
        trans = vtk.vtkTransform()
        trans.Scale(scaling)
        tf.SetTransform(trans)
        tf.Update()
        image = tf.GetOutput()
    return vu.makeActor(image, c, alpha, wire, bc, edges, legend, texture)
Exemple #16
0
    def testContour2DAll(self):

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetMultiSamples(0)
        renWin.AddRenderer(ren)

        # create pipeline
        #
        slc = vtk.vtkSLCReader()
        slc.SetFileName(VTK_DATA_ROOT + "/Data/nut.slc")
        slc.Update()

        types = ["Char", "UnsignedChar", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"]

        i = 3

        clip = list()
        cast = list()
        iso = list()
        mapper = list()
        actor = list()

        for idx, vtkType in enumerate(types):

            clip.append(vtk.vtkImageClip())
            clip[idx].SetInputConnection(slc.GetOutputPort())
            clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i)

            i += 2

            cast.append(vtk.vtkImageCast())
            eval("cast[idx].SetOutputScalarTypeTo" + vtkType)
            cast[idx].SetInputConnection(clip[idx].GetOutputPort())
            cast[idx].ClampOverflowOn()

            iso.append(vtk.vtkContourFilter())
            iso[idx] = vtk.vtkContourFilter()
            iso[idx].SetInputConnection(cast[idx].GetOutputPort())
            iso[idx].GenerateValues(1, 30, 30)

            mapper.append(vtk.vtkPolyDataMapper())
            mapper[idx].SetInputConnection(iso[idx].GetOutputPort())
            mapper[idx].SetColorModeToMapScalars()

            actor.append(vtk.vtkActor())
            actor[idx].SetMapper(mapper[idx])
            ren.AddActor(actor[idx])

        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(slc.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)
        outlineActor.VisibilityOff()
        #
        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(outlineActor)
        ren.ResetCamera()
        ren.GetActiveCamera().SetViewAngle(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Azimuth(20)
        ren.GetActiveCamera().Zoom(1.5)
        ren.ResetCameraClippingRange()

        ren.SetBackground(0.9, .9, .9)
        renWin.SetSize(200, 200)

        # render and interact with data

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

        img_file = "contour2DAll.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemple #17
0
# Create the standard renderer, render window
# and interactor
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.SetDesiredUpdateRate(3)
# Create the reader for the data
# This is the data the will be volume rendered
reader = vtk.vtkStructuredPointsReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/ironProt.vtk")
# create a reader for the other data that will
# be contoured and displayed as a polygonal mesh
reader2 = vtk.vtkSLCReader()
reader2.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/neghip.slc")
# convert from vtkImageData to vtkUnstructuredGrid, remove
# any cells where all values are below 80
thresh = vtk.vtkThreshold()
thresh.ThresholdByUpper(80)
thresh.AllScalarsOff()
thresh.SetInputConnection(reader.GetOutputPort())
# make sure we have only tetrahedra
trifilter = vtk.vtkDataSetTriangleFilter()
trifilter.SetInputConnection(thresh.GetOutputPort())
# Create transfer mapping scalar value to opacity
opacityTransferFunction = vtk.vtkPiecewiseFunction()
opacityTransferFunction.AddPoint(80,0.0)
opacityTransferFunction.AddPoint(120,0.2)
opacityTransferFunction.AddPoint(255,0.2)
Exemple #18
0
# Create the standard renderer, render window
# and interactor
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.SetDesiredUpdateRate(3)
# Create the reader for the data
# This is the data the will be volume rendered
reader = vtk.vtkStructuredPointsReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/ironProt.vtk")
# create a reader for the other data that will
# be contoured and displayed as a polygonal mesh
reader2 = vtk.vtkSLCReader()
reader2.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/neghip.slc")
# convert from vtkImageData to vtkUnstructuredGrid, remove
# any cells where all values are below 80
thresh = vtk.vtkThreshold()
thresh.ThresholdByUpper(80)
thresh.AllScalarsOff()
thresh.SetInputConnection(reader.GetOutputPort())
# make sure we have only tetrahedra
trifilter = vtk.vtkDataSetTriangleFilter()
trifilter.SetInputConnection(thresh.GetOutputPort())
# Create transfer mapping scalar value to opacity
opacityTransferFunction = vtk.vtkPiecewiseFunction()
opacityTransferFunction.AddPoint(80,0.0)
opacityTransferFunction.AddPoint(120,0.2)
opacityTransferFunction.AddPoint(255,0.2)
Exemple #19
0
    def testContour2DAll(self):

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetMultiSamples(0)
        renWin.AddRenderer(ren)

        # create pipeline
        #
        slc = vtk.vtkSLCReader()
        slc.SetFileName(VTK_DATA_ROOT + "/Data/nut.slc")
        slc.Update()

        types = [
            "Char", "UnsignedChar", "Short", "UnsignedShort", "Int",
            "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"
        ]

        i = 3

        clip = list()
        cast = list()
        iso = list()
        mapper = list()
        actor = list()

        for idx, vtkType in enumerate(types):

            clip.append(vtk.vtkImageClip())
            clip[idx].SetInputConnection(slc.GetOutputPort())
            clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i)

            i += 2

            cast.append(vtk.vtkImageCast())
            eval("cast[idx].SetOutputScalarTypeTo" + vtkType)
            cast[idx].SetInputConnection(clip[idx].GetOutputPort())
            cast[idx].ClampOverflowOn()

            iso.append(vtk.vtkContourFilter())
            iso[idx] = vtk.vtkContourFilter()
            iso[idx].SetInputConnection(cast[idx].GetOutputPort())
            iso[idx].GenerateValues(1, 30, 30)

            mapper.append(vtk.vtkPolyDataMapper())
            mapper[idx].SetInputConnection(iso[idx].GetOutputPort())
            mapper[idx].SetColorModeToMapScalars()

            actor.append(vtk.vtkActor())
            actor[idx].SetMapper(mapper[idx])
            ren.AddActor(actor[idx])

        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(slc.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)
        outlineActor.VisibilityOff()
        #
        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(outlineActor)
        ren.ResetCamera()
        ren.GetActiveCamera().SetViewAngle(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Azimuth(20)
        ren.GetActiveCamera().Zoom(1.5)
        ren.ResetCameraClippingRange()

        ren.SetBackground(0.9, .9, .9)
        renWin.SetSize(200, 200)

        # render and interact with data

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

        img_file = "contour2DAll.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
Exemple #20
0
import vtk
from vtk.util.colors import tan

## Load in knee model
kneeFile = r"./assets/vw_knee.slc"
kneeReader = vtk.vtkSLCReader()
kneeReader.SetFileName(kneeFile)

## Apply contourfilter to knee skin model
kneeSkinContourFilter = vtk.vtkContourFilter()
kneeSkinContourFilter.SetInputConnection(kneeReader.GetOutputPort())
kneeSkinContourFilter.SetValue(0, 50)

## Clip the knee skin
sphere = vtk.vtkSphere()
sphere.SetCenter(0, 0, 50)
sphere.SetRadius(100)

sphereClip = vtk.vtkClipPolyData()
sphereClip.SetInputConnection(kneeSkinContourFilter.GetOutputPort())
sphereClip.GenerateClippedOutputOn()
sphereClip.GenerateClipScalarsOn()
sphereClip.SetClipFunction(sphere)

## Apply contour filter to knee itself
kneeContourFilter = vtk.vtkContourFilter()
kneeContourFilter.SetInputConnection(kneeReader.GetOutputPort())
kneeContourFilter.SetValue(0, 80)

## Smoothen everything up by sampling less
kneeExtractVOI = vtk.vtkExtractVOI()
Exemple #21
0
    def SetUp(self):
        """
        Set up cursor3D
        """

        def OnClosing():
            self.root.quit()

        def ViewerDown(tkvw):
            viewer = tkvw.GetImageViewer()
            ViewerSetZSlice(tkvw, viewer.GetZSlice() - 1)

        def ViewerUp(tkvw):
            viewer = tkvw.GetImageViewer()
            ViewerSetZSlice(tkvw, viewer.GetZSlice() + 1)

        def ViewerSetZSlice(tkvw, z):
            viewer = tkvw.GetImageViewer()
            viewer.SetZSlice(z)
            txt = "slice: " + str(z)
            sliceLabel.configure(text=txt)
            tkvw.Render()

        def SetCursorFromViewer(event):
            x = int(event.x)
            y = int(event.y)
            # We have to flip y axis because tk uses upper right origin.
            self.root.update_idletasks()
            height = int(self.tkvw.configure()["height"][4])
            y = height - y
            z = self.tkvw.GetImageViewer().GetZSlice()
            SetCursor(x / IMAGE_MAG_X, y / IMAGE_MAG_Y, z / IMAGE_MAG_Z)

        def SetCursor(x, y, z):

            CURSOR_X = x
            CURSOR_Y = y
            CURSOR_Z = z

            axes.SetOrigin(CURSOR_X, CURSOR_Y, CURSOR_Z)
            imageCursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X, CURSOR_Y * IMAGE_MAG_Y, CURSOR_Z * IMAGE_MAG_Z)

            self.viewer.Render()
            self.tkrw.Render()

        # Pipeline stuff.
        reader = vtk.vtkSLCReader()
        reader.SetFileName(VTK_DATA_ROOT + "/Data/neghip.slc")
        # Cursor stuff

        magnify = vtk.vtkImageMagnify()
        magnify.SetInputConnection(reader.GetOutputPort())
        magnify.SetMagnificationFactors(IMAGE_MAG_X, IMAGE_MAG_Y, IMAGE_MAG_Z)

        imageCursor = vtk.vtkImageCursor3D()
        imageCursor.SetInputConnection(magnify.GetOutputPort())
        imageCursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X, CURSOR_Y * IMAGE_MAG_Y, CURSOR_Z * IMAGE_MAG_Z)
        imageCursor.SetCursorValue(255)
        imageCursor.SetCursorRadius(50 * IMAGE_MAG_X)

        axes = vtk.vtkAxes()
        axes.SymmetricOn()
        axes.SetOrigin(CURSOR_X, CURSOR_Y, CURSOR_Z)
        axes.SetScaleFactor(50.0)

        axes_mapper = vtk.vtkPolyDataMapper()
        axes_mapper.SetInputConnection(axes.GetOutputPort())

        axesActor = vtk.vtkActor()
        axesActor.SetMapper(axes_mapper)
        axesActor.GetProperty().SetAmbient(0.5)

        # Image viewer stuff.
        viewer = vtk.vtkImageViewer()
        viewer.SetInputConnection(imageCursor.GetOutputPort())
        viewer.SetZSlice(CURSOR_Z * IMAGE_MAG_Z)
        viewer.SetColorWindow(256)
        viewer.SetColorLevel(128)

        # Create transfer functions for opacity and color.
        opacity_transfer_function = vtk.vtkPiecewiseFunction()
        opacity_transfer_function.AddPoint(20, 0.0)
        opacity_transfer_function.AddPoint(255, 0.2)

        color_transfer_function = vtk.vtkColorTransferFunction()
        color_transfer_function.AddRGBPoint(0, 0, 0, 0)
        color_transfer_function.AddRGBPoint(64, 1, 0, 0)
        color_transfer_function.AddRGBPoint(128, 0, 0, 1)
        color_transfer_function.AddRGBPoint(192, 0, 1, 0)
        color_transfer_function.AddRGBPoint(255, 0, 0.2, 0)

        # Create properties, mappers, volume actors, and ray cast function.
        volume_property = vtk.vtkVolumeProperty()
        volume_property.SetColor(color_transfer_function)
        #         volume_property.SetColor(color_transfer_function[0],
        #                                  color_transfer_function[1],
        #                                  color_transfer_function[2])
        volume_property.SetScalarOpacity(opacity_transfer_function)

        volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volume_mapper.SetInputConnection(reader.GetOutputPort())

        volume = vtk.vtkVolume()
        volume.SetMapper(volume_mapper)
        volume.SetProperty(volume_property)

        # Create outline.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(reader.GetOutputPort())

        outline_mapper = vtk.vtkPolyDataMapper()
        outline_mapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outline_mapper)
        outlineActor.GetProperty().SetColor(1, 1, 1)

        # Create the renderer.
        ren = vtk.vtkRenderer()
        ren.AddActor(axesActor)
        ren.AddVolume(volume)
        ren.SetBackground(0.1, 0.2, 0.4)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.SetSize(256, 256)

        # Create the GUI: two renderer widgets and a quit button.
        self.root = tkinter.Tk()
        self.root.title("cursor3D")
        # Define what to do when the user explicitly closes a window.
        self.root.protocol("WM_DELETE_WINDOW", OnClosing)

        # Help label, frame and quit button
        helpLabel = tkinter.Label(self.root, text="MiddleMouse (or shift-LeftMouse) in image viewer to place cursor")
        displayFrame = tkinter.Frame(self.root)
        quitButton = tkinter.Button(self.root, text="Quit", command=OnClosing)

        # Pack the GUI.
        helpLabel.pack()
        displayFrame.pack(fill=BOTH, expand=TRUE)
        quitButton.pack(fill=X)

        # Create the viewer widget.
        viewerFrame = tkinter.Frame(displayFrame)
        viewerFrame.pack(padx=3, pady=3, side=LEFT, anchor=N, fill=BOTH, expand=FALSE)
        self.tkvw = vtkTkImageViewerWidget(viewerFrame, iv=viewer, width=264, height=264)
        viewerControls = tkinter.Frame(viewerFrame)
        viewerControls.pack(side=BOTTOM, anchor=S, fill=BOTH, expand=TRUE)
        self.tkvw.pack(side=TOP, anchor=N, fill=BOTH, expand=FALSE)
        downButton = tkinter.Button(viewerControls, text="Down", command=[ViewerDown, self.tkvw])
        upButton = tkinter.Button(viewerControls, text="Up", command=[ViewerUp, self.tkvw])
        sliceLabel = tkinter.Label(viewerControls, text="slice: " + str(CURSOR_Z * IMAGE_MAG_Z))
        downButton.pack(side=LEFT, expand=TRUE, fill=BOTH)
        upButton.pack(side=LEFT, expand=TRUE, fill=BOTH)
        sliceLabel.pack(side=LEFT, expand=TRUE, fill=BOTH)

        # Create the render widget
        renderFrame = tkinter.Frame(displayFrame)
        renderFrame.pack(padx=3, pady=3, side=LEFT, anchor=N, fill=BOTH, expand=TRUE)
        self.tkrw = vtkTkRenderWidget(renderFrame, rw=renWin, width=264, height=264)

        self.tkrw.pack(side=TOP, anchor=N, fill=BOTH, expand=TRUE)

        # Bindings
        self.tkvw.BindTkImageViewer()
        self.tkrw.BindTkRenderWidget()

        # Lets add an extra binding of the middle button in the image viewer
        # to set the cursor location.
        self.tkvw.bind("<Button-2>", SetCursorFromViewer)
        self.tkvw.bind("<Shift-Button-1>", SetCursorFromViewer)

        # Associate the functions with the buttons and label.
        #
        downButton.config(command=partial(ViewerDown, self.tkvw))
        upButton.config(command=partial(ViewerUp, self.tkvw))
Exemple #22
0
def main():
    InputFilename, iso_value = get_program_parameters()

    colors = vtk.vtkNamedColors()

    # vtkSLCReader to read.
    reader = vtk.vtkSLCReader()
    reader.SetFileName(InputFilename)
    reader.Update()

    # Create a mapper.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(reader.GetOutputPort())

    # Implementing Marching Cubes Algorithm to create the surface using vtkContourFilter object.
    contourFilter = vtk.vtkContourFilter()
    contourFilter.SetInputConnection(reader.GetOutputPort())
    # Change the range(2nd and 3rd Paramater) based on your
    # requirement. recomended value for 1st parameter is above 1
    # contourFilter.GenerateValues(5, 80.0, 100.0)
    contourFilter.SetValue(0, iso_value)

    outliner = vtk.vtkOutlineFilter()
    outliner.SetInputConnection(reader.GetOutputPort())
    outliner.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(contourFilter.GetOutputPort())
    mapper.SetScalarVisibility(0)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetDiffuse(0.8)
    actor.GetProperty().SetDiffuseColor(colors.GetColor3d('Ivory'))
    actor.GetProperty().SetSpecular(0.8)
    actor.GetProperty().SetSpecularPower(120.0)

    # Create a rendering window and renderer.
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(500, 500)

    # Create a renderwindowinteractor.
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Assign actor to the renderer.
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    # Pick a good view
    cam1 = renderer.GetActiveCamera()
    cam1.SetFocalPoint(0.0, 0.0, 0.0)
    cam1.SetPosition(0.0, -1.0, 0.0)
    cam1.SetViewUp(0.0, 0.0, -1.0)
    cam1.Azimuth(-90.0)
    renderer.ResetCamera()
    renderer.ResetCameraClippingRange()

    renderWindow.SetWindowName('ReadSLC')
    renderWindow.SetSize(640, 512)
    renderWindow.Render()

    # Enable user interface interactor.
    renderWindowInteractor.Initialize()
    renderWindow.Render()
    renderWindowInteractor.Start()
Exemple #23
0
def main():
    ren_win = vtk.vtkRenderWindow()
    ren_win.SetWindowName("The good knee")
    ren_win.SetSize(1000, 1000)

    # Watch for events
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(ren_win)

    # Set the interactor style
    style = vtk.vtkInteractorStyleTrackballCamera()
    interactor.SetInteractorStyle(style)

    # Create an SLC reader
    reader = vtk.vtkSLCReader()
    reader.SetFileName(SLC_FILENAME)
    reader.Update()

    # Create contours
    bone_contour = contour(reader, 0, 72.0)
    skin_contour = contour(reader, 0, 50)

    # Create actors
    knee_outline = outline(reader)
    knee_bone = create_actor(bone_contour)
    knee_skin = create_actor(skin_contour)
    knee_skin.GetProperty().SetColor(0.9, 0.69, 0.56)

    # Cut knee for top left visualization
    cut_skin = repeated_cuts(skin_contour, 19)
    cut_skin.GetProperty().SetColor(0.9, 0.69, 0.56)

    # Clipped knee for top right and bottom left visualizations
    knee_clipped = create_sphere_clipping(skin_contour, 48, (80, 40, 110))
    knee_clipped.GetProperty().SetColor(0.9, 0.69, 0.56)

    knee_clipped_transparent = create_sphere_clipping(skin_contour, 48,
                                                      (80, 40, 110))
    knee_clipped_transparent.GetProperty().SetColor(0.9, 0.69, 0.56)
    knee_clipped_transparent.GetProperty().SetOpacity(0.5)

    knee_clipped_backside = create_sphere_clipping(skin_contour, 48,
                                                   (80, 40, 110))
    knee_clipped_backside.GetProperty().SetColor(0.9, 0.69, 0.56)
    knee_clipped_backside.GetProperty().FrontfaceCullingOn()

    sphere_transparent = get_sphere_actor((80, 40, 110), 48)
    sphere_transparent.GetProperty().SetOpacity(0.4)

    # Colored bone for bottom right visualization
    # This will generate the file if it doesn't exist (computationally expensive)
    bone_color = distance_color(bone_contour, skin_contour,
                                "bone_distance_color.vtk")

    # Set up a single camera for all the viewports
    camera = vtk.vtkCamera()
    camera.SetPosition(0, 0, 100)
    camera.SetFocalPoint(0, 0, 0)
    # Move the camera in the right position
    camera.Elevation(-90)
    camera.OrthogonalizeViewUp()
    camera.Roll(180)

    # Define viewport ranges
    viewports = [(0, 0, 0.5, 0.5), (0.5, 0, 1, 0.5), (0, 0.5, 0.5, 1),
                 (0.5, 0.5, 1, 1)]

    # Actors for the four viewports
    actors_per_viewport = [[
        knee_clipped, sphere_transparent, knee_bone, knee_outline
    ], [bone_color, knee_outline], [cut_skin, knee_bone, knee_outline],
                           [
                               knee_clipped_transparent, knee_clipped_backside,
                               knee_bone, knee_outline
                           ]]

    # Background colors for the four viewports
    bg_colors = [(0.82, 0.82, 1), (0.82, 0.82, 0.82), (1, 0.82, 0.82),
                 (0.82, 1, 0.82)]

    # Create the viewports and generate the visualizations
    for idx, actors in enumerate(actors_per_viewport):
        # Set up the renderer for this viewport
        ren = vtk.vtkRenderer()
        ren.SetActiveCamera(camera)
        ren_win.AddRenderer(ren)

        ren.SetViewport(viewports[idx])

        # Add appropriate actors
        for actor in actors:
            ren.AddActor(actor)

        ren.SetBackground(bg_colors[idx])
        ren.ResetCamera()

    # Move the camera around the focal point to turn around the objects
    for _ in range(360):
        camera.Azimuth(1)

        ren_win.Render()
        sleep(FRAMERATE)

    interactor.Start()