VTK官方例子
vtkMutableDirectedGraph
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (
vtkIntArray,
vtkLookupTable
)
from vtkmodules.vtkCommonDataModel import vtkMutableDirectedGraph
from vtkmodules.vtkViewsCore import vtkViewTheme
from vtkmodules.vtkViewsInfovis import vtkGraphLayoutView
def main():
colors = vtkNamedColors()
graph = vtkMutableDirectedGraph()
# Create a graph
v1 = graph.AddVertex()
v2 = graph.AddVertex()
v3 = graph.AddVertex()
graph.AddGraphEdge(v1, v2)
graph.AddGraphEdge(v2, v3)
# Create the color array
edgeColors = vtkIntArray()
edgeColors.SetNumberOfComponents(1)
edgeColors.SetName('Color')
lookupTable = vtkLookupTable()
lookupTable.SetNumberOfTableValues(2)
lookupTable.SetTableValue(0, colors.GetColor4d('Red'))
lookupTable.SetTableValue(1, colors.GetColor4d('Lime'))
lookupTable.Build()
edgeColors.InsertNextValue(0)
edgeColors.InsertNextValue(1)
# Add the color array to the graph
graph.GetEdgeData().AddArray(edgeColors)
graphLayoutView = vtkGraphLayoutView()
graphLayoutView.AddRepresentationFromInput(graph)
graphLayoutView.SetLayoutStrategy('Simple 2D')
graphLayoutView.GetLayoutStrategy().SetEdgeWeightField('Graphs')
graphLayoutView.GetLayoutStrategy().SetWeightEdges(1)
graphLayoutView.SetEdgeColorArrayName('Color')
graphLayoutView.SetEdgeLabelVisibility(1)
graphLayoutView.ColorEdgesOn()
theme = vtkViewTheme()
theme.SetCellLookupTable(lookupTable)
graphLayoutView.ApplyViewTheme(theme)
graphLayoutView.ResetCamera()
graphLayoutView.GetRenderer().GetActiveCamera().Zoom(0.8)
graphLayoutView.Render()
graphLayoutView.GetLayoutStrategy().SetRandomSeed(0)
graphLayoutView.GetInteractor().Initialize()
graphLayoutView.GetInteractor().Start()
if __name__ == '__main__':
main()
vtkGraphLayoutView
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkIntArray
from vtkmodules.vtkCommonDataModel import vtkMutableDirectedGraph
from vtkmodules.vtkViewsInfovis import (
vtkGraphLayoutView,
vtkRenderedGraphRepresentation
)
def main():
colors = vtkNamedColors()
# Create a graph
graph = vtkMutableDirectedGraph()
v1 = graph.AddVertex()
v2 = graph.AddVertex()
graph.AddEdge(v1, v2)
# Create an array for the vertex labels
vertexIDs = vtkIntArray()
vertexIDs.SetNumberOfComponents(1)
vertexIDs.SetName('VertexIDs')
# Set the vertex labels
vertexIDs.InsertNextValue(0)
vertexIDs.InsertNextValue(1)
# Add the array to the graph
graph.GetVertexData().AddArray(vertexIDs)
graphLayoutView = vtkGraphLayoutView()
graphLayoutView.AddRepresentationFromInput(graph)
graphLayoutView.SetVertexLabelVisibility(1)
rGraph = vtkRenderedGraphRepresentation()
rGraph.SafeDownCast(graphLayoutView.GetRepresentation()).GetVertexLabelTextProperty().SetColor(
colors.GetColor3d('Red'))
graphLayoutView.SetLayoutStrategyToSimple2D()
graphLayoutView.SetVertexLabelArrayName('VertexIDs')
graphLayoutView.SetVertexLabelVisibility(True)
graphLayoutView.ResetCamera()
graphLayoutView.GetRenderer().GetActiveCamera().Zoom(0.8)
graphLayoutView.Render()
graphLayoutView.GetInteractor().Start()
if __name__ == '__main__':
main()
ImageWeightedSum
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkImagingCore import vtkImageCast
from vtkmodules.vtkImagingMath import vtkImageWeightedSum
from vtkmodules.vtkImagingSources import (
vtkImageMandelbrotSource,
vtkImageSinusoidSource
)
from vtkmodules.vtkRenderingCore import (
vtkImageActor,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Create image 1
source1 = vtkImageMandelbrotSource()
source1.SetWholeExtent(0, 255, 0, 255, 0, 0)
source1.Update()
source1Double = vtkImageCast()
source1Double.SetInputConnection(0, source1.GetOutputPort())
source1Double.SetOutputScalarTypeToDouble()
# Create image 2
source2 = vtkImageSinusoidSource()
source2.SetWholeExtent(0, 255, 0, 255, 0, 0)
source2.Update()
# Do the sum
sumFilter = vtkImageWeightedSum()
sumFilter.SetWeight(0, 0.8)
sumFilter.SetWeight(1, 0.2)
sumFilter.AddInputConnection(source1Double.GetOutputPort())
sumFilter.AddInputConnection(source2.GetOutputPort())
sumFilter.Update()
# Display the images
source1CastFilter = vtkImageCast()
source1CastFilter.SetInputConnection(source1.GetOutputPort())
source1CastFilter.SetOutputScalarTypeToUnsignedChar()
source1CastFilter.Update()
source2CastFilter = vtkImageCast()
source2CastFilter.SetInputConnection(source2.GetOutputPort())
source2CastFilter.SetOutputScalarTypeToUnsignedChar()
source2CastFilter.Update()
summedCastFilter = vtkImageCast()
summedCastFilter.SetInputConnection(sumFilter.GetOutputPort())
summedCastFilter.SetOutputScalarTypeToUnsignedChar()
summedCastFilter.Update()
# Create actors
source1Actor = vtkImageActor()
source1Actor.GetMapper().SetInputConnection(source1CastFilter.GetOutputPort())
source2Actor = vtkImageActor()
source2Actor.GetMapper().SetInputConnection(source2CastFilter.GetOutputPort())
summedActor = vtkImageActor()
summedActor.GetMapper().SetInputConnection(summedCastFilter.GetOutputPort())
# There will be one render window
renderWindow = vtkRenderWindow()
renderWindow.SetSize(600, 300)
# And one interactor
interactor = vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
# Define viewport ranges
# (xmin, ymin, xmax, ymax)
leftViewport = [0.0, 0.0, 0.33, 1.0]
centerViewport = [0.33, 0.0, .66, 1.0]
rightViewport = [0.66, 0.0, 1.0, 1.0]
# Setup renderers
leftRenderer = vtkRenderer()
renderWindow.AddRenderer(leftRenderer)
leftRenderer.SetViewport(leftViewport)
leftRenderer.SetBackground(colors.GetColor3d('Peru'))
centerRenderer = vtkRenderer()
renderWindow.AddRenderer(centerRenderer)
centerRenderer.SetViewport(centerViewport)
centerRenderer.SetBackground(colors.GetColor3d('DarkTurquoise'))
rightRenderer = vtkRenderer()
renderWindow.AddRenderer(rightRenderer)
rightRenderer.SetViewport(rightViewport)
rightRenderer.SetBackground(colors.GetColor3d('SteelBlue'))
leftRenderer.AddActor(source1Actor)
centerRenderer.AddActor(source2Actor)
rightRenderer.AddActor(summedActor)
leftRenderer.ResetCamera()
centerRenderer.ResetCamera()
rightRenderer.ResetCamera()
renderWindow.SetWindowName('ImageWeightedSum')
renderWindow.Render()
interactor.Start()
if __name__ == '__main__':
main()
writeImageData
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import VTK_DOUBLE
from vtkmodules.vtkCommonDataModel import vtkImageData
from vtkmodules.vtkFiltersGeometry import vtkImageDataGeometryFilter
from vtkmodules.vtkIOXML import (
vtkXMLImageDataReader,
vtkXMLImageDataWriter
)
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def get_program_parameters():
import argparse
description = 'Generate image data, edit data points, store and reload it.'
epilogue = '''
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue)
parser.add_argument('filename', help='A required vtk filename, e.g. writeImageData.vti.', nargs='?',
const='writeImageData.vti',
type=str, default='writeImageData.vti')
args = parser.parse_args()
return args.filename
def main():
colors = vtkNamedColors()
filename = get_program_parameters()
imageData = vtkImageData()
imageData.SetDimensions(3, 4, 5)
imageData.AllocateScalars(VTK_DOUBLE, 1)
dims = imageData.GetDimensions()
# Fill every entry of the image data with '2.0'
for z in range(dims[2]):
for y in range(dims[1]):
for x in range(dims[0]):
imageData.SetScalarComponentFromDouble(x, y, z, 0, 2.0)
writer = vtkXMLImageDataWriter()
writer.SetFileName(filename)
writer.SetInputData(imageData)
writer.Write()
# Read the file (to test that it was written correctly)
reader = vtkXMLImageDataReader()
reader.SetFileName(filename)
reader.Update()
# Convert the image to a polydata
imageDataGeometryFilter = vtkImageDataGeometryFilter()
imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort())
imageDataGeometryFilter.Update()
mapper = vtkPolyDataMapper()
mapper.SetInputConnection(imageDataGeometryFilter.GetOutputPort())
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetPointSize(3)
# Setup rendering
renderer = vtkRenderer()
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d('White'))
renderer.ResetCamera()
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderWindowInteractor.Initialize()
renderWindowInteractor.Start()
if __name__ == '__main__':
main()
EnhanceEdges
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkIOImage import vtkImageReader2Factory
from vtkmodules.vtkImagingColor import vtkImageMapToWindowLevelColors
from vtkmodules.vtkImagingCore import vtkImageCast
from vtkmodules.vtkImagingGeneral import vtkImageLaplacian
from vtkmodules.vtkImagingMath import vtkImageMathematics
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleImage
from vtkmodules.vtkRenderingCore import (
vtkImageActor,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
# colors = vtkNamedColors()
fileName = "D:/vtk/vtk-examples-master/src/Testing/Data/FullHead.mhd"
# Read the image.
readerFactory = 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 = vtkImageCast()
cast.SetInputConnection(reader.GetOutputPort())
cast.SetOutputScalarTypeToDouble()
cast.Update()
laplacian = vtkImageLaplacian()
laplacian.SetInputConnection(cast.GetOutputPort())
laplacian.SetDimensionality(3)
enhance = 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 = vtkImageMapToWindowLevelColors()
originalColor.SetWindow(colorWindow)
originalColor.SetLevel(colorLevel)
originalColor.SetInputConnection(reader.GetOutputPort())
originalActor = 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 = vtkImageMapToWindowLevelColors()
laplacianColor.SetWindow(1000)
laplacianColor.SetLevel(0)
laplacianColor.SetInputConnection(laplacian.GetOutputPort())
laplacianActor = vtkImageActor()
laplacianActor.GetMapper().SetInputConnection(laplacianColor.GetOutputPort())
laplacianActor.GetProperty().SetInterpolationTypeToNearest()
laplacianActor.SetDisplayExtent(originalActor.GetDisplayExtent())
enhancedColor = vtkImageMapToWindowLevelColors()
enhancedColor.SetWindow(colorWindow)
enhancedColor.SetLevel(colorLevel)
enhancedColor.SetInputConnection(enhance.GetOutputPort())
enhancedActor = vtkImageActor()
enhancedActor.GetMapper().SetInputConnection(enhancedColor.GetOutputPort())
enhancedActor.GetProperty().SetInterpolationTypeToNearest()
enhancedActor.SetDisplayExtent(originalActor.GetDisplayExtent())
# Setup the renderers.
originalRenderer = vtkRenderer()
originalRenderer.AddActor(originalActor)
laplacianRenderer = vtkRenderer()
laplacianRenderer.AddActor(laplacianActor)
enhancedRenderer = 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 = 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])
renderWindow.SetWindowName('EnhanceEdges')
renderWindowInteractor = vtkRenderWindowInteractor()
style = 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()
def get_program_parameters():
import argparse
description = 'High-pass filters can extract and enhance edges in an image.'
epilogue = '''
Subtraction of the Laplacian (middle) from the original image (left) results
in edge enhancement or a sharpening operation (right).
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('filename', help='FullHead.mhd.')
args = parser.parse_args()
return args.filename
if __name__ == '__main__':
main()