VTK官方示例

VTK官方示例

-vtk字體

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingFreeType
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (vtkCellArray,vtkPolyData
)
from vtkmodules.vtkRenderingCore import (vtkActor2D,vtkCoordinate,vtkPolyDataMapper2D,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer,vtkTextMapper,vtkTextProperty
)def main():font_size = 24# Create the text mappers and the associated Actor2Ds.# The font and text properties (except justification) are the same for# each single line mapper. Let's create a common text property objectsingleLineTextProp = vtkTextProperty()singleLineTextProp.SetFontSize(font_size)singleLineTextProp.SetFontFamilyToArial()singleLineTextProp.BoldOff()singleLineTextProp.ItalicOff()singleLineTextProp.ShadowOff()# The font and text properties (except justification) are the same for# each multi line mapper. Let's create a common text property objectmultiLineTextProp = vtkTextProperty()multiLineTextProp.ShallowCopy(singleLineTextProp)multiLineTextProp.BoldOn()multiLineTextProp.ItalicOn()multiLineTextProp.ShadowOn()multiLineTextProp.SetLineSpacing(0.8)colors = vtkNamedColors()# The text is on a single line and bottom-justified.singleLineTextB = vtkTextMapper()singleLineTextB.SetInput('Single line (bottom)')tprop = singleLineTextB.GetTextProperty()tprop.ShallowCopy(singleLineTextProp)tprop.SetVerticalJustificationToBottom()tprop.SetColor(colors.GetColor3d('Tomato'))singleLineTextActorB = vtkActor2D()singleLineTextActorB.SetMapper(singleLineTextB)singleLineTextActorB.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()singleLineTextActorB.GetPositionCoordinate().SetValue(0.05, 0.85)# The text is on a single line and center-justified (vertical justification).singleLineTextC = vtkTextMapper()singleLineTextC.SetInput('Single line (centered)')tprop = singleLineTextC.GetTextProperty()tprop.ShallowCopy(singleLineTextProp)tprop.SetVerticalJustificationToCentered()tprop.SetColor(colors.GetColor3d('DarkGreen'))singleLineTextActorC = vtkActor2D()singleLineTextActorC.SetMapper(singleLineTextC)singleLineTextActorC.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()singleLineTextActorC.GetPositionCoordinate().SetValue(0.05, 0.75)# The text is on a single line and top-justified.singleLineTextT = vtkTextMapper()singleLineTextT.SetInput('Single line (top)')tprop = singleLineTextT.GetTextProperty()tprop.ShallowCopy(singleLineTextProp)tprop.SetVerticalJustificationToTop()tprop.SetColor(colors.GetColor3d('Peacock'))singleLineTextActorT = vtkActor2D()singleLineTextActorT.SetMapper(singleLineTextT)singleLineTextActorT.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()singleLineTextActorT.GetPositionCoordinate().SetValue(0.05, 0.65)# The text is on multiple lines and left- and top-justified.textMapperL = vtkTextMapper()textMapperL.SetInput('This is\nmulti-line\ntext output\n(left-top)')tprop = textMapperL.GetTextProperty()tprop.ShallowCopy(multiLineTextProp)tprop.SetJustificationToLeft()tprop.SetVerticalJustificationToTop()tprop.SetColor(colors.GetColor3d('Tomato'))textActorL = vtkActor2D()textActorL.SetMapper(textMapperL)textActorL.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()textActorL.GetPositionCoordinate().SetValue(0.05, 0.5)# The text is on multiple lines and center-justified (both horizontal and vertical).textMapperC = vtkTextMapper()textMapperC.SetInput('This is\nmulti-line\ntext output\n(centered)')tprop = textMapperC.GetTextProperty()tprop.ShallowCopy(multiLineTextProp)tprop.SetJustificationToCentered()tprop.SetVerticalJustificationToCentered()tprop.SetColor(colors.GetColor3d('DarkGreen'))textActorC = vtkActor2D()textActorC.SetMapper(textMapperC)textActorC.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()textActorC.GetPositionCoordinate().SetValue(0.5, 0.5)# The text is on multiple lines and right- and bottom-justified.textMapperR = vtkTextMapper()textMapperR.SetInput('This is\nmulti-line\ntext output\n(right-bottom)')tprop = textMapperR.GetTextProperty()tprop.ShallowCopy(multiLineTextProp)tprop.SetJustificationToRight()tprop.SetVerticalJustificationToBottom()tprop.SetColor(colors.GetColor3d('Peacock'))textActorR = vtkActor2D()textActorR.SetMapper(textMapperR)textActorR.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()textActorR.GetPositionCoordinate().SetValue(0.95, 0.5)# Draw the grid to demonstrate the placement of the text.# Set up the necessary points.Pts = vtkPoints()Pts.InsertNextPoint(0.05, 0.0, 0.0)Pts.InsertNextPoint(0.05, 1.0, 0.0)Pts.InsertNextPoint(0.5, 0.0, 0.0)Pts.InsertNextPoint(0.5, 1.0, 0.0)Pts.InsertNextPoint(0.95, 0.0, 0.0)Pts.InsertNextPoint(0.95, 1.0, 0.0)Pts.InsertNextPoint(0.0, 0.5, 0.0)Pts.InsertNextPoint(1.0, 0.5, 0.0)Pts.InsertNextPoint(0.00, 0.85, 0.0)Pts.InsertNextPoint(0.50, 0.85, 0.0)Pts.InsertNextPoint(0.00, 0.75, 0.0)Pts.InsertNextPoint(0.50, 0.75, 0.0)Pts.InsertNextPoint(0.00, 0.65, 0.0)Pts.InsertNextPoint(0.50, 0.65, 0.0)# Set up the lines that use these points.Lines = vtkCellArray()Lines.InsertNextCell(2)Lines.InsertCellPoint(0)Lines.InsertCellPoint(1)Lines.InsertNextCell(2)Lines.InsertCellPoint(2)Lines.InsertCellPoint(3)Lines.InsertNextCell(2)Lines.InsertCellPoint(4)Lines.InsertCellPoint(5)Lines.InsertNextCell(2)Lines.InsertCellPoint(6)Lines.InsertCellPoint(7)Lines.InsertNextCell(2)Lines.InsertCellPoint(8)Lines.InsertCellPoint(9)Lines.InsertNextCell(2)Lines.InsertCellPoint(10)Lines.InsertCellPoint(11)Lines.InsertNextCell(2)Lines.InsertCellPoint(12)Lines.InsertCellPoint(13)# Create a grid that uses these points and lines.Grid = vtkPolyData()Grid.SetPoints(Pts)Grid.SetLines(Lines)# Set up the coordinate system.normCoords = vtkCoordinate()normCoords.SetCoordinateSystemToNormalizedViewport()# Set up the mapper and actor (2D) for the grid.mapper = vtkPolyDataMapper2D()mapper.SetInputData(Grid)mapper.SetTransformCoordinate(normCoords)gridActor = vtkActor2D()gridActor.SetMapper(mapper)gridActor.GetProperty().SetColor(colors.GetColor3d('DimGray'))# Create the Renderer, RenderWindow, and RenderWindowInteractorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)interactor = vtkRenderWindowInteractor()interactor.SetRenderWindow(renderWindow)# Add the actors to the renderer set the background and size zoom in closer to the image renderrenderer.AddActor2D(textActorL)renderer.AddActor2D(textActorC)renderer.AddActor2D(textActorR)renderer.AddActor2D(singleLineTextActorB)renderer.AddActor2D(singleLineTextActorC)renderer.AddActor2D(singleLineTextActorT)renderer.AddActor2D(gridActor)renderer.SetBackground(colors.GetColor3d('Silver'))renderWindow.SetSize(640, 480)renderer.GetActiveCamera().Zoom(1.5)# Enable user interface interactorinteractor.Initialize()renderWindow.SetWindowName('MultiLineText')renderWindow.Render()interactor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Text origin

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersGeneral import vtkAxes
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera
from vtkmodules.vtkRenderingCore import (vtkActor,vtkFollower,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)
from vtkmodules.vtkRenderingFreeType import vtkVectorTextdef main():colors = vtkNamedColors()# Create the axes and the associated mapper and actor.axes = vtkAxes()axes.SetOrigin(0, 0, 0)axesMapper = vtkPolyDataMapper()axesMapper.SetInputConnection(axes.GetOutputPort())axesActor = vtkActor()axesActor.SetMapper(axesMapper)# Create the 3D text and the associated mapper and follower (a type of actor).  Position the text so it is displayed over the origin of the axes.atext = vtkVectorText()atext.SetText('Origin')textMapper = vtkPolyDataMapper()textMapper.SetInputConnection(atext.GetOutputPort())textActor = vtkFollower()textActor.SetMapper(textMapper)textActor.SetScale(0.2, 0.2, 0.2)textActor.AddPosition(0, -0.1, 0)textActor.GetProperty().SetColor(colors.GetColor3d('Peacock'))# Create the Renderer, RenderWindow, and RenderWindowInteractor.renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindow.SetSize(640, 480)interactor = vtkRenderWindowInteractor()interactor.SetRenderWindow(renderWindow)style = vtkInteractorStyleTrackballCamera()interactor.SetInteractorStyle(style)# Add the actors to the renderer.renderer.AddActor(axesActor)renderer.AddActor(textActor)renderer.SetBackground(colors.GetColor3d('Silver'))# Zoom in closer.renderer.ResetCamera()renderer.GetActiveCamera().Zoom(1.6)renderer.SetBackground(colors.GetColor3d('Silver'))# Reset the clipping range of the camera; set the camera of the follower; render.renderer.ResetCameraClippingRange()textActor.SetCamera(renderer.GetActiveCamera())interactor.Initialize()renderWindow.SetWindowName('TextOrigin')renderWindow.Render()interactor.Start()if __name__ == '__main__':main()

在这里插入图片描述

將actor保存成vtk文件

#!/usr/bin/env pythonfrom vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkIOXML import vtkXMLPolyDataWriterdef main():# setup spheresphereSource = vtkSphereSource()sphereSource.Update()polydata = vtkPolyData()polydata.ShallowCopy(sphereSource.GetOutput())normals = polydata.GetPointData().GetNormals()normals.SetName('TestN')writer = vtkXMLPolyDataWriter()writer.SetFileName('Test.vtp')writer.SetInputData(polydata)writer.Write()if __name__ == '__main__':main()结果:'Test.vtp'
<?xml version="1.0"?>
<VTKFile type="PolyData" version="0.1" byte_order="LittleEndian" header_type="UInt32" compressor="vtkZLibDataCompressor"><PolyData><Piece NumberOfPoints="50"                   NumberOfVerts="0"                    NumberOfLines="0"                    NumberOfStrips="0"                    NumberOfPolys="96"                  ><PointData Normals="TestN"><DataArray type="Float32" Name="TestN" NumberOfComponents="3" format="appended" RangeMin="0.99999997719"        RangeMax="1.000000013"          offset="0"                   /></PointData><CellData></CellData><Points><DataArray type="Float32" Name="Points" NumberOfComponents="3" format="appended" RangeMin="0.49999998859"        RangeMax="0.50000000651"        offset="336"                 /></Points><Verts><DataArray type="Int64" Name="connectivity" format="appended" RangeMin=""                     RangeMax=""                     offset="668"                 /><DataArray type="Int64" Name="offsets" format="appended" RangeMin=""                     RangeMax=""                     offset="684"                 /></Verts><Lines><DataArray type="Int64" Name="connectivity" format="appended" RangeMin=""                     RangeMax=""                     offset="700"                 /><DataArray type="Int64" Name="offsets" format="appended" RangeMin=""                     RangeMax=""                     offset="716"                 /></Lines><Strips><DataArray type="Int64" Name="connectivity" format="appended" RangeMin=""                     RangeMax=""                     offset="732"                 /><DataArray type="Int64" Name="offsets" format="appended" RangeMin=""                     RangeMax=""                     offset="748"                 /></Strips><Polys><DataArray type="Int64" Name="connectivity" format="appended" RangeMin=""                     RangeMax=""                     offset="764"                 /><DataArray type="Int64" Name="offsets" format="appended" RangeMin=""                     RangeMax=""                     offset="1240"                /></Polys></Piece></PolyData><AppendedData encoding="base64">_AQAAAACAAABYAgAA6AAAAA==eJxNkaEKAkEURReLyGLUJBhcLSL4BTvV5BfYBKsWg1pMil2jzfUXbO+2xegHiFjEL9gud9jBO/Dgwrx75s57URTO1kV/jUrvlVJ9splr9Ub+rnpuu/dx5fX+OU1Fm/SoF/3GOWWR89jVfZHT3Ax9kSPapEe9cHHRIZecbz5J+B45xfWQMAc5ok161EumSR5IHkgeSB5InuDlH83Fy6ScD775Mynng+Ja65bzCdqkR72BaZIHkgeSB5IHkodezO+3C7nkDE7djO+Rs1iPM+YgR7RJj3rDzE32BdkXZF+QfUH25Tk/IcXzPQ==AQAAAACAAABYAgAA5gAAAA==eJxNkSEOwlAQRBsMIWhQoNrUEDSK9iKEK4DBgIcgcCAJpq3mAn9wTRXhABUkBHqCChzMTwvTZJMRO+9Pdxzn94V/6Vwa/jSgeMavoOdnVjePp+C+f1u9yR9j0UZ2IF4MOv2AQ85tvbNDTnd1tkOOaCM76kXYXrjkklOkucv3yCmTlscc5Ig2sqNeMiF5IHkgeSB5IHlqL//xyy3d6j4o0olX3QdlsvWq+9TayI56ayYkDyQPJA8kDyQPvZhlo4hccoaHOOJ75MyX14g5yBFtZEe99c0hfUH6gvQF6QvSl+V8AO4bFuI=AAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAQAAAACAAAAACQAAUgEAAA==eJxdz0VuQ1EUBNHEEGZmh+ww7X9zGeSfQepNrqrUT+oeLf29taX/D+/E46N4fBGPb+PxIh6/x+NR/Opwl4e7ncsf5vLnufwsl5/n8m+5/E8ur7c94+Gux+O15CbD3YjH68lNh7sZjzeSWxnuVjzeTM6e7Xjsnx367cbjneT024vHu8nptx+P95LT7yAe7ydn12E89s8O/Y7j8VFy+p3E4+Pk9DuNxyfJ6XcWj0+Ts+s8Hvtnh36X8fgiOf2u4vFlcvpdx+Or5PS7icfXydk1i8f+2aHfXTy+TU6/+3h8l5x+D/H4Pjn9HuPxQ3J2zeOxf3bo9xSPF8np9xyPn5LT7yUePyen32s8fknOrrd47J8d+n3E4/fk9PuMxx/J6fcVjz+T0+87Hn8lZ9dPPPbPDv3G8XiUnH6TeDxOTr9pPJ4kp99KPJ4mZ9dqPPbvF4aPGyE=AQAAAACAAAAAAwAAyAAAAA==eJwtxVtEAwAAAMAeltKUTWlKKSIiRsSIMcYYERExYoyIiIgYY0RERESMETEiIiIiIiJGjBgjIsaIiKiP3f1cd0dbj/sc9KDDHnbEY57wlKc941nPOep5LzjmRcedcNIpp73kZa941WvOeN1Z57zhTW952zve9Z7zLrjofR/40Ec+9olPfeaSyz73hSu+9JWvfeNb3/neD370k5/94qpfXfOb62743R/+dNMtf/nbP/71n7s62wfc634POOQhj3jU4570P6sgK5w=</AppendedData>
</VTKFile>

vtkCompositePolyDataMapper和vtkMultiBlockDataSet将多个数据绑定成一个

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkMultiBlockDataSet
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkCompositeDataDisplayAttributes,vtkCompositePolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Create Sphere 1.sphere1 = vtkSphereSource()sphere1.SetRadius(3)sphere1.SetCenter(0, 0, 0)sphere1.Update()# Create Sphere 2.sphere2 = vtkSphereSource()sphere2.SetRadius(2)sphere2.SetCenter(2, 0, 0)sphere2.Update()mbds = vtkMultiBlockDataSet()mbds.SetNumberOfBlocks(3)mbds.SetBlock(0, sphere1.GetOutput())# Leave block 1 NULL.  NULL blocks are valid and should be handled by# algorithms that process multiblock datasets.  Especially when# running in parallel where the blocks owned by other processes are# NULL in this process.mbds.SetBlock(2, sphere2.GetOutput())# Use vtkCompositePolyDataMapper2 if VTK Version < 90020230516mapper = vtkCompositePolyDataMapper()mapper.SetInputDataObject(mbds)cdsa = vtkCompositeDataDisplayAttributes()mapper.SetCompositeDataDisplayAttributes(cdsa)# You can use the vtkCompositeDataDisplayAttributes to set the color,# opacity and visibiliy of individual blocks of the multiblock dataset.# Attributes are mapped by block pointers (vtkDataObject*), so these can# be queried by their flat index through a convenience function in the# attribute class (vtkCompositeDataDisplayAttributes::DataObjectFromIndex).# Alternatively, one can set attributes directly through the mapper using# flat indices.## This sets the block at flat index 3 red# Note that the index is the flat index in the tree, so the whole multiblock# is index 0 and the blocks are flat indexes 1, 2 and 3.  This affects# the block returned by mbds.GetBlock(2).mapper.SetBlockColor(3, colors.GetColor3d('Red'))# Color the spheres.mapper.SetBlockColor(1, colors.GetColor3d('LavenderBlush'))mapper.SetBlockColor(2, colors.GetColor3d('Lavender'))actor = vtkActor()actor.SetMapper(mapper)# Create the Renderer, RenderWindow, and RenderWindowInteractor.renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Enable user interface interactor.renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('SteelBlue'))renderWindow.SetWindowName('CompositePolyDataMapper')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

vtkMultiBlockDataSet

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkMultiBlockDataSet# vtkExtractEdges moved from vtkFiltersExtraction to vtkFiltersCore in
# VTK commit d9981b9aeb93b42d1371c6e295d76bfdc18430bd
try:from vtkmodules.vtkFiltersCore import vtkExtractEdges
except ImportError:from vtkmodules.vtkFiltersExtraction import vtkExtractEdges
from vtkmodules.vtkFiltersGeometry import vtkCompositeDataGeometryFilter
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# PART 1 Make some Data.# Make a tree.root = vtkMultiBlockDataSet()branch = vtkMultiBlockDataSet()root.SetBlock(0, branch)# Make some leaves.leaf1 = vtkSphereSource()leaf1.SetCenter(0, 0, 0)leaf1.Update()branch.SetBlock(0, leaf1.GetOutput())leaf2 = vtkSphereSource()leaf2.SetCenter(1.75, 2.5, 0)leaf2.SetRadius(1.5)leaf2.Update()branch.SetBlock(1, leaf2.GetOutput())leaf3 = vtkSphereSource()leaf3.SetCenter(4, 0, 0)leaf3.SetRadius(2)leaf3.Update()root.SetBlock(1, leaf3.GetOutput())# PART 2 Do something with the data# a non composite aware filter, the pipeline will iterateedges = vtkExtractEdges()edges.SetInputData(root)# PART 3 Show the data# also demonstrate a composite aware filter# this filter aggregates all blocks into one polydata# this is handy for display, although fairly limited.polydata = vtkCompositeDataGeometryFilter()polydata.SetInputConnection(edges.GetOutputPort())# Create the Renderer, RenderWindow, and RenderWindowInteractor.renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)mapper = vtkPolyDataMapper()mapper.SetInputConnection(0, polydata.GetOutputPort(0))actor = vtkActor()actor.GetProperty().SetColor(colors.GetColor3d('Yellow'))actor.GetProperty().SetLineWidth(2)actor.SetMapper(mapper)# Enable user interface interactor.renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('CornflowerBlue'))renderWindow.SetWindowName('MultiBlockDataSet')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

vtkOverlappingAMR

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkFloatArray
from vtkmodules.vtkCommonDataModel import (vtkAMRBox,vtkOverlappingAMR,vtkSphere,vtkUniformGrid
)
from vtkmodules.vtkFiltersCore import vtkContourFilter
from vtkmodules.vtkFiltersGeometry import vtkCompositeDataGeometryFilter
from vtkmodules.vtkFiltersModeling import vtkOutlineFilter
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def MakeScalars(dims, origin, spacing, scalars):# Implicit function used to compute scalarssphere = vtkSphere()sphere.SetRadius(3)sphere.SetCenter(5, 5, 5)scalars.SetNumberOfTuples(dims[0] * dims[1] * dims[2])for k in range(0, dims[2]):z = origin[2] + spacing[2] * kfor j in range(0, dims[1]):y = origin[1] + spacing[1] * jfor i in range(0, dims[0]):x = origin[0] + spacing[0] * iscalars.SetValue(k * dims[0] * dims[1] + j * dims[0] + i, sphere.EvaluateFunction(x, y, z))def main():colors = vtkNamedColors()# Create and populate the AMR dataset# The dataset should look like# Level 0#   uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9) # Level 1 - refinement ratio : 2#   uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9)#   uniform grid, dimensions 11, 11, 11, AMR box (10, 10, 10) - (19, 19, 19)# Use MakeScalars() above to fill the scalar arraysamr = vtkOverlappingAMR()blocksPerLevel = [1, 2]amr.Initialize(2, blocksPerLevel)origin = [0.0, 0.0, 0.0]spacing = [1.0, 1.0, 1.0]dims = [11, 11, 11]ug1 = vtkUniformGrid()# Geometryug1.SetOrigin(origin)ug1.SetSpacing(spacing)ug1.SetDimensions(dims)# Datascalars = vtkFloatArray()ug1.GetPointData().SetScalars(scalars)MakeScalars(dims, origin, spacing, scalars)lo = [0, 0, 0]hi = [9, 9, 9]box1 = vtkAMRBox()amr.SetAMRBox(0, 0, box1)amr.SetDataSet(0, 0, ug1)spacing2 = [0.5, 0.5, 0.5]ug2 = vtkUniformGrid()# Geometryug2.SetOrigin(origin)ug2.SetSpacing(spacing2)ug2.SetDimensions(dims)# Datascalars2 = vtkFloatArray()ug2.GetPointData().SetScalars(scalars2)MakeScalars(dims, origin, spacing2, scalars2)lo2 = [0, 0, 0]hi2 = [9, 9, 9]box2 = vtkAMRBox()amr.SetAMRBox(1, 0, box2)amr.SetDataSet(1, 0, ug2)origin3 = [5, 5, 5]ug3 = vtkUniformGrid()# Geometryug3.SetOrigin(origin3)ug3.SetSpacing(spacing2)ug3.SetDimensions(dims)# Datascalars3 = vtkFloatArray()ug3.GetPointData().SetScalars(scalars3)MakeScalars(dims, origin3, spacing2, scalars3)lo3 = [10, 10, 10]hi3 = [19, 19, 19]box3 = vtkAMRBox()amr.SetAMRBox(1, 1, box3)amr.SetDataSet(1, 1, ug3)amr.SetRefinementRatio(0, 2)# Render the amr data here.of = vtkOutlineFilter()of.SetInputData(amr)geomFilter = vtkCompositeDataGeometryFilter()geomFilter.SetInputConnection(of.GetOutputPort())# Create an iso-surface - at 10.cf = vtkContourFilter()cf.SetInputData(amr)cf.SetNumberOfContours(1)cf.SetValue(0, 10.0)geomFilter2 = vtkCompositeDataGeometryFilter()geomFilter2.SetInputConnection(cf.GetOutputPort())# Create the render window, renderer, and interactor.aren = vtkRenderer()renWin = vtkRenderWindow()renWin.AddRenderer(aren)iren = vtkRenderWindowInteractor()iren.SetRenderWindow(renWin)# Associate the geometry with a mapper and the mapper to an actor.mapper = vtkPolyDataMapper()mapper.SetInputConnection(of.GetOutputPort())actor1 = vtkActor()actor1.GetProperty().SetColor(colors.GetColor3d('Yellow'))actor1.SetMapper(mapper)# Associate the geometry with a mapper and the mapper to an actor.mapper2 = vtkPolyDataMapper()mapper2.SetInputConnection(geomFilter2.GetOutputPort())actor2 = vtkActor()actor2.SetMapper(mapper2)# Add the actor to the renderer and start handling events.aren.AddActor(actor1)aren.AddActor(actor2)aren.SetBackground(colors.GetColor3d('CornflowerBlue'))renWin.SetWindowName('OverlappingAMR')renWin.Render()iren.Start()if __name__ == '__main__':main()

在这里插入图片描述

vtkLoopSubdivisionFilter Use a filter to smooth the data (will add triangles and smooth).

#!/usr/bin/env pythonimport numpy as np
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonComputationalGeometry import vtkParametricSpline
from vtkmodules.vtkCommonCore import (mutable,vtkPoints,vtkUnsignedCharArray
)
from vtkmodules.vtkCommonDataModel import (vtkCellArray,vtkCellLocator,vtkPolyData,vtkTriangle
)
from vtkmodules.vtkFiltersCore import vtkCleanPolyData
from vtkmodules.vtkFiltersModeling import vtkLoopSubdivisionFilter
from vtkmodules.vtkFiltersSources import vtkParametricFunctionSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():named_colors = vtkNamedColors()# Make a 32 x 32 grid.size = 32# Define z values for the topography.# Comment out the following line if you want a different random#  distribution each time the script is run.np.random.seed(3)topography = np.random.randint(0, 5, (size, size))# Define points, triangles and colorscolors = vtkUnsignedCharArray()colors.SetNumberOfComponents(3)points = vtkPoints()triangles = vtkCellArray()# Build the meshgrid manually.count = 0for i in range(size - 1):for j in range(size - 1):z1 = topography[i][j]z2 = topography[i][j + 1]z3 = topography[i + 1][j]# Triangle 1points.InsertNextPoint(i, j, z1)points.InsertNextPoint(i, (j + 1), z2)points.InsertNextPoint((i + 1), j, z3)triangle = vtkTriangle()triangle.GetPointIds().SetId(0, count)triangle.GetPointIds().SetId(1, count + 1)triangle.GetPointIds().SetId(2, count + 2)triangles.InsertNextCell(triangle)z1 = topography[i][j + 1]z2 = topography[i + 1][j + 1]z3 = topography[i + 1][j]# Triangle 2points.InsertNextPoint(i, (j + 1), z1)points.InsertNextPoint((i + 1), (j + 1), z2)points.InsertNextPoint((i + 1), j, z3)triangle = vtkTriangle()triangle.GetPointIds().SetId(0, count + 3)triangle.GetPointIds().SetId(1, count + 4)triangle.GetPointIds().SetId(2, count + 5)count += 6triangles.InsertNextCell(triangle)# Add some color.r = [int(i / float(size) * 255), int(j / float(size) * 255), 0]colors.InsertNextTypedTuple(r)colors.InsertNextTypedTuple(r)colors.InsertNextTypedTuple(r)colors.InsertNextTypedTuple(r)colors.InsertNextTypedTuple(r)colors.InsertNextTypedTuple(r)# Create a polydata object.trianglePolyData = vtkPolyData()# Add the geometry and topology to the polydata.trianglePolyData.SetPoints(points)trianglePolyData.GetPointData().SetScalars(colors)trianglePolyData.SetPolys(triangles)# Clean the polydata so that the edges are shared!cleanPolyData = vtkCleanPolyData()cleanPolyData.SetInputData(trianglePolyData)# Use a filter to smooth the data (will add triangles and smooth).smooth_loop = vtkLoopSubdivisionFilter()smooth_loop.SetNumberOfSubdivisions(3)smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())# Create a mapper and actor for smoothed dataset.mapper = vtkPolyDataMapper()mapper.SetInputConnection(smooth_loop.GetOutputPort())actor_loop = vtkActor()actor_loop.SetMapper(mapper)actor_loop.GetProperty().SetInterpolationToFlat()# Update the pipeline so that vtkCellLocator finds cells!smooth_loop.Update()# Define a cellLocator to be able to compute intersections between lines.# and the surfacelocator = vtkCellLocator()locator.SetDataSet(smooth_loop.GetOutput())locator.BuildLocator()maxloop = 1000dist = 20.0 / maxlooptolerance = 0.001# Make a list of points. Each point is the intersection of a vertical line# defined by p1 and p2 and the surface.points = vtkPoints()for i in range(maxloop):p1 = [2 + i * dist, 16, -1]p2 = [2 + i * dist, 16, 6]# Outputs (we need only pos which is the x, y, z position# of the intersection)t = mutable(0)pos = [0.0, 0.0, 0.0]pcoords = [0.0, 0.0, 0.0]subId = mutable(0)locator.IntersectWithLine(p1, p2, tolerance, t, pos, pcoords, subId)# Add a slight offset in z.pos[2] += 0.01# Add the x, y, z position of the intersection.points.InsertNextPoint(pos)# Create a spline and add the pointsspline = vtkParametricSpline()spline.SetPoints(points)functionSource = vtkParametricFunctionSource()functionSource.SetUResolution(maxloop)functionSource.SetParametricFunction(spline)# Map the splinemapper = vtkPolyDataMapper()mapper.SetInputConnection(functionSource.GetOutputPort())# Define the line actoractor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetColor(named_colors.GetColor3d('Red'))actor.GetProperty().SetLineWidth(3)# Visualizerenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add actors and renderrenderer.AddActor(actor)renderer.AddActor(actor_loop)renderer.SetBackground(named_colors.GetColor3d('Cornsilk'))renderWindow.SetSize(800, 800)renderWindow.Render()renderer.GetActiveCamera().SetPosition(-32.471276, 53.258788, 61.209332)renderer.GetActiveCamera().SetFocalPoint(15.500000, 15.500000, 2.000000)renderer.GetActiveCamera().SetViewUp(0.348057, -0.636740, 0.688055)renderer.ResetCameraClippingRange()renderWindow.SetWindowName('LineOnMesh')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

mesh label image color

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (vtkLookupTable,vtkVersion
)
from vtkmodules.vtkFiltersCore import (vtkPolyDataNormals,vtkWindowedSincPolyDataFilter
)
from vtkmodules.vtkFiltersGeneral import (vtkDiscreteFlyingEdges3D,vtkDiscreteMarchingCubes
)
from vtkmodules.vtkIOImage import vtkMetaImageReader
from vtkmodules.vtkImagingCore import vtkExtractVOI
from vtkmodules.vtkRenderingCore import (vtkColorTransferFunction,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)
from vtkmodules.vtkRenderingLOD import vtkLODActordef main():# vtkFlyingEdges3D was introduced in VTK >= 8.2use_flying_edges = vtk_version_ok(8, 2, 0)colors = vtkNamedColors()#ifn, index = get_program_parameters()ifn = "D:/vtk/vtk-examples-master/src/Testing/Data/labels.mhd"index = 0;# Prepare to read the file.reader_volume = vtkMetaImageReader()reader_volume.SetFileName(ifn)reader_volume.Update()# Extract the region of interest.voi = vtkExtractVOI()voi.SetInputConnection(reader_volume.GetOutputPort())voi.SetVOI(0, 517, 0, 228, 0, 392)voi.SetSampleRate(1, 1, 1)voi.Update()  # Necessary for GetScalarRange().srange = voi.GetOutput().GetScalarRange()  # Needs Update() before!print('Range', srange)# Prepare surface generation.# For label images.if use_flying_edges:try:contour = vtkDiscreteFlyingEdges3D()except AttributeError:contour = vtkDiscreteMarchingCubes()else:contour = vtkDiscreteMarchingCubes()contour.SetInputConnection(voi.GetOutputPort())# contour.ComputeNormalsOn()print('Doing label', index)contour.SetValue(0, index)contour.Update()  # Needed for GetNumberOfPolys()!!!smoother = vtkWindowedSincPolyDataFilter()smoother.SetInputConnection(contour.GetOutputPort())smoother.SetNumberOfIterations(30)  # This has little effect on the error!# smoother.BoundarySmoothingOff()# smoother.FeatureEdgeSmoothingOff()# smoother.SetFeatureAngle(120.0)# smoother.SetPassBand(0.001)        # This increases the error a lot!smoother.NonManifoldSmoothingOn()smoother.NormalizeCoordinatesOn()smoother.GenerateErrorScalarsOn()# smoother.GenerateErrorVectorsOn()smoother.Update()# Find min and max of the smoother error.se_range = smoother.GetOutput().GetPointData().GetScalars().GetRange()print('Smoother error range:', se_range)if se_range[1] > 1:print('Big smoother error: min/max:', se_range[0], se_range[1])lut = get_diverging_lut(4)# Calculate cell normals.normals = vtkPolyDataNormals()normals.SetInputConnection(smoother.GetOutputPort())normals.ComputeCellNormalsOn()normals.ComputePointNormalsOff()normals.ConsistencyOn()normals.AutoOrientNormalsOn()normals.Update()  # Creates vtkPolyData.normals.SetFeatureAngle(60.0)mapper = vtkPolyDataMapper()# mapper.SetInputConnection(smoother.GetOutputPort()) # This has no normals.mapper.SetInputConnection(normals.GetOutputPort())  # This is better for visibility.)mapper.ScalarVisibilityOn()  # Show colour.mapper.SetScalarRange(se_range)# mapper.SetScalarModeToUseCellData() # Contains the label eg. 31mapper.SetScalarModeToUsePointData()  # The smoother error relates to the verts.mapper.SetLookupTable(lut)# Take the isosurface data and create geometry.actor = vtkLODActor()actor.SetNumberOfCloudPoints(100000)actor.SetMapper(mapper)# Create the renderer.ren = vtkRenderer()ren.SetBackground(colors.GetColor3d('DimGray'))ren.AddActor(actor)# Create a window for the renderer of size 600X600ren_win = vtkRenderWindow()ren_win.AddRenderer(ren)ren_win.SetSize(600, 600)ren_win.SetWindowName('MeshLabelImageColor')ren_win.Render()# Set a user interface interactor for the render window.iren = vtkRenderWindowInteractor()iren.SetRenderWindow(ren_win)# Start the initialization and rendering.iren.Initialize()iren.Start()def get_program_parameters():import argparsedescription = 'MeshLabelImageColor.'epilogue = '''Takes a label image in Meta format and meshes a single label of it.'''parser = argparse.ArgumentParser(description=description, epilog=epilogue)parser.add_argument('filename', help='labels.mhd')parser.add_argument('label', nargs='?', const=1, type=int, default=31, help='The label to use e.g 31')args = parser.parse_args()return args.filename, args.labeldef get_diverging_lut(ct=0):"""See: [Diverging Color Maps for Scientific Visualization](https://www.kennethmoreland.com/color-maps/):param ct: The index of the color map to use.:return: The lookup table."""cm = dict()# Start point = 0.0, mid point = 0.5 and end point = 1.0.# Each value is a list with three sublists corresponding to the start point,# mid point and end point along with the rgb color values for the respective point.# cool to warmcm[0] = [[0.0, 0.230, 0.299, 0.754], [0.5, 0.865, 0.865, 0.865], [1.0, 0.706, 0.016, 0.150]]# purple to orangecm[1] = [[0.0, 0.436, 0.308, 0.631], [0.5, 0.865, 0.865, 0.865], [1.0, 0.759, 0.334, 0.046]]# green to purplecm[2] = [[0.0, 0.085, 0.532, 0.201], [0.5, 0.865, 0.865, 0.865], [1.0, 0.436, 0.308, 0.631]]# blue to browncm[3] = [[0.0, 0.217, 0.525, 0.910], [0.5, 0.865, 0.865, 0.865], [1.0, 0.677, 0.492, 0.093]]# green to redcm[4] = [[0.0, 0.085, 0.532, 0.201], [0.5, 0.865, 0.865, 0.865], [1.0, 0.758, 0.214, 0.233]]ct = abs(ct)if ct > len(cm) - 1:ct = 0print('The selected diverging color map is unavailable. Using the default cool to warm one.')ctf = vtkColorTransferFunction()ctf.SetColorSpaceToDiverging()for scheme in cm[ct]:ctf.AddRGBPoint(*scheme)table_size = 256lut = vtkLookupTable()lut.SetNumberOfTableValues(table_size)lut.Build()for i in range(0, table_size):rgba = list(ctf.GetColor(float(i) / table_size))rgba.append(1)lut.SetTableValue(i, rgba)return lutdef vtk_version_ok(major, minor, build):"""Check the VTK version.:param major: Requested major version.:param minor: Requested minor version.:param build: Requested build version.:return: True if the requested VTK version is >= the actual VTK version."""requested_version = (100 * int(major) + int(minor)) * 100000000 + int(build)ver = vtkVersion()actual_version = (100 * ver.GetVTKMajorVersion() + ver.GetVTKMinorVersion()) \* 100000000 + ver.GetVTKBuildVersion()if actual_version >= requested_version:return Trueelse:return Falseif __name__ == '__main__':main()

在这里插入图片描述

vtkParametricFunctionSource

# !/usr/bin/env python
# -*- coding: utf-8 -*-import vtkmodules.all as vtkdef main():colors = vtk.vtkNamedColors()colors.SetColor("BkgColor", [26, 51, 102, 255])parametricObjects = list()parametricObjects.append(vtk.vtkParametricBoy())parametricObjects.append(vtk.vtkParametricConicSpiral())parametricObjects.append(vtk.vtkParametricCrossCap())parametricObjects.append(vtk.vtkParametricDini())parametricObjects.append(vtk.vtkParametricEllipsoid())parametricObjects[-1].SetXRadius(0.5)parametricObjects[-1].SetYRadius(2.0)parametricObjects.append(vtk.vtkParametricEnneper())parametricObjects.append(vtk.vtkParametricFigure8Klein())parametricObjects.append(vtk.vtkParametricKlein())parametricObjects.append(vtk.vtkParametricMobius())parametricObjects[-1].SetRadius(2)parametricObjects[-1].SetMinimumV(-0.5)parametricObjects[-1].SetMaximumV(0.5)parametricObjects.append(vtk.vtkParametricRandomHills())parametricObjects[-1].AllowRandomGenerationOff()parametricObjects.append(vtk.vtkParametricRoman())parametricObjects.append(vtk.vtkParametricSuperEllipsoid())parametricObjects[-1].SetN1(0.5)parametricObjects[-1].SetN2(0.1)parametricObjects.append(vtk.vtkParametricSuperToroid())parametricObjects[-1].SetN1(0.2)parametricObjects[-1].SetN2(3.0)parametricObjects.append(vtk.vtkParametricTorus())parametricObjects.append(vtk.vtkParametricSpline())# Add some points to the parametric spline.inputPoints = vtk.vtkPoints()rng = vtk.vtkMinimalStandardRandomSequence()rng.SetSeed(8775070)for i in range(0, 10):rng.Next()x = rng.GetRangeValue(0.0, 1.0)rng.Next()y = rng.GetRangeValue(0.0, 1.0)rng.Next()z = rng.GetRangeValue(0.0, 1.0)inputPoints.InsertNextPoint(x, y, z)parametricObjects[-1].SetPoints(inputPoints)parametricFunctionSources = list()renderers = list()mappers = list()actors = list()textmappers = list()textactors = list()# Create one text property for alltextProperty = vtk.vtkTextProperty()textProperty.SetFontSize(12)textProperty.SetJustificationToCentered()backProperty = vtk.vtkProperty()backProperty.SetColor(colors.GetColor3d("Tomato"))# Create a parametric function source, renderer, mapper, and actor# for each objectfor i in range(0, len(parametricObjects)):parametricFunctionSources.append(vtk.vtkParametricFunctionSource())parametricFunctionSources[i].SetParametricFunction(parametricObjects[i])parametricFunctionSources[i].SetUResolution(51)parametricFunctionSources[i].SetVResolution(51)parametricFunctionSources[i].SetWResolution(51)parametricFunctionSources[i].Update()mappers.append(vtk.vtkPolyDataMapper())mappers[i].SetInputConnection(parametricFunctionSources[i].GetOutputPort())actors.append(vtk.vtkActor())actors[i].SetMapper(mappers[i])actors[i].GetProperty().SetColor(colors.GetColor3d("Banana"))actors[i].GetProperty().SetSpecular(.5)actors[i].GetProperty().SetSpecularPower(20)actors[i].SetBackfaceProperty(backProperty)textmappers.append(vtk.vtkTextMapper())textmappers[i].SetInput(parametricObjects[i].GetClassName())textmappers[i].SetTextProperty(textProperty)textactors.append(vtk.vtkActor2D())textactors[i].SetMapper(textmappers[i])textactors[i].SetPosition(100, 16)renderers.append(vtk.vtkRenderer())renderers[i].AddActor(actors[i])renderers[i].AddActor(textactors[i])renderers[i].SetBackground(colors.GetColor3d("BkgColor"))# Setup the viewportsxGridDimensions = 4yGridDimensions = 4rendererSize = 200renderWindow = vtk.vtkRenderWindow()renderWindow.SetWindowName("Parametric Objects Demonstration")renderWindow.SetSize(rendererSize * xGridDimensions, rendererSize * yGridDimensions)for row in range(0, yGridDimensions):for col in range(0, 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]if index > (len(actors) - 1):# Add a renderer even if there is no actor.# This makes the render window background all the same color.ren = vtk.vtkRenderer()ren.SetBackground(colors.GetColor3d("BkgColor"))ren.SetViewport(viewport)renderWindow.AddRenderer(ren)continuerenderers[index].SetViewport(viewport)renderers[index].ResetCamera()renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)renderers[index].GetActiveCamera().Zoom(0.9)renderers[index].ResetCameraClippingRange()renderWindow.AddRenderer(renderers[index])interactor = vtk.vtkRenderWindowInteractor()interactor.SetRenderWindow(renderWindow)renderWindow.Render()interactor.Start()if __name__ == '__main__':main()

![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/17f8039637cc4149866acee2798eaa70.png在这里插入图片描述

This example demonstrates how (1) to create an explicit structured grid and (2) to convert an explicit structured grid into an unstructured grid or vice versa.

#!/usr/bin/env python
# -*- coding: utf-8 -*-import vtkmodules.all as vtkdef main():colors = vtk.vtkNamedColors()colors.SetColor("BkgColor", [26, 51, 102, 255])parametricObjects = list()parametricObjects.append(vtk.vtkParametricBohemianDome())parametricObjects[-1].SetA(5.0)parametricObjects[-1].SetB(1.0)parametricObjects[-1].SetC(2.0)parametricObjects.append(vtk.vtkParametricBour())parametricObjects.append(vtk.vtkParametricCatalanMinimal())parametricObjects.append(vtk.vtkParametricHenneberg())parametricObjects.append(vtk.vtkParametricKuen())parametricObjects.append(vtk.vtkParametricPluckerConoid())parametricObjects.append(vtk.vtkParametricPseudosphere())parametricFunctionSources = list()renderers = list()mappers = list()actors = list()textmappers = list()textactors = list()# Create one text property for alltextProperty = vtk.vtkTextProperty()textProperty.SetFontSize(12)textProperty.SetJustificationToCentered()backProperty = vtk.vtkProperty()backProperty.SetColor(colors.GetColor3d("Tomato"))# Create a parametric function source, renderer, mapper, and actor# for each objectfor i in range(0, len(parametricObjects)):parametricFunctionSources.append(vtk.vtkParametricFunctionSource())parametricFunctionSources[i].SetParametricFunction(parametricObjects[i])parametricFunctionSources[i].Update()mappers.append(vtk.vtkPolyDataMapper())mappers[i].SetInputConnection(parametricFunctionSources[i].GetOutputPort())actors.append(vtk.vtkActor())actors[i].SetMapper(mappers[i])actors[i].GetProperty().SetColor(colors.GetColor3d("Banana"))actors[i].GetProperty().SetSpecular(.5)actors[i].GetProperty().SetSpecularPower(20)actors[i].SetBackfaceProperty(backProperty)textmappers.append(vtk.vtkTextMapper())textmappers[i].SetInput(parametricObjects[i].GetClassName())textmappers[i].SetTextProperty(textProperty)textactors.append(vtk.vtkActor2D())textactors[i].SetMapper(textmappers[i])textactors[i].SetPosition(100, 16)renderers.append(vtk.vtkRenderer())renderers[i].AddActor(actors[i])renderers[i].AddActor(textactors[i])renderers[i].SetBackground(colors.GetColor3d("BkgColor"))# Setup the viewportsxGridDimensions = 4yGridDimensions = 2rendererSize = 200renderWindow = vtk.vtkRenderWindow()renderWindow.SetWindowName("Parametric Objects Demonstration2")renderWindow.SetSize(rendererSize * xGridDimensions,rendererSize * yGridDimensions)for row in range(0, yGridDimensions):for col in range(0, 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]if index > (len(actors) - 1):# Add a renderer even if there is no actor.# This makes the render window background all the same color.ren = vtk.vtkRenderer()ren.SetBackground(colors.GetColor3d("BkgColor"))ren.SetViewport(viewport)renderWindow.AddRenderer(ren)continuerenderers[index].SetViewport(viewport)renderers[index].ResetCamera()renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)renderers[index].GetActiveCamera().Zoom(0.9)renderers[index].ResetCameraClippingRange()renderWindow.AddRenderer(renderers[index])interactor = vtk.vtkRenderWindowInteractor()interactor.SetRenderWindow(renderWindow)renderWindow.Render()interactor.Start()if __name__ == '__main__':main()

在这里插入图片描述

#!/usr/bin/env pythonimport numpy as np
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (vtkCellArray,vtkExplicitStructuredGrid
)
from vtkmodules.vtkFiltersCore import (vtkExplicitStructuredGridToUnstructuredGrid,vtkUnstructuredGridToExplicitStructuredGrid
)
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleRubberBandPick
from vtkmodules.vtkRenderingCore import (vtkActor,vtkDataSetMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def create_explicit_structured_grid(dimensions, spacing=(1, 1, 1)):"""Create an explicit structured grid.Parameters----------dimensions : tuple(int, int, int)The number of points in the I, J and K directions.spacing : tuple(int, int, int)The spacing between points in the I, J and K directions.Returns-------grid : vtkExplicitStructuredGridAn explicit structured grid."""ni, nj, nk = dimensionssi, sj, sk = spacingpoints = vtkPoints()for z in range(0, nk * sk, sk):for y in range(0, nj * sj, sj):for x in range(0, ni * si, si):points.InsertNextPoint((x, y, z))cells = vtkCellArray()for k in range(0, nk - 1):for j in range(0, nj - 1):for i in range(0, ni - 1):multi_index = ([i, i + 1, i + 1, i, i, i + 1, i + 1, i],[j, j, j + 1, j + 1, j, j, j + 1, j + 1],[k, k, k, k, k + 1, k + 1, k + 1, k + 1])pts = np.ravel_multi_index(multi_index, dimensions, order='F')cells.InsertNextCell(8, pts)grid = vtkExplicitStructuredGrid()grid.SetDimensions(ni, nj, nk)grid.SetPoints(points)grid.SetCells(cells)return griddef convert_to_unstructured_grid(grid):"""Convert explicit structured grid to unstructured grid.Parameters----------grid : vtkExplicitStructuredGridAn explicit structured grid.Returns-------vtkUnstructuredGridAn unstructured grid."""converter = vtkExplicitStructuredGridToUnstructuredGrid()converter.SetInputData(grid)converter.Update()return converter.GetOutput()def convert_to_explicit_structured_grid(grid):"""Convert unstructured grid to explicit structured grid.Parameters----------grid : UnstructuredGridAn unstructured grid.Returns-------vtkExplicitStructuredGridAn explicit structured grid. The ``'BLOCK_I'``, ``'BLOCK_J'`` and``'BLOCK_K'`` cell arrays are required."""converter = vtkUnstructuredGridToExplicitStructuredGrid()converter.SetInputData(grid)converter.SetInputArrayToProcess(0, 0, 0, 1, 'BLOCK_I')converter.SetInputArrayToProcess(1, 0, 0, 1, 'BLOCK_J')converter.SetInputArrayToProcess(2, 0, 0, 1, 'BLOCK_K')converter.Update()return converter.GetOutput()def main():grid = create_explicit_structured_grid((5, 6, 7), (20, 10, 1))grid = convert_to_unstructured_grid(grid)grid = convert_to_explicit_structured_grid(grid)mapper = vtkDataSetMapper()mapper.SetInputData(grid)colors = vtkNamedColors()actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().EdgeVisibilityOn()actor.GetProperty().LightingOff()actor.GetProperty().SetColor(colors.GetColor3d('Seashell'))renderer = vtkRenderer()renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('DarkSlateGray'))window = vtkRenderWindow()window.AddRenderer(renderer)window.SetWindowName('CreateESGrid')window.SetSize(1024, 768)window.Render()camera = renderer.GetActiveCamera()camera.SetPosition(8.383354, -72.468670, 94.262605)camera.SetFocalPoint(42.295234, 21.111537, -0.863606)camera.SetViewUp(0.152863, 0.676710, 0.720206)camera.SetDistance(137.681759)camera.SetClippingRange(78.173985, 211.583658)interactor = vtkRenderWindowInteractor()interactor.SetRenderWindow(window)interactor.SetInteractorStyle(vtkInteractorStyleRubberBandPick())window.Render()interactor.Start()if __name__ == '__main__':main()

在这里插入图片描述

This example displays the using the vtkExplicitStructuredGrid class.

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersCore import vtkUnstructuredGridToExplicitStructuredGrid
from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleRubberBandPick
from vtkmodules.vtkRenderingCore import (vtkActor,vtkDataSetMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def get_program_parameters(argv):import argparsedescription = 'Load an explicit structured grid from a file'epilogue = ''''''parser = argparse.ArgumentParser(description=description, epilog=epilogue,formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument('fn', help='The explicit structured grid file name e.g. UNISIM-II-D.vtu.')args = parser.parse_args()return args.fndef main(fn):reader = vtkXMLUnstructuredGridReader()reader.SetFileName(fn)reader.Update()converter = vtkUnstructuredGridToExplicitStructuredGrid()converter.GlobalWarningDisplayOff()  # hide VTK errorsconverter.SetInputConnection(reader.GetOutputPort())converter.SetInputArrayToProcess(0, 0, 0, 1, 'BLOCK_I')converter.SetInputArrayToProcess(1, 0, 0, 1, 'BLOCK_J')converter.SetInputArrayToProcess(2, 0, 0, 1, 'BLOCK_K')converter.Update()grid = converter.GetOutput()grid.ComputeFacesConnectivityFlagsArray()grid.GetCellData().SetActiveScalars('ConnectivityFlags')scalars = grid.GetCellData().GetArray('ConnectivityFlags')mapper = vtkDataSetMapper()mapper.SetInputData(grid)mapper.SetColorModeToMapScalars()mapper.SetScalarRange(scalars.GetRange())actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().EdgeVisibilityOn()colors = vtkNamedColors()renderer = vtkRenderer()renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('DimGray'))window = vtkRenderWindow()window.AddRenderer(renderer)window.SetWindowName('LoadESGrid')window.SetSize(1024, 768)window.Render()camera = renderer.GetActiveCamera()camera.SetPosition(312452.407650, 7474760.406373, 3507.364723)camera.SetFocalPoint(314388.388434, 7481520.509575, -2287.477388)camera.SetViewUp(0.089920, 0.633216, 0.768734)camera.SetDistance(9111.926908)camera.SetClippingRange(595.217338, 19595.429475)interactor = vtkRenderWindowInteractor()interactor.SetRenderWindow(window)interactor.SetInteractorStyle(vtkInteractorStyleRubberBandPick())window.Render()interactor.Start()if __name__ == '__main__':import sysfn = get_program_parameters(sys.argv)main(fn)

在这里插入图片描述

This example loads points into a polydata and an unstructured grid then combines them.The example should be extended to show cells being combined as well.

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (vtkPolyData,vtkUnstructuredGrid
)
from vtkmodules.vtkFiltersCore import vtkAppendFilter
from vtkmodules.vtkFiltersSources import (vtkPointSource,vtkSphereSource
)
from vtkmodules.vtkRenderingCore import (vtkActor,vtkDataSetMapper,vtkGlyph3DMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Create 5 points (vtkPolyData)pointSource = vtkPointSource()pointSource.SetNumberOfPoints(5)pointSource.Update()polydata = pointSource.GetOutput()print('There are', polydata.GetNumberOfPoints(), 'points in the polydata.')# Create 2 points in a vtkUnstructuredGridpoints = vtkPoints()points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(0, 0, 1)ug = vtkUnstructuredGrid()ug.SetPoints(points)print('There are', ug.GetNumberOfPoints(), 'points in the unstructured.')# Combine the two data setsappendFilter = vtkAppendFilter()appendFilter.AddInputData(polydata)appendFilter.AddInputData(ug)appendFilter.Update()combined = vtkUnstructuredGrid()combined = appendFilter.GetOutput()print('There are', combined.GetNumberOfPoints(), 'points combined.')# Create a mapper and actormapper = vtkDataSetMapper()mapper.SetInputConnection(appendFilter.GetOutputPort())actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetPointSize(5)# Map the points to spheressphereActor = point_to_glyph(appendFilter.GetOutput().GetPoints(), 0.05)sphereActor.GetProperty().SetColor(colors.GetColor3d("Gold"))# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actor to the scenerenderer.AddActor(actor)renderer.AddActor(sphereActor)renderer.SetBackground(colors.GetColor3d('RoyalBlue'))# Render and interactrenderWindow.SetWindowName('AppendFilter')renderWindow.Render()renderWindowInteractor.Start()def point_to_glyph(points, scale):"""Convert points to glyphs.:param points: The points to glyph.:param scale: The scale, used to determine the size of theglyph representing the point, expressed as afraction of the largest side of the boundingbox surrounding the points. e.g. 0.05:return: The actor."""bounds = points.GetBounds()max_len = 0.0for i in range(0, 3):max_len = max(bounds[i + 1] - bounds[i], max_len)sphere_source = vtkSphereSource()sphere_source.SetRadius(scale * max_len)pd = vtkPolyData()pd.SetPoints(points)mapper = vtkGlyph3DMapper()mapper.SetInputData(pd)mapper.SetSourceConnection(sphere_source.GetOutputPort())mapper.ScalarVisibilityOff()mapper.ScalingOff()actor = vtkActor()actor.SetMapper(mapper)return actorif __name__ == '__main__':main()

在这里插入图片描述

This example reads two .vtp files (or produces them if not specified as command line arguments), combines them, and

displays the result to the screen.

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import (vtkAppendPolyData,vtkCleanPolyData
)
from vtkmodules.vtkFiltersSources import (vtkConeSource,vtkSphereSource
)
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Set the background color.colors.SetColor('BkgColor', [0.3, 0.2, 0.1, 1.0])input1 = vtkPolyData()input2 = vtkPolyData()sphereSource = vtkSphereSource()sphereSource.SetCenter(5, 0, 0)sphereSource.Update()input1.ShallowCopy(sphereSource.GetOutput())coneSource = vtkConeSource()coneSource.Update()input2.ShallowCopy(coneSource.GetOutput())# Append the two meshesappendFilter = vtkAppendPolyData()appendFilter.AddInputData(input1)appendFilter.AddInputData(input2)appendFilter.Update()#  Remove any duplicate points.cleanFilter = vtkCleanPolyData()cleanFilter.SetInputConnection(appendFilter.GetOutputPort())cleanFilter.Update()# Create a mapper and actormapper = vtkPolyDataMapper()mapper.SetInputConnection(cleanFilter.GetOutputPort())actor = vtkActor()actor.SetMapper(mapper)# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actors to the scenerenderer.AddActor(actor)# Render and interactrenderWindowInteractor.Initialize()renderWindow.Render()renderWindow.SetWindowName('CombinePolyData')renderer.SetBackground(colors.GetColor3d('deep_ochre'))renderer.GetActiveCamera().Zoom(0.9)renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

CombinePolyData

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersCore import (vtkAppendFilter,vtkConnectivityFilter,vtkDelaunay3D
)
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkDataSetMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()sphereSource1 = vtkSphereSource()sphereSource1.Update()delaunay1 = vtkDelaunay3D()delaunay1.SetInputConnection(sphereSource1.GetOutputPort())delaunay1.Update()sphereSource2 = vtkSphereSource()sphereSource2.SetCenter(5, 0, 0)sphereSource2.Update()delaunay2 = vtkDelaunay3D()delaunay2.SetInputConnection(sphereSource2.GetOutputPort())delaunay2.Update()appendFilter = vtkAppendFilter()appendFilter.AddInputConnection(delaunay1.GetOutputPort())appendFilter.AddInputConnection(delaunay2.GetOutputPort())appendFilter.Update()connectivityFilter = vtkConnectivityFilter()connectivityFilter.SetInputConnection(appendFilter.GetOutputPort())connectivityFilter.SetExtractionModeToAllRegions()connectivityFilter.ColorRegionsOn()connectivityFilter.Update()# Visualizemapper = vtkDataSetMapper()mapper.SetInputConnection(connectivityFilter.GetOutputPort())mapper.Update()actor = vtkActor()actor.SetMapper(mapper)renderer = vtkRenderer()renderer.AddActor(actor)# renWindow = vtkRenderWindow()# renWindow.AddRenderer(renderer)# iren = vtkRenderWindowInteractor()# iren.SetRenderWindow(renWindow)# iren.Initialize()# iren.Start()renWindow = vtkRenderWindow()renWindow.AddRenderer(renderer)iren = vtkRenderWindowInteractor()iren.SetRenderWindow(renWindow)iren.Initialize()renWindow.Render()renWindow.SetWindowName('ConnectivityFilter')renderer.SetBackground(colors.GetColor3d('deep_ochre'))renderer.GetActiveCamera().Zoom(0.9)renWindow.Render()iren.Start()if __name__ == '__main__':main()

在这里插入图片描述

ConstrainedDelaunay2D

Description

Perform a 2D Delaunay triangulation respecting a specified boundary. This examples constructs a 10x10 grid of points. It
then defines a polygon that uses the points in the grid. We want to triangulate all of the points except the region
inside the boundary of the polygon. We expect a rectangular hole of size 4x3 in the resulting triangulated plane.

#!/usr/bin/python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (vtkMinimalStandardRandomSequence,vtkPoints
)
from vtkmodules.vtkCommonDataModel import (vtkCellArray,vtkPolyData,vtkPolygon
)
from vtkmodules.vtkFiltersCore import vtkDelaunay2D
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Generate a 10 x 10 grid of pointspoints = vtkPoints()gridSize = 10seed = 0randomSequence = vtkMinimalStandardRandomSequence()randomSequence.Initialize(seed)for x in range(gridSize):for y in range(gridSize):d1 = randomSequence.GetValue() / 2.0 - 0.25randomSequence.Next()d2 = randomSequence.GetValue() / 2.0 - 0.25randomSequence.Next()points.InsertNextPoint(x + d1, y + d2, 0)aPolyData = vtkPolyData()aPolyData.SetPoints(points)# Create a cell array to store the polygon inaCellArray = vtkCellArray()# Define a polygonal hole with a clockwise polygonaPolygon = vtkPolygon()aPolygon.GetPointIds().InsertNextId(22)aPolygon.GetPointIds().InsertNextId(23)aPolygon.GetPointIds().InsertNextId(24)aPolygon.GetPointIds().InsertNextId(25)aPolygon.GetPointIds().InsertNextId(35)aPolygon.GetPointIds().InsertNextId(45)aPolygon.GetPointIds().InsertNextId(44)aPolygon.GetPointIds().InsertNextId(43)aPolygon.GetPointIds().InsertNextId(42)aPolygon.GetPointIds().InsertNextId(32)aCellArray.InsertNextCell(aPolygon)# Create a polydata to store the boundary. The points must be the# same as the points we will triangulate.boundary = vtkPolyData()boundary.SetPoints(aPolyData.GetPoints())boundary.SetPolys(aCellArray)# Triangulate the grid pointsdelaunay = vtkDelaunay2D()delaunay.SetInputData(aPolyData)delaunay.SetSourceData(boundary)# VisualizemeshMapper = vtkPolyDataMapper()meshMapper.SetInputConnection(delaunay.GetOutputPort())meshActor = vtkActor()meshActor.SetMapper(meshMapper)meshActor.GetProperty().EdgeVisibilityOn()meshActor.GetProperty().SetEdgeColor(colors.GetColor3d('Peacock'))meshActor.GetProperty().SetInterpolationToFlat()boundaryMapper = vtkPolyDataMapper()boundaryMapper.SetInputData(boundary)boundaryActor = vtkActor()boundaryActor.SetMapper(boundaryMapper)boundaryActor.GetProperty().SetColor(colors.GetColor3d('Raspberry'))boundaryActor.GetProperty().SetLineWidth(3)boundaryActor.GetProperty().EdgeVisibilityOn()boundaryActor.GetProperty().SetEdgeColor(colors.GetColor3d('Red'))boundaryActor.GetProperty().SetRepresentationToWireframe()# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actor to the scenerenderer.AddActor(meshActor)renderer.AddActor(boundaryActor)renderer.SetBackground(colors.GetColor3d('Mint'))# Render and interactrenderWindow.SetSize(640, 480)renderWindow.SetWindowName('ConstrainedDelaunay2D')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Delaunay2D

#!/usr/bin/python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkDelaunay2D
from vtkmodules.vtkFiltersGeneral import vtkVertexGlyphFilter
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Create a set of heights on a grid.# This is often called a "terrain map".points = vtkPoints()gridSize = 10for x in range(gridSize):for y in range(gridSize):points.InsertNextPoint(x, y, int((x + y) / (y + 1)))# Add the grid points to a polydata objectpolydata = vtkPolyData()polydata.SetPoints(points)delaunay = vtkDelaunay2D()delaunay.SetInputData(polydata)# VisualizemeshMapper = vtkPolyDataMapper()meshMapper.SetInputConnection(delaunay.GetOutputPort())meshActor = vtkActor()meshActor.SetMapper(meshMapper)meshActor.GetProperty().SetColor(colors.GetColor3d('Banana'))meshActor.GetProperty().EdgeVisibilityOn()glyphFilter = vtkVertexGlyphFilter()glyphFilter.SetInputData(polydata)pointMapper = vtkPolyDataMapper()pointMapper.SetInputConnection(glyphFilter.GetOutputPort())pointActor = vtkActor()pointActor.GetProperty().SetColor(colors.GetColor3d('Tomato'))pointActor.GetProperty().SetPointSize(5)pointActor.SetMapper(pointMapper)renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)renderer.AddActor(meshActor)renderer.AddActor(pointActor)renderer.SetBackground(colors.GetColor3d('Mint'))renderWindowInteractor.Initialize()renderWindow.SetWindowName('Delaunay2D')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

GaussianSplat

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkContourFilter
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkImagingHybrid import vtkGaussianSplatter
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():# Create points on a spheresphereSource = vtkSphereSource()sphereSource.Update()colors = vtkNamedColors()polydata = vtkPolyData()polydata.SetPoints(sphereSource.GetOutput().GetPoints())splatter = vtkGaussianSplatter()splatter.SetInputData(polydata)splatter.SetSampleDimensions(50, 50, 50)splatter.SetRadius(0.5)splatter.ScalarWarpingOff()surface = vtkContourFilter()surface.SetInputConnection(splatter.GetOutputPort())surface.SetValue(0, 0.01)# Create a mapper and actormapper = vtkPolyDataMapper()mapper.SetInputConnection(surface.GetOutputPort())actor = vtkActor()actor.SetMapper(mapper)# Visualizerenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('SteelBlue'))renderWindow.SetWindowName('GaussianSplat')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Glyph2D

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkGlyph2D
from vtkmodules.vtkFiltersSources import vtkRegularPolygonSource
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleImage
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(2, 2, 0)polydata = vtkPolyData()polydata.SetPoints(points)# Create anything you want here, we will use a polygon for the demo.polygonSource = vtkRegularPolygonSource()  # default is 6 sidesglyph2D = vtkGlyph2D()glyph2D.SetSourceConnection(polygonSource.GetOutputPort())glyph2D.SetInputData(polydata)glyph2D.Update()mapper = vtkPolyDataMapper()mapper.SetInputConnection(glyph2D.GetOutputPort())mapper.Update()actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetColor(colors.GetColor3d('Salmon'))# Visualizerenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('SlateGray'))style = vtkInteractorStyleImage()renderWindowInteractor.SetInteractorStyle(style)renderWindow.SetWindowName('Glyph2D');renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Glyph3D

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkGlyph3D
from vtkmodules.vtkFiltersSources import vtkCubeSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 1, 1)points.InsertNextPoint(2, 2, 2)polydata = vtkPolyData()polydata.SetPoints(points)# Create anything you want here, we will use a cube for the demo.cubeSource = vtkCubeSource()glyph3D = vtkGlyph3D()glyph3D.SetSourceConnection(cubeSource.GetOutputPort())glyph3D.SetInputData(polydata)glyph3D.Update()# Visualizemapper = vtkPolyDataMapper()mapper.SetInputConnection(glyph3D.GetOutputPort())actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetColor(colors.GetColor3d('Salmon'))renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('SlateGray'))  # Background Slate GrayrenderWindow.SetWindowName('Glyph2D');renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

PerlinNoise

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkPerlinNoise
from vtkmodules.vtkFiltersCore import vtkContourFilter
from vtkmodules.vtkImagingHybrid import vtkSampleFunction
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()perlinNoise = vtkPerlinNoise()perlinNoise.SetFrequency(2, 1.25, 1.5)perlinNoise.SetPhase(0, 0, 0)sample = vtkSampleFunction()sample.SetImplicitFunction(perlinNoise)sample.SetSampleDimensions(65, 65, 20)sample.ComputeNormalsOff()surface = vtkContourFilter()surface.SetInputConnection(sample.GetOutputPort())surface.SetValue(0, 0.0)mapper = vtkPolyDataMapper()mapper.SetInputConnection(surface.GetOutputPort())mapper.ScalarVisibilityOff()actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetColor(colors.GetColor3d('SteelBlue'))renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)interactor = vtkRenderWindowInteractor()interactor.SetRenderWindow(renderWindow)# Add the actors to the renderer, set the background and sizerenderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('SlateGray'))renderWindow.SetWindowName('PerlinNoise')renderWindow.SetSize(300, 300)renderer.ResetCamera()renderWindow.Render()interactor.Start()if __name__ == '__main__':main()

在这里插入图片描述

TransformPolyData

Description

This example demonstrates how to apply a transform to a data set. It uses vtkTransformPolyDataFilter, but it can be
replaced with vtkTransformFilter for different types of data sets, including vtkUnstructuredGrid and vtkStructuredGrid.
vtkTransformFilter will work with vtkPolyData, too).

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Create the polydata geometrysphereSource = vtkSphereSource()sphereSource.Update()# Set up the actor to display the untransformed polydataoriginalMapper = vtkPolyDataMapper()originalMapper.SetInputConnection(sphereSource.GetOutputPort())originalActor = vtkActor()originalActor.SetMapper(originalMapper)originalActor.GetProperty().SetColor(colors.GetColor3d('Blue'))# Set up the transform filtertranslation = vtkTransform()translation.Translate(1.0, 2.0, 3.0)transformFilter = vtkTransformPolyDataFilter()transformFilter.SetInputConnection(sphereSource.GetOutputPort())transformFilter.SetTransform(translation)transformFilter.Update()# Set up the actor to display the transformed polydatatransformedMapper = vtkPolyDataMapper()transformedMapper.SetInputConnection(transformFilter.GetOutputPort())transformedActor = vtkActor()transformedActor.SetMapper(transformedMapper)transformedActor.GetProperty().SetColor(colors.GetColor3d('Red'))# Set up the rest of the visualization pipelinerenderer = vtkRenderer()renderer.AddActor(originalActor)renderer.AddActor(transformedActor)renderer.SetBackground(colors.GetColor3d('Green'))renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)renderWindow.SetWindowName('TransformPolyData')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

TriangulateTerrainMap

Description

This example generates heights (z-values) on a 10x10 grid (a terrain map) and triangulates the points.

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (vtkMinimalStandardRandomSequence,vtkPoints
)
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkDelaunay2D
from vtkmodules.vtkFiltersGeneral import vtkVertexGlyphFilter
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Create points on an XY grid with random Z coordinatepoints = vtkPoints()gridSize = 10seed = 0randomSequence = vtkMinimalStandardRandomSequence()randomSequence.Initialize(seed)for x in range(0, gridSize):for y in range(0, gridSize):d = randomSequence.GetValue()randomSequence.Next()points.InsertNextPoint(x, y, d * 3)# Add the grid points to a polydata objectpolydata = vtkPolyData()polydata.SetPoints(points)glyphFilter = vtkVertexGlyphFilter()glyphFilter.SetInputData(polydata)glyphFilter.Update()# Create a mapper and actorpointsMapper = vtkPolyDataMapper()pointsMapper.SetInputConnection(glyphFilter.GetOutputPort())pointsActor = vtkActor()pointsActor.SetMapper(pointsMapper)pointsActor.GetProperty().SetPointSize(3)pointsActor.GetProperty().SetColor(colors.GetColor3d("Red"))# Triangulate the grid pointsdelaunay = vtkDelaunay2D()delaunay.SetInputData(polydata)delaunay.Update()# Create a mapper and actortriangulatedMapper = vtkPolyDataMapper()triangulatedMapper.SetInputConnection(delaunay.GetOutputPort())triangulatedActor = vtkActor()triangulatedActor.SetMapper(triangulatedMapper)# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actor to the scenerenderer.AddActor(pointsActor)renderer.AddActor(triangulatedActor)renderer.SetBackground(colors.GetColor3d("Green"))  # Background color green# Render and interactrenderWindow.SetWindowName('TriangulateTerrainMap')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

VertexGlyphFilter

Description

This example creates a set of points and adds a vertex at each point using vtkVertexGlyphFilter.

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersGeneral import vtkVertexGlyphFilter
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 1, 1)points.InsertNextPoint(2, 2, 2)polydata = vtkPolyData()polydata.SetPoints(points)vertexGlyphFilter = vtkVertexGlyphFilter()vertexGlyphFilter.AddInputData(polydata)vertexGlyphFilter.Update()# Create a mapper and actormapper = vtkPolyDataMapper()mapper.SetInputConnection(vertexGlyphFilter.GetOutputPort())actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetPointSize(10)actor.GetProperty().SetColor(colors.GetColor3d('Yellow'))# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actor to the scenerenderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('Green'))# Render and interactrenderWindow.SetWindowName('VertexGlyphFilter')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

WarpTo

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersCore import vtkTubeFilter
from vtkmodules.vtkFiltersGeneral import vtkWarpTo
from vtkmodules.vtkFiltersSources import vtkLineSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkDataSetMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Create the RenderWindow, Renderer and both Actorsrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Create a linelineSource = vtkLineSource()lineSource.SetPoint1(0.0, 0.0, 0.0)lineSource.SetPoint2(0.0, 1.0, 0.0)lineSource.SetResolution(20)lineSource.Update()# Create a tube (cylinder) around the linetubeFilter = vtkTubeFilter()tubeFilter.SetInputConnection(lineSource.GetOutputPort())tubeFilter.SetRadius(.01)  # default is .5tubeFilter.SetNumberOfSides(50)tubeFilter.Update()warpTo = vtkWarpTo()warpTo.SetInputConnection(tubeFilter.GetOutputPort())warpTo.SetPosition(10, 1, 0)warpTo.SetScaleFactor(5)warpTo.AbsoluteOn()mapper = vtkDataSetMapper()mapper.SetInputConnection(warpTo.GetOutputPort())mapper.ScalarVisibilityOff()actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetColor(colors.GetColor3d('Gold'))renderer.SetBackground(colors.GetColor3d('Green'))renderer.AddActor(actor)renderWindow.SetWindowName('WarpTo')renderWindow.Render()renderWindowInteractor.Initialize()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Arrow

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersSources import vtkArrowSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()arrowSource = vtkArrowSource()# arrowSource.SetShaftRadius(0.01)# arrowSource.SetTipLength(.9)# Create a mapper and actormapper = vtkPolyDataMapper()mapper.SetInputConnection(arrowSource.GetOutputPort())actor = vtkActor()actor.SetMapper(mapper)# Visualizerenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName('Arrow')renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('MidnightBlue'))renderWindow.SetWindowName('Arrow')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Axes

Description

This example shows how to position an vtkAxesActor in 3D. Notice that position and orientation of the vtkAxesActor is
done with a user transform.

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingAnnotation import vtkAxesActor
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# create a SpheresphereSource = vtkSphereSource()sphereSource.SetCenter(0.0, 0.0, 0.0)sphereSource.SetRadius(0.5)# create a mappersphereMapper = vtkPolyDataMapper()sphereMapper.SetInputConnection(sphereSource.GetOutputPort())# create an actorsphereActor = vtkActor()sphereActor.SetMapper(sphereMapper)# a renderer and render windowrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName('Axes')renderWindow.AddRenderer(renderer)# an interactorrenderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# add the actors to the scenerenderer.AddActor(sphereActor)renderer.SetBackground(colors.GetColor3d('SlateGray'))transform = vtkTransform()transform.Translate(1.0, 0.0, 0.0)axes = vtkAxesActor()#  The axes are positioned with a user transformaxes.SetUserTransform(transform)# properties of the axes labels can be set as follows# this sets the x axis label to red# axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetColor(colors.GetColor3d('Red'));# the actual text of the axis label can be changed:# axes->SetXAxisLabelText('test');renderer.AddActor(axes)renderer.GetActiveCamera().Azimuth(50)renderer.GetActiveCamera().Elevation(-30)renderer.ResetCamera()renderWindow.SetWindowName('Axes')renderWindow.Render()# begin mouse interactionrenderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Cell3DDemonstration

Description

This is a demonstration of how to construct and display geometric objects using the classes derived from vtkCell3D. For
each object we specify the points and cell Ids.

From this we create an unstructured grid. In some cases a vtkCellArray is used and the result is added to the
unstructured grid, see: MakePolyhedron() and MakeTetrahedron().

Also demonstrated is the use of vectors to hold the unstructured grids, mappers, actors and renderers.

The resultant objects are then displayed in a grid.

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingFreeType
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (vtkIdList,vtkPoints
)
from vtkmodules.vtkCommonDataModel import (VTK_POLYHEDRON,VTK_TETRA,vtkCellArray,vtkHexagonalPrism,vtkHexahedron,vtkPentagonalPrism,vtkPyramid,vtkTetra,vtkUnstructuredGrid,vtkVoxel,vtkWedge
)
from vtkmodules.vtkIOImage import vtkPNGWriter
from vtkmodules.vtkRenderingCore import (vtkActor,vtkActor2D,vtkDataSetMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer,vtkTextMapper,vtkTextProperty,vtkWindowToImageFilter
)def main():colors = vtkNamedColors()# Set the background color.colors.SetColor('BkgColor', [51, 77, 102, 255])titles = list()textMappers = list()textActors = list()uGrids = list()mappers = list()actors = list()renderers = list()uGrids.append(MakeHexagonalPrism())titles.append('Hexagonal Prism')uGrids.append(MakeHexahedron())titles.append('Hexahedron')uGrids.append(MakePentagonalPrism())titles.append('Pentagonal Prism')uGrids.append(MakePolyhedron())titles.append('Polyhedron')uGrids.append(MakePyramid())titles.append('Pyramid')uGrids.append(MakeTetrahedron())titles.append('Tetrahedron')uGrids.append(MakeVoxel())titles.append('Voxel')uGrids.append(MakeWedge())titles.append('Wedge')renWin = vtkRenderWindow()renWin.SetWindowName('Cell3DDemonstration')iRen = vtkRenderWindowInteractor()iRen.SetRenderWindow(renWin)# Create one text property for alltextProperty = vtkTextProperty()textProperty.SetFontSize(16)textProperty.SetJustificationToCentered()textProperty.SetColor(colors.GetColor3d('LightGoldenrodYellow'))# Create and link the mappers actors and renderers together.for i in range(0, len(uGrids)):textMappers.append(vtkTextMapper())textActors.append(vtkActor2D())mappers.append(vtkDataSetMapper())actors.append(vtkActor())renderers.append(vtkRenderer())mappers[i].SetInputData(uGrids[i])actors[i].SetMapper(mappers[i])actors[i].GetProperty().SetColor(colors.GetColor3d('PeachPuff'))renderers[i].AddViewProp(actors[i])textMappers[i].SetInput(titles[i])textMappers[i].SetTextProperty(textProperty)textActors[i].SetMapper(textMappers[i])textActors[i].SetPosition(120, 16)renderers[i].AddViewProp(textActors[i])renWin.AddRenderer(renderers[i])gridDimensions = 3rendererSize = 300renWin.SetSize(rendererSize * gridDimensions,rendererSize * gridDimensions)for row in range(0, gridDimensions):for col in range(0, gridDimensions):index = row * gridDimensions + col# (xmin, ymin, xmax, ymax)viewport = [float(col) * rendererSize /(gridDimensions * rendererSize),float(gridDimensions - (row + 1)) * rendererSize /(gridDimensions * rendererSize),float(col + 1) * rendererSize /(gridDimensions * rendererSize),float(gridDimensions - row) * rendererSize /(gridDimensions * rendererSize)]if index > len(actors) - 1:# Add a renderer even if there is no actor.# This makes the render window background all the same color.ren = vtkRenderer()ren.SetBackground(colors.GetColor3d('BkgColor'))ren.SetViewport(viewport)renWin.AddRenderer(ren)continuerenderers[index].SetViewport(viewport)renderers[index].SetBackground(colors.GetColor3d('BkgColor'))renderers[index].ResetCamera()renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)renderers[index].GetActiveCamera().Zoom(0.85)renderers[index].ResetCameraClippingRange()iRen.Initialize()renWin.SetWindowName('Cell3DDemonstration')renWin.Render()iRen.Start()def MakeHexagonalPrism():"""3D: hexagonal prism: a wedge with an hexagonal base.Be careful, the base face ordering is different from wedge."""numberOfVertices = 12points = vtkPoints()points.InsertNextPoint(0.0, 0.0, 1.0)points.InsertNextPoint(1.0, 0.0, 1.0)points.InsertNextPoint(1.5, 0.5, 1.0)points.InsertNextPoint(1.0, 1.0, 1.0)points.InsertNextPoint(0.0, 1.0, 1.0)points.InsertNextPoint(-0.5, 0.5, 1.0)points.InsertNextPoint(0.0, 0.0, 0.0)points.InsertNextPoint(1.0, 0.0, 0.0)points.InsertNextPoint(1.5, 0.5, 0.0)points.InsertNextPoint(1.0, 1.0, 0.0)points.InsertNextPoint(0.0, 1.0, 0.0)points.InsertNextPoint(-0.5, 0.5, 0.0)hexagonalPrism = vtkHexagonalPrism()for i in range(0, numberOfVertices):hexagonalPrism.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.InsertNextCell(hexagonalPrism.GetCellType(),hexagonalPrism.GetPointIds())ug.SetPoints(points)return ugdef MakeHexahedron():"""A regular hexagon (cube) with all faces square and three squares aroundeach vertex is created below.Setup the coordinates of eight points(the two faces must be in counter clockwiseorder as viewed from the outside).As an exercise you can modify the coordinates of the points to createseven topologically distinct convex hexahedras."""numberOfVertices = 8# Create the pointspoints = vtkPoints()points.InsertNextPoint(0.0, 0.0, 0.0)points.InsertNextPoint(1.0, 0.0, 0.0)points.InsertNextPoint(1.0, 1.0, 0.0)points.InsertNextPoint(0.0, 1.0, 0.0)points.InsertNextPoint(0.0, 0.0, 1.0)points.InsertNextPoint(1.0, 0.0, 1.0)points.InsertNextPoint(1.0, 1.0, 1.0)points.InsertNextPoint(0.0, 1.0, 1.0)# Create a hexahedron from the pointshex_ = vtkHexahedron()for i in range(0, numberOfVertices):hex_.GetPointIds().SetId(i, i)# Add the points and hexahedron to an unstructured griduGrid = vtkUnstructuredGrid()uGrid.SetPoints(points)uGrid.InsertNextCell(hex_.GetCellType(), hex_.GetPointIds())return uGriddef MakePentagonalPrism():numberOfVertices = 10# Create the pointspoints = vtkPoints()points.InsertNextPoint(11, 10, 10)points.InsertNextPoint(13, 10, 10)points.InsertNextPoint(14, 12, 10)points.InsertNextPoint(12, 14, 10)points.InsertNextPoint(10, 12, 10)points.InsertNextPoint(11, 10, 14)points.InsertNextPoint(13, 10, 14)points.InsertNextPoint(14, 12, 14)points.InsertNextPoint(12, 14, 14)points.InsertNextPoint(10, 12, 14)# Pentagonal PrismpentagonalPrism = vtkPentagonalPrism()for i in range(0, numberOfVertices):pentagonalPrism.GetPointIds().SetId(i, i)# Add the points and hexahedron to an unstructured griduGrid = vtkUnstructuredGrid()uGrid.SetPoints(points)uGrid.InsertNextCell(pentagonalPrism.GetCellType(),pentagonalPrism.GetPointIds())return uGriddef MakePolyhedron():"""Make a regular dodecahedron. It consists of twelve regular pentagonalfaces with three faces meeting at each vertex."""# numberOfVertices = 20numberOfFaces = 12# numberOfFaceVertices = 5points = vtkPoints()points.InsertNextPoint(1.21412, 0, 1.58931)points.InsertNextPoint(0.375185, 1.1547, 1.58931)points.InsertNextPoint(-0.982247, 0.713644, 1.58931)points.InsertNextPoint(-0.982247, -0.713644, 1.58931)points.InsertNextPoint(0.375185, -1.1547, 1.58931)points.InsertNextPoint(1.96449, 0, 0.375185)points.InsertNextPoint(0.607062, 1.86835, 0.375185)points.InsertNextPoint(-1.58931, 1.1547, 0.375185)points.InsertNextPoint(-1.58931, -1.1547, 0.375185)points.InsertNextPoint(0.607062, -1.86835, 0.375185)points.InsertNextPoint(1.58931, 1.1547, -0.375185)points.InsertNextPoint(-0.607062, 1.86835, -0.375185)points.InsertNextPoint(-1.96449, 0, -0.375185)points.InsertNextPoint(-0.607062, -1.86835, -0.375185)points.InsertNextPoint(1.58931, -1.1547, -0.375185)points.InsertNextPoint(0.982247, 0.713644, -1.58931)points.InsertNextPoint(-0.375185, 1.1547, -1.58931)points.InsertNextPoint(-1.21412, 0, -1.58931)points.InsertNextPoint(-0.375185, -1.1547, -1.58931)points.InsertNextPoint(0.982247, -0.713644, -1.58931)# Dimensions are [numberOfFaces][numberOfFaceVertices]dodechedronFace = [[0, 1, 2, 3, 4],[0, 5, 10, 6, 1],[1, 6, 11, 7, 2],[2, 7, 12, 8, 3],[3, 8, 13, 9, 4],[4, 9, 14, 5, 0],[15, 10, 5, 14, 19],[16, 11, 6, 10, 15],[17, 12, 7, 11, 16],[18, 13, 8, 12, 17],[19, 14, 9, 13, 18],[19, 18, 17, 16, 15]]dodechedronFacesIdList = vtkIdList()# Number faces that make up the cell.dodechedronFacesIdList.InsertNextId(numberOfFaces)for face in dodechedronFace:# Number of points in the face == numberOfFaceVerticesdodechedronFacesIdList.InsertNextId(len(face))# Insert the pointIds for that face.[dodechedronFacesIdList.InsertNextId(i) for i in face]uGrid = vtkUnstructuredGrid()uGrid.InsertNextCell(VTK_POLYHEDRON, dodechedronFacesIdList)uGrid.SetPoints(points)return uGriddef MakePyramid():"""Make a regular square pyramid."""numberOfVertices = 5points = vtkPoints()p = [[1.0, 1.0, 0.0],[-1.0, 1.0, 0.0],[-1.0, -1.0, 0.0],[1.0, -1.0, 0.0],[0.0, 0.0, 1.0]]for pt in p:points.InsertNextPoint(pt)pyramid = vtkPyramid()for i in range(0, numberOfVertices):pyramid.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds())return ugdef MakeTetrahedron():"""Make a tetrahedron."""numberOfVertices = 4points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 0, 0)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(0, 1, 1)tetra = vtkTetra()for i in range(0, numberOfVertices):tetra.GetPointIds().SetId(i, i)cellArray = vtkCellArray()cellArray.InsertNextCell(tetra)unstructuredGrid = vtkUnstructuredGrid()unstructuredGrid.SetPoints(points)unstructuredGrid.SetCells(VTK_TETRA, cellArray)return unstructuredGriddef MakeVoxel():"""A voxel is a representation of a regular grid in 3-D space."""numberOfVertices = 8points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 0, 0)points.InsertNextPoint(0, 1, 0)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(0, 0, 1)points.InsertNextPoint(1, 0, 1)points.InsertNextPoint(0, 1, 1)points.InsertNextPoint(1, 1, 1)voxel = vtkVoxel()for i in range(0, numberOfVertices):voxel.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(voxel.GetCellType(), voxel.GetPointIds())return ugdef MakeWedge():"""A wedge consists of two triangular ends and three rectangular faces."""numberOfVertices = 6points = vtkPoints()points.InsertNextPoint(0, 1, 0)points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(0, .5, .5)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(1, 0.0, 0.0)points.InsertNextPoint(1, .5, .5)wedge = vtkWedge()for i in range(0, numberOfVertices):wedge.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(wedge.GetCellType(), wedge.GetPointIds())return ugdef WritePNG(renWin, fn, magnification=1):"""ScreenshotWrite out a png corresponding to the render window.:param: renWin - the render window.:param: fn - the file name.:param: magnification - the magnification."""windowToImageFilter = vtkWindowToImageFilter()windowToImageFilter.SetInput(renWin)windowToImageFilter.SetMagnification(magnification)# Record the alpha (transparency) channel# windowToImageFilter.SetInputBufferTypeToRGBA()windowToImageFilter.SetInputBufferTypeToRGB()# Read from the back bufferwindowToImageFilter.ReadFrontBufferOff()windowToImageFilter.Update()writer = vtkPNGWriter()writer.SetFileName(fn)writer.SetInputConnection(windowToImageFilter.GetOutputPort())writer.Write()if __name__ == '__main__':main()

在这里插入图片描述

CellTypeSource

Description

This example uses vtkCellTypeSource to generate a vtkUnstructuredGrid. If a cell does not fill a rectangular area or
volume, then multiple cells will be generated. For example, a vtkTetra requires 12 cells to fill a cube. A vtkTriangle
requires two cells to fill a square. vtkCellTypeSource generates a uniform set of coordinates. The example perturbs
those coordinates to illustrate the results of the vtkTessellatorFilter. Also, each cell is passed through
vtkShrinkFilter to help identify the cells. Each generated cell also has a unique color.

The example takes an optional argument, a vtkCell name.

For example, to generate vtkTriangles, run

CellTypeSource vtkTriangle
# !/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingFreeType
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import (vtkColorSeries,vtkNamedColors
)
from vtkmodules.vtkCommonCore import (vtkIntArray,vtkLookupTable,vtkMinimalStandardRandomSequence,vtkPoints
)
from vtkmodules.vtkCommonDataModel import (VTK_CUBIC_LINE,VTK_HEXAHEDRON,VTK_LINE,VTK_PYRAMID,VTK_QUAD,VTK_QUADRATIC_EDGE,VTK_QUADRATIC_HEXAHEDRON,VTK_QUADRATIC_PYRAMID,VTK_QUADRATIC_QUAD,VTK_QUADRATIC_TETRA,VTK_QUADRATIC_TRIANGLE,VTK_QUADRATIC_WEDGE,VTK_TETRA,VTK_TRIANGLE,VTK_WEDGE,vtkCellTypes
)
from vtkmodules.vtkFiltersGeneral import (vtkShrinkFilter,vtkTessellatorFilter
)
from vtkmodules.vtkFiltersSources import vtkCellTypeSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkActor2D,vtkDataSetMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer,vtkTextMapper,vtkTextProperty
)def main():cellName = get_program_parameters()# Store the cell class names in a dictionary.cellMap = dict()cellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_LINE)] = VTK_LINEcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_EDGE)] = VTK_QUADRATIC_EDGEcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_CUBIC_LINE)] = VTK_CUBIC_LINEcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_TRIANGLE)] = VTK_TRIANGLEcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_TRIANGLE)] = VTK_QUADRATIC_TRIANGLEcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUAD)] = VTK_QUADcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_QUAD)] = VTK_QUADRATIC_QUADcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_TETRA)] = VTK_TETRAcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_HEXAHEDRON)] = VTK_HEXAHEDRONcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_WEDGE)] = VTK_WEDGEcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_PYRAMID)] = VTK_PYRAMIDcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_WEDGE)] = VTK_QUADRATIC_WEDGEcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_PYRAMID)] = VTK_QUADRATIC_PYRAMIDcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_HEXAHEDRON)] = VTK_QUADRATIC_HEXAHEDRONcellMap[vtkCellTypes.GetClassNameFromTypeId(VTK_QUADRATIC_TETRA)] = VTK_QUADRATIC_TETRAif cellName not in cellMap:print('Cell type ', cellName, ' is not supported.')returnsource = vtkCellTypeSource()source.SetCellType(cellMap[cellName])source.Update()print('Cell: ', cellName)originalPoints = source.GetOutput().GetPoints()points = vtkPoints()points.SetNumberOfPoints(source.GetOutput().GetNumberOfPoints())rng = vtkMinimalStandardRandomSequence()rng.SetSeed(5070)  # for testingfor i in range(0, points.GetNumberOfPoints()):perturbation = [0.0] * 3for j in range(0, 3):rng.Next()perturbation[j] = rng.GetRangeValue(-0.1, 0.1)currentPoint = [0.0] * 3originalPoints.GetPoint(i, currentPoint)points.SetPoint(i, currentPoint[0] + perturbation[0],currentPoint[1] + perturbation[1],currentPoint[2] + perturbation[2])source.GetOutput().SetPoints(points)numCells = source.GetOutput().GetNumberOfCells()print('Number of cells: ', numCells)idArray = vtkIntArray()idArray.SetNumberOfTuples(numCells)for i in range(0, numCells):idArray.InsertTuple1(i, i + 1)idArray.SetName('Ids')source.GetOutput().GetCellData().AddArray(idArray)source.GetOutput().GetCellData().SetActiveScalars('Ids')shrink = vtkShrinkFilter()shrink.SetInputConnection(source.GetOutputPort())shrink.SetShrinkFactor(.8)tessellate = vtkTessellatorFilter()tessellate.SetInputConnection(shrink.GetOutputPort())tessellate.SetMaximumNumberOfSubdivisions(3)# Create a lookup table to map cell data to colors.lut = vtkLookupTable()colorSeries = vtkColorSeries()seriesEnum = colorSeries.BREWER_QUALITATIVE_SET3colorSeries.SetColorScheme(seriesEnum)colorSeries.BuildLookupTable(lut, colorSeries.ORDINAL)# Fill in a few known colors, the rest will be generated if needed.colors = vtkNamedColors()# Create a mapper and actor.mapper = vtkDataSetMapper()mapper.SetInputConnection(source.GetOutputPort())mapper.SetInputConnection(shrink.GetOutputPort())mapper.SetScalarRange(0, numCells + 1)mapper.SetLookupTable(lut)mapper.SetScalarModeToUseCellData()mapper.SetResolveCoincidentTopologyToPolygonOffset()if (source.GetCellType() == VTK_QUADRATIC_PYRAMID orsource.GetCellType() == VTK_QUADRATIC_WEDGE):mapper.SetInputConnection(shrink.GetOutputPort())else:mapper.SetInputConnection(tessellate.GetOutputPort())actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().EdgeVisibilityOn()#  actor.GetProperty().SetLineWidth(3)textProperty = vtkTextProperty()textProperty.SetFontSize(20)textProperty.SetJustificationToCentered()textProperty.SetColor(colors.GetColor3d('Lamp_Black'))textMapper = vtkTextMapper()textMapper.SetInput(cellName)textMapper.SetTextProperty(textProperty)textActor = vtkActor2D()textActor.SetMapper(textMapper)textActor.SetPosition(320, 20)# Create a renderer, render window, and interactor.renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName('CellTypeSource')renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actors to the scene.renderer.AddViewProp(textActor)renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('Silver'))renderer.ResetCamera()renderer.GetActiveCamera().Azimuth(30)renderer.GetActiveCamera().Elevation(30)renderer.ResetCameraClippingRange()# Render and interact.renderWindow.SetSize(640, 480)renderWindow.Render()renderWindowInteractor.Start()def get_program_parameters():import argparsedescription = 'Cell Type Source.'epilogue = '''You can supply an optional argument consisting of a vtkCell name e.g: vtkTriangle.The default is vtkTetra.'''parser = argparse.ArgumentParser(description=description, epilog=epilogue,formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument('cell_name', nargs='?', const='vtkTetra', default='vtkTetra', type=str, help='The cell name.')args = parser.parse_args()return args.cell_nameif __name__ == '__main__':main()

在这里插入图片描述

ConvexPointSet

Description

vtkConvexPointSet object represents a 3D cell defined by a convex set of points. An example of such a cell is an
octant (from an octree).

vtkConvexPointSet uses the ordered triangulations approach (vtkOrderedTriangulator) to create triangulations guaranteed
to be compatible across shared faces.

# !/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (vtkConvexPointSet,vtkPolyData,vtkUnstructuredGrid
)
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkDataSetMapper,vtkGlyph3DMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():cps = vtkConvexPointSet()points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 0, 0)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(0, 1, 0)points.InsertNextPoint(0, 0, 1)points.InsertNextPoint(1, 0, 1)points.InsertNextPoint(1, 1, 1)points.InsertNextPoint(0, 1, 1)points.InsertNextPoint(0.5, 0, 0)points.InsertNextPoint(1, 0.5, 0)points.InsertNextPoint(0.5, 1, 0)points.InsertNextPoint(0, 0.5, 0)points.InsertNextPoint(0.5, 0.5, 0)for i in range(0, 13):cps.GetPointIds().InsertId(i, i)ug = vtkUnstructuredGrid()ug.Allocate(1, 1)ug.InsertNextCell(cps.GetCellType(), cps.GetPointIds())ug.SetPoints(points)colors = vtkNamedColors()mapper = vtkDataSetMapper()mapper.SetInputData(ug)actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetColor(colors.GetColor3d("Tomato"))actor.GetProperty().SetLineWidth(3)actor.GetProperty().EdgeVisibilityOn()# Glyph the pointssphere = vtkSphereSource()sphere.SetPhiResolution(21)sphere.SetThetaResolution(21)sphere.SetRadius(.03)# Create a polydata to store everything inpolyData = vtkPolyData()polyData.SetPoints(points)pointMapper = vtkGlyph3DMapper()pointMapper.SetInputData(polyData)pointMapper.SetSourceConnection(sphere.GetOutputPort())pointActor = vtkActor()pointActor.SetMapper(pointMapper)pointActor.GetProperty().SetColor(colors.GetColor3d("Peacock"))# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName("ConvexPointSet")renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actors to the scenerenderer.AddActor(actor)renderer.AddActor(pointActor)renderer.SetBackground(colors.GetColor3d("Silver"))renderer.ResetCamera()renderer.GetActiveCamera().Azimuth(210)renderer.GetActiveCamera().Elevation(30)renderer.ResetCameraClippingRange()# Render and interactrenderWindow.SetSize(640, 480)renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Disk

Description

vtkDiskSource objects creates a polygonal disk with a hole in the center.
The disk has zero height. The user can specify the inner and outer radius of the disk, and the radial and
circumferential resolution of the polygonal representation.

#!/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersSources import vtkDiskSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()diskSource = vtkDiskSource()# Create a mapper and actor.mapper = vtkPolyDataMapper()mapper.SetInputConnection(diskSource.GetOutputPort())actor = vtkActor()actor.GetProperty().SetColor(colors.GetColor3d("Cornsilk"))actor.SetMapper(mapper)# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName("Disk")renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actors to the scenerenderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d("DarkGreen"))# Render and interactrenderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

ShrinkCube

Description

Generates a cube using vtkCubeSource, then a shrink filter is applied.

vtkShrinkFilter object shrinks cells composing an arbitrary data set towards their centroid. The centroid of a cell is computed as the average position of the cell points. Shrinking results in disconnecting the cells from one another.

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersGeneral import vtkShrinkFilter
from vtkmodules.vtkFiltersSources import vtkCubeSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkDataSetMapper,vtkProperty,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Create a cube.cubeSource = vtkCubeSource()shrink = vtkShrinkFilter()shrink.SetInputConnection(cubeSource.GetOutputPort())shrink.SetShrinkFactor(0.9)# Create a mapper and actor.mapper = vtkDataSetMapper()mapper.SetInputConnection(shrink.GetOutputPort())back = vtkProperty()back.SetColor(colors.GetColor3d('Tomato'))actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().EdgeVisibilityOn()actor.GetProperty().SetColor(colors.GetColor3d('Banana'))actor.SetBackfaceProperty(back)# Create a renderer, render window, and interactor.renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actors to the scenerenderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('Silver'))renderer.ResetCamera()renderer.GetActiveCamera().Azimuth(30)renderer.GetActiveCamera().Elevation(30)renderer.ResetCameraClippingRange()# Render and interactrenderWindow.SetWindowName('ShrinkCube')renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

SourceObjectsDemo

#!/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingFreeType
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersSources import (vtkConeSource,vtkCubeSource,vtkCylinderSource,vtkDiskSource,vtkLineSource,vtkPlaneSource,vtkPointSource,vtkSphereSource,vtkTextSource
)
from vtkmodules.vtkRenderingCore import (vtkActor,vtkActor2D,vtkPolyDataMapper,vtkProperty,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer,vtkTextMapper,vtkTextProperty
)def main():colors = vtkNamedColors()# Set the background color.colors.SetColor('BkgColor', [51, 77, 102, 255])sourceObjects = list()sourceObjects.append(vtkSphereSource())sourceObjects[-1].SetPhiResolution(21)sourceObjects[-1].SetThetaResolution(21)sourceObjects.append(vtkConeSource())sourceObjects[-1].SetResolution(51)sourceObjects.append(vtkCylinderSource())sourceObjects[-1].SetResolution(51)sourceObjects.append(vtkCubeSource())sourceObjects.append(vtkPlaneSource())sourceObjects.append(vtkTextSource())sourceObjects[-1].SetText('Hello')sourceObjects[-1].BackingOff()sourceObjects.append(vtkPointSource())sourceObjects[-1].SetNumberOfPoints(500)sourceObjects.append(vtkDiskSource())sourceObjects[-1].SetCircumferentialResolution(51)sourceObjects.append(vtkLineSource())renderers = list()mappers = list()actors = list()textmappers = list()textactors = list()# Create one text property for all.textProperty = vtkTextProperty()textProperty.SetFontSize(16)textProperty.SetJustificationToCentered()textProperty.SetColor(colors.GetColor3d('LightGoldenrodYellow'))backProperty = vtkProperty()backProperty.SetColor(colors.GetColor3d('Tomato'))# Create a source, renderer, mapper, and actor# for each object.for i in range(0, len(sourceObjects)):mappers.append(vtkPolyDataMapper())mappers[i].SetInputConnection(sourceObjects[i].GetOutputPort())actors.append(vtkActor())actors[i].SetMapper(mappers[i])actors[i].GetProperty().SetColor(colors.GetColor3d('PeachPuff'))actors[i].SetBackfaceProperty(backProperty)textmappers.append(vtkTextMapper())textmappers[i].SetInput(sourceObjects[i].GetClassName())textmappers[i].SetTextProperty(textProperty)textactors.append(vtkActor2D())textactors[i].SetMapper(textmappers[i])textactors[i].SetPosition(120, 16)renderers.append(vtkRenderer())gridDimensions = 3# We need a renderer even if there is no actor.for i in range(len(sourceObjects), gridDimensions ** 2):renderers.append(vtkRenderer())renderWindow = vtkRenderWindow()renderWindow.SetWindowName('SourceObjectsDemo')rendererSize = 300renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)for row in range(0, gridDimensions):for col in range(0, gridDimensions):index = row * gridDimensions + colx0 = float(col) / gridDimensionsy0 = float(gridDimensions - row - 1) / gridDimensionsx1 = float(col + 1) / gridDimensionsy1 = float(gridDimensions - row) / gridDimensionsrenderWindow.AddRenderer(renderers[index])renderers[index].SetViewport(x0, y0, x1, y1)if index > (len(sourceObjects) - 1):continuerenderers[index].AddActor(actors[index])renderers[index].AddActor(textactors[index])renderers[index].SetBackground(colors.GetColor3d('BkgColor'))renderers[index].ResetCamera()renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(30)renderers[index].GetActiveCamera().Zoom(0.8)renderers[index].ResetCameraClippingRange()interactor = vtkRenderWindowInteractor()interactor.SetRenderWindow(renderWindow)renderWindow.Render()interactor.Start()if __name__ == '__main__':main()

在这里插入图片描述

OrientedArrow

Description

This example illustrates how to create and display an arrow that passes through two points.

It demonstrates two different ways to apply the transform:

  1. Use vtkTransformPolyDataFilter to create a new transformed polydata. This method is useful if the transformed
    polydata is needed later in the pipeline, e.g. vtkGlyph3DFilter.

  2. Apply the transform directly to the actor using vtkProp3D’s SetUserMatrix. No new data is produced.

Switch between the two methods by #defining USER_MATRIX or leaving out the #define.

#!/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (vtkMath,vtkMinimalStandardRandomSequence
)
from vtkmodules.vtkCommonMath import vtkMatrix4x4
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter
from vtkmodules.vtkFiltersSources import (vtkArrowSource,vtkSphereSource
)
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)"""
There are two alternative ways to apply the transform.1) Use vtkTransformPolyDataFilter to create a new transformed polydata.This method is useful if the transformed polydata is neededlater in the pipelineTo do this, set USER_MATRIX = True2) Apply the transform directly to the actor using vtkProp3D's SetUserMatrix.No new data is produced.To do this, set USER_MATRIX = False
"""
USER_MATRIX = Truedef main():colors = vtkNamedColors()# Set the background color.colors.SetColor('BkgColor', [26, 51, 77, 255])# Create an arrow.arrowSource = vtkArrowSource()# Generate a random start and end pointstartPoint = [0] * 3endPoint = [0] * 3rng = vtkMinimalStandardRandomSequence()rng.SetSeed(8775070)  # For testing.for i in range(0, 3):rng.Next()startPoint[i] = rng.GetRangeValue(-10, 10)rng.Next()endPoint[i] = rng.GetRangeValue(-10, 10)# Compute a basisnormalizedX = [0] * 3normalizedY = [0] * 3normalizedZ = [0] * 3# The X axis is a vector from start to endvtkMath.Subtract(endPoint, startPoint, normalizedX)length = vtkMath.Norm(normalizedX)vtkMath.Normalize(normalizedX)# The Z axis is an arbitrary vector cross Xarbitrary = [0] * 3for i in range(0, 3):rng.Next()arbitrary[i] = rng.GetRangeValue(-10, 10)vtkMath.Cross(normalizedX, arbitrary, normalizedZ)vtkMath.Normalize(normalizedZ)# The Y axis is Z cross XvtkMath.Cross(normalizedZ, normalizedX, normalizedY)matrix = vtkMatrix4x4()# Create the direction cosine matrixmatrix.Identity()for i in range(0, 3):matrix.SetElement(i, 0, normalizedX[i])matrix.SetElement(i, 1, normalizedY[i])matrix.SetElement(i, 2, normalizedZ[i])# Apply the transformstransform = vtkTransform()transform.Translate(startPoint)transform.Concatenate(matrix)transform.Scale(length, length, length)# Transform the polydatatransformPD = vtkTransformPolyDataFilter()transformPD.SetTransform(transform)transformPD.SetInputConnection(arrowSource.GetOutputPort())# Create a mapper and actor for the arrowmapper = vtkPolyDataMapper()actor = vtkActor()if USER_MATRIX:mapper.SetInputConnection(arrowSource.GetOutputPort())actor.SetUserMatrix(transform.GetMatrix())else:mapper.SetInputConnection(transformPD.GetOutputPort())actor.SetMapper(mapper)actor.GetProperty().SetColor(colors.GetColor3d('Cyan'))# Create spheres for start and end pointsphereStartSource = vtkSphereSource()sphereStartSource.SetCenter(startPoint)sphereStartSource.SetRadius(0.8)sphereStartMapper = vtkPolyDataMapper()sphereStartMapper.SetInputConnection(sphereStartSource.GetOutputPort())sphereStart = vtkActor()sphereStart.SetMapper(sphereStartMapper)sphereStart.GetProperty().SetColor(colors.GetColor3d('Yellow'))sphereEndSource = vtkSphereSource()sphereEndSource.SetCenter(endPoint)sphereEndSource.SetRadius(0.8)sphereEndMapper = vtkPolyDataMapper()sphereEndMapper.SetInputConnection(sphereEndSource.GetOutputPort())sphereEnd = vtkActor()sphereEnd.SetMapper(sphereEndMapper)sphereEnd.GetProperty().SetColor(colors.GetColor3d('Magenta'))# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName('OrientedArrow')renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actor to the scenerenderer.AddActor(actor)renderer.AddActor(sphereStart)renderer.AddActor(sphereEnd)renderer.SetBackground(colors.GetColor3d('BkgColor'))# Render and interactrenderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

vtkShrinkPolyData

Description

This example gets the frustum from a camera and displays it on the screen.

#!/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import vtkPlanes
from vtkmodules.vtkFiltersGeneral import vtkShrinkPolyData
from vtkmodules.vtkFiltersSources import vtkFrustumSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkCamera,vtkPolyDataMapper,vtkProperty,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()camera = vtkCamera()camera.SetClippingRange(0.1, 0.4)planesArray = [0] * 24camera.GetFrustumPlanes(1.0, planesArray)planes = vtkPlanes()planes.SetFrustumPlanes(planesArray)frustumSource = vtkFrustumSource()frustumSource.ShowLinesOff()frustumSource.SetPlanes(planes)shrink = vtkShrinkPolyData()shrink.SetInputConnection(frustumSource.GetOutputPort())shrink.SetShrinkFactor(.9)mapper = vtkPolyDataMapper()mapper.SetInputConnection(shrink.GetOutputPort())back = vtkProperty()back.SetColor(colors.GetColor3d("Tomato"))actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().EdgeVisibilityOn()actor.GetProperty().SetColor(colors.GetColor3d("Banana"))actor.SetBackfaceProperty(back)# a renderer and render windowrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName("Frustum")renderWindow.AddRenderer(renderer)# an interactorrenderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# add the actors to the scenerenderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d("Silver"))# Position the camera so that we can see the frustumrenderer.GetActiveCamera().SetPosition(1, 0, 0)renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)renderer.GetActiveCamera().SetViewUp(0, 1, 0)renderer.GetActiveCamera().Azimuth(30)renderer.GetActiveCamera().Elevation(30)renderer.ResetCamera()# render an image (lights and cameras are created automatically)renderWindow.Render()# begin mouse interactionrenderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

# !/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (# VTK_HEXAGONAL_PRISM,# VTK_HEXAHEDRON,# VTK_LINE,# VTK_PENTAGONAL_PRISM,# VTK_PIXEL,# VTK_POLY_LINE,# VTK_POLY_VERTEX,# VTK_POLYGON,# VTK_PYRAMID,# VTK_QUAD,VTK_TETRA,# VTK_TRIANGLE,# VTK_TRIANGLE_STRIP,# VTK_VERTEX,# VTK_VOXEL,# VTK_WEDGE,vtkCellArray,vtkHexagonalPrism,vtkHexahedron,vtkLine,vtkPentagonalPrism,vtkPixel,vtkPolyLine,vtkPolyVertex,vtkPolygon,vtkPyramid,vtkQuad,vtkTetra,vtkTriangle,vtkTriangleStrip,vtkUnstructuredGrid,vtkVertex,vtkVoxel,vtkWedge
)
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkActor2D,vtkDataSetMapper,vtkGlyph3DMapper,vtkProperty,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer,vtkTextMapper,vtkTextProperty
)
from vtkmodules.vtkRenderingLabel import vtkLabeledDataMapperdef get_program_parameters():import argparsedescription = 'Demonstrate the linear cell types found in VTK. Numbers define ordering of the defining points.'epilogue = ''''''parser = argparse.ArgumentParser(description=description, epilog=epilogue,formatter_class=argparse.RawDescriptionHelpFormatter)group1 = parser.add_mutually_exclusive_group()group1.add_argument('-w', '--wireframe', action='store_true',help='Render a wireframe.')group1.add_argument('-b', '--backface', action='store_true',help='Display the back face in a different colour.')args = parser.parse_args()return args.wireframe, args.backfacedef main():wireframe_on, backface_on = get_program_parameters()titles = list()text_mappers = list()text_actors = list()u_grids = list()mappers = list()actors = list()renderers = list()u_grids.append(make_vertex())titles.append('VTK_VERTEX (=1)')u_grids.append(make_poly_vertex())titles.append('VTK_POLY_VERTEX (=2)')u_grids.append(make_line())titles.append('VTK_LINE (=3)')u_grids.append(make_polyline())titles.append('VTK_POLY_LINE (=4)')u_grids.append(make_triangle())titles.append('VTK_TRIANGLE (=5)')u_grids.append(make_triangle_strip())titles.append('VTK_TRIANGLE_STRIP (=6)')u_grids.append(make_polygon())titles.append('VTK_POLYGON (=7)')u_grids.append(make_pixel())titles.append('VTK_PIXEL (=8)')u_grids.append(make_quad())titles.append('VTK_QUAD (=9)')u_grids.append(make_tetra())titles.append('VTK_TETRA (=10)')u_grids.append(make_voxel())titles.append('VTK_VOXEL (=11)')u_grids.append(make_hexahedron())titles.append('VTK_HEXAHEDRON (=12)')u_grids.append(make_wedge())titles.append('VTK_WEDGE (=13)')u_grids.append(make_pyramid())titles.append('VTK_PYRAMID (=14)')u_grids.append(make_pentagonal_prism())titles.append('VTK_PENTAGONAL_PRISM (=15)')u_grids.append(make_hexagonal_prism())titles.append('VTK_HEXAGONAL_PRISM (=16)')colors = vtkNamedColors()ren_win = vtkRenderWindow()ren_win.SetWindowName('LinearCellDemo')iren = vtkRenderWindowInteractor()iren.SetRenderWindow(ren_win)# Create one sphere for allsphere = vtkSphereSource()sphere.SetPhiResolution(21)sphere.SetThetaResolution(21)sphere.SetRadius(.08)# Create one text property for alltext_property = vtkTextProperty()text_property.SetFontSize(10)text_property.SetJustificationToCentered()text_property.SetColor(colors.GetColor3d('Black'))back_property = vtkProperty()back_property.SetColor(colors.GetColor3d('MediumSeaGreen'))# Create and link the mappers actors and renderers together.for i in range(0, len(u_grids)):print('Creating:', titles[i])text_mappers.append(vtkTextMapper())text_actors.append(vtkActor2D())mappers.append(vtkDataSetMapper())actors.append(vtkActor())renderers.append(vtkRenderer())mappers[i].SetInputData(u_grids[i])actors[i].SetMapper(mappers[i])if wireframe_on:actors[i].GetProperty().SetRepresentationToWireframe()actors[i].GetProperty().SetLineWidth(2)actors[i].GetProperty().SetOpacity(1)actors[i].GetProperty().SetColor(colors.GetColor3d('Black'))else:actors[i].GetProperty().EdgeVisibilityOn()actors[i].GetProperty().SetLineWidth(3)actors[i].GetProperty().SetColor(colors.GetColor3d('Tomato'))if backface_on:actors[i].SetBackfaceProperty(back_property)actors[i].GetProperty().SetOpacity(1)else:actors[i].GetProperty().SetOpacity(0.5)renderers[i].AddViewProp(actors[i])text_mappers[i].SetInput(titles[i])text_actors[i].SetMapper(text_mappers[i])text_actors[i].SetPosition(50, 10)if wireframe_on:text_actors[i].GetProperty().SetColor(colors.GetColor3d('Black'))renderers[i].AddViewProp(text_actors[i])# Label the pointslabel_mapper = vtkLabeledDataMapper()label_mapper.SetInputData(u_grids[i])label_actor = vtkActor2D()label_actor.SetMapper(label_mapper)if wireframe_on:label_actor.GetProperty().SetColor(colors.GetColor3d('Snow'))renderers[i].AddViewProp(label_actor)# Glyph the pointspoint_mapper = vtkGlyph3DMapper()point_mapper.SetInputData(u_grids[i])point_mapper.SetSourceConnection(sphere.GetOutputPort())point_mapper.ScalingOn()point_mapper.ScalarVisibilityOff()point_actor = vtkActor()point_actor.SetMapper(point_mapper)if wireframe_on:point_actor.GetProperty().SetColor(colors.GetColor3d('Banana'))else:point_actor.GetProperty().SetColor(colors.GetColor3d('Banana'))point_actor.GetProperty().SetSpecular(.6)point_actor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)point_actor.GetProperty().SetSpecularPower(100)renderers[i].AddViewProp(point_actor)ren_win.AddRenderer(renderers[i])# Set up the viewportsgrid_dimensions_x = 4grid_dimensions_y = 4renderer_size = 300ren_win.SetSize(renderer_size * grid_dimensions_x, renderer_size * grid_dimensions_y)for row in range(0, grid_dimensions_y):for col in range(0, grid_dimensions_x):index = row * grid_dimensions_x + col# (xmin, ymin, xmax, ymax)viewport = [float(col) / grid_dimensions_x,float(grid_dimensions_y - (row + 1)) / grid_dimensions_y,float(col + 1) / grid_dimensions_x,float(grid_dimensions_y - row) / grid_dimensions_y]if index > (len(actors) - 1):# Add a renderer even if there is no actor.# This makes the render window background all the same color.ren = vtkRenderer()if wireframe_on:ren.SetBackground(colors.GetColor3d('LightSlateGray'))else:ren.SetBackground(colors.GetColor3d('SlateGray'))ren.SetViewport(viewport)ren_win.AddRenderer(ren)continueif wireframe_on:renderers[index].SetBackground(colors.GetColor3d('LightSlateGray'))else:renderers[index].SetBackground(colors.GetColor3d('SlateGray'))renderers[index].SetViewport(viewport)renderers[index].ResetCamera()if index == 0:renderers[index].GetActiveCamera().Dolly(0.1)renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)elif index == 1:renderers[index].GetActiveCamera().Dolly(0.8)renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)elif index == 2:renderers[index].GetActiveCamera().Dolly(0.4)renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)elif index == 4:renderers[index].GetActiveCamera().Dolly(0.7)renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)elif index == 5:renderers[index].GetActiveCamera().Dolly(1.1)renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)elif index == 6:renderers[index].GetActiveCamera().Azimuth(0)renderers[index].GetActiveCamera().Elevation(-45)elif index == 7:renderers[index].GetActiveCamera().Azimuth(0)renderers[index].GetActiveCamera().Elevation(-45)elif index == 8:renderers[index].GetActiveCamera().Azimuth(0)renderers[index].GetActiveCamera().Elevation(-45)elif index == 9:renderers[index].GetActiveCamera().Azimuth(0)renderers[index].GetActiveCamera().Elevation(-22.5)elif index == 10:renderers[index].GetActiveCamera().Azimuth(-22.5)renderers[index].GetActiveCamera().Elevation(15)elif index == 11:renderers[index].GetActiveCamera().Azimuth(-22.5)renderers[index].GetActiveCamera().Elevation(15)elif index == 12:renderers[index].GetActiveCamera().Azimuth(-45)renderers[index].GetActiveCamera().Elevation(15)elif index == 13:renderers[index].GetActiveCamera().Azimuth(0)renderers[index].GetActiveCamera().Elevation(-30)elif index == 14:renderers[index].GetActiveCamera().Azimuth(-22.5)renderers[index].GetActiveCamera().Elevation(10)elif index == 15:renderers[index].GetActiveCamera().Azimuth(-30)renderers[index].GetActiveCamera().Elevation(15)else:renderers[index].GetActiveCamera().Azimuth(30)renderers[index].GetActiveCamera().Elevation(-30)renderers[index].ResetCameraClippingRange()ren_win.Render()iren.Initialize()iren.Start()# These functions return a vtkUnstructured grid corresponding to the object.def make_vertex():# A vertex is a cell that represents a 3D pointnumber_of_vertices = 1points = vtkPoints()points.InsertNextPoint(0, 0, 0)vertex = vtkVertex()for i in range(0, number_of_vertices):vertex.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(vertex.GetCellType(), vertex.GetPointIds())return ugdef make_poly_vertex():# A polyvertex is a cell represents a set of 0D verticesnumber_of_vertices = 6points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 0, 0)points.InsertNextPoint(0, 1, 0)points.InsertNextPoint(0, 0, 1)points.InsertNextPoint(1, 0, 0.4)points.InsertNextPoint(0, 1, 0.6)poly_vertex = vtkPolyVertex()poly_vertex.GetPointIds().SetNumberOfIds(number_of_vertices)for i in range(0, number_of_vertices):poly_vertex.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(poly_vertex.GetCellType(), poly_vertex.GetPointIds())return ugdef make_line():# A line is a cell that represents a 1D pointnumber_of_vertices = 2points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(0.5, 0.5, 0)line = vtkLine()for i in range(0, number_of_vertices):line.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(line.GetCellType(), line.GetPointIds())return ugdef make_polyline():# A polyline is a cell that represents a set of 1D linesnumber_of_vertices = 5points = vtkPoints()points.InsertNextPoint(0, 0.5, 0)points.InsertNextPoint(0.5, 0, 0)points.InsertNextPoint(1, 0.3, 0)points.InsertNextPoint(1.5, 0.4, 0)points.InsertNextPoint(2.0, 0.4, 0)polyline = vtkPolyLine()polyline.GetPointIds().SetNumberOfIds(number_of_vertices)for i in range(0, number_of_vertices):polyline.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(polyline.GetCellType(), polyline.GetPointIds())return ugdef make_triangle():# A triangle is a cell that represents a 1D pointnumber_of_vertices = 3points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(0.5, 0.5, 0)points.InsertNextPoint(.2, 1, 0)triangle = vtkTriangle()for i in range(0, number_of_vertices):triangle.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(triangle.GetCellType(), triangle.GetPointIds())return ugdef make_triangle_strip():# A triangle is a cell that represents a triangle stripnumber_of_vertices = 10points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, -.1, 0)points.InsertNextPoint(0.5, 1, 0)points.InsertNextPoint(2.0, -0.1, 0)points.InsertNextPoint(1.5, 0.8, 0)points.InsertNextPoint(3.0, 0, 0)points.InsertNextPoint(2.5, 0.9, 0)points.InsertNextPoint(4.0, -0.2, 0)points.InsertNextPoint(3.5, 0.8, 0)points.InsertNextPoint(4.5, 1.1, 0)trianglestrip = vtkTriangleStrip()trianglestrip.GetPointIds().SetNumberOfIds(number_of_vertices)for i in range(0, number_of_vertices):trianglestrip.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(trianglestrip.GetCellType(), trianglestrip.GetPointIds())return ugdef make_polygon():# A polygon is a cell that represents a polygonnumber_of_vertices = 6points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, -0.1, 0)points.InsertNextPoint(0.8, 0.5, 0)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(0.6, 1.2, 0)points.InsertNextPoint(0, 0.8, 0)polygon = vtkPolygon()polygon.GetPointIds().SetNumberOfIds(number_of_vertices)for i in range(0, number_of_vertices):polygon.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(polygon.GetCellType(), polygon.GetPointIds())return ugdef make_pixel():# A pixel is a cell that represents a pixelpixel = vtkPixel()pixel.GetPoints().SetPoint(0, 0, 0, 0)pixel.GetPoints().SetPoint(1, 1, 0, 0)pixel.GetPoints().SetPoint(2, 0, 1, 0)pixel.GetPoints().SetPoint(3, 1, 1, 0)pixel.GetPointIds().SetId(0, 0)pixel.GetPointIds().SetId(1, 1)pixel.GetPointIds().SetId(2, 2)pixel.GetPointIds().SetId(3, 3)ug = vtkUnstructuredGrid()ug.SetPoints(pixel.GetPoints())ug.InsertNextCell(pixel.GetCellType(), pixel.GetPointIds())return ugdef make_quad():# A quad is a cell that represents a quadquad = vtkQuad()quad.GetPoints().SetPoint(0, 0, 0, 0)quad.GetPoints().SetPoint(1, 1, 0, 0)quad.GetPoints().SetPoint(2, 1, 1, 0)quad.GetPoints().SetPoint(3, 0, 1, 0)quad.GetPointIds().SetId(0, 0)quad.GetPointIds().SetId(1, 1)quad.GetPointIds().SetId(2, 2)quad.GetPointIds().SetId(3, 3)ug = vtkUnstructuredGrid()ug.SetPoints(quad.GetPoints())ug.InsertNextCell(quad.GetCellType(), quad.GetPointIds())return ugdef make_tetra():# Make a tetrahedron.number_of_vertices = 4points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 0, 0)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(0, 1, 1)tetra = vtkTetra()for i in range(0, number_of_vertices):tetra.GetPointIds().SetId(i, i)cell_array = vtkCellArray()cell_array.InsertNextCell(tetra)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.SetCells(VTK_TETRA, cell_array)return ugdef make_voxel():# A voxel is a representation of a regular grid in 3-D space.number_of_vertices = 8points = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 0, 0)points.InsertNextPoint(0, 1, 0)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(0, 0, 1)points.InsertNextPoint(1, 0, 1)points.InsertNextPoint(0, 1, 1)points.InsertNextPoint(1, 1, 1)voxel = vtkVoxel()for i in range(0, number_of_vertices):voxel.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(voxel.GetCellType(), voxel.GetPointIds())return ugdef make_hexahedron():# A regular hexagon (cube) with all faces square and three squares around# each vertex is created below.# Set up the coordinates of eight points# (the two faces must be in counter-clockwise# order as viewed from the outside).number_of_vertices = 8# Create the pointspoints = vtkPoints()points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(1, 0, 0)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(0, 1, 0)points.InsertNextPoint(0, 0, 1)points.InsertNextPoint(1, 0, 1)points.InsertNextPoint(1, 1, 1)points.InsertNextPoint(0, 1, 1)# Create a hexahedron from the pointshexhedr = vtkHexahedron()for i in range(0, number_of_vertices):hexhedr.GetPointIds().SetId(i, i)# Add the points and hexahedron to an unstructured gridug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(hexhedr.GetCellType(), hexhedr.GetPointIds())return ugdef make_wedge():# A wedge consists of two triangular ends and three rectangular faces.number_of_vertices = 6points = vtkPoints()points.InsertNextPoint(0, 1, 0)points.InsertNextPoint(0, 0, 0)points.InsertNextPoint(0, 0.5, 0.5)points.InsertNextPoint(1, 1, 0)points.InsertNextPoint(1, 0.0, 0.0)points.InsertNextPoint(1, 0.5, 0.5)wedge = vtkWedge()for i in range(0, number_of_vertices):wedge.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(wedge.GetCellType(), wedge.GetPointIds())return ugdef make_pyramid():# Make a regular square pyramid.number_of_vertices = 5points = vtkPoints()p0 = [1.0, 1.0, 0.0]p1 = [-1.0, 1.0, 0.0]p2 = [-1.0, -1.0, 0.0]p3 = [1.0, -1.0, 0.0]p4 = [0.0, 0.0, 1.0]points.InsertNextPoint(p0)points.InsertNextPoint(p1)points.InsertNextPoint(p2)points.InsertNextPoint(p3)points.InsertNextPoint(p4)pyramid = vtkPyramid()for i in range(0, number_of_vertices):pyramid.GetPointIds().SetId(i, i)ug = vtkUnstructuredGrid()ug.SetPoints(points)ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds())return ugdef make_pentagonal_prism():pentagonal_prism = vtkPentagonalPrism()pentagonal_prism.GetPointIds().SetId(0, 0)pentagonal_prism.GetPointIds().SetId(1, 1)pentagonal_prism.GetPointIds().SetId(2, 2)pentagonal_prism.GetPointIds().SetId(3, 3)pentagonal_prism.GetPointIds().SetId(4, 4)pentagonal_prism.GetPointIds().SetId(5, 5)pentagonal_prism.GetPointIds().SetId(6, 6)pentagonal_prism.GetPointIds().SetId(7, 7)pentagonal_prism.GetPointIds().SetId(8, 8)pentagonal_prism.GetPointIds().SetId(9, 9)scale = 2.0pentagonal_prism.GetPoints().SetPoint(0, 11 / scale, 10 / scale, 10 / scale)pentagonal_prism.GetPoints().SetPoint(1, 13 / scale, 10 / scale, 10 / scale)pentagonal_prism.GetPoints().SetPoint(2, 14 / scale, 12 / scale, 10 / scale)pentagonal_prism.GetPoints().SetPoint(3, 12 / scale, 14 / scale, 10 / scale)pentagonal_prism.GetPoints().SetPoint(4, 10 / scale, 12 / scale, 10 / scale)pentagonal_prism.GetPoints().SetPoint(5, 11 / scale, 10 / scale, 14 / scale)pentagonal_prism.GetPoints().SetPoint(6, 13 / scale, 10 / scale, 14 / scale)pentagonal_prism.GetPoints().SetPoint(7, 14 / scale, 12 / scale, 14 / scale)pentagonal_prism.GetPoints().SetPoint(8, 12 / scale, 14 / scale, 14 / scale)pentagonal_prism.GetPoints().SetPoint(9, 10 / scale, 12 / scale, 14 / scale)ug = vtkUnstructuredGrid()ug.SetPoints(pentagonal_prism.GetPoints())ug.InsertNextCell(pentagonal_prism.GetCellType(), pentagonal_prism.GetPointIds())return ugdef make_hexagonal_prism():hexagonal_prism = vtkHexagonalPrism()hexagonal_prism.GetPointIds().SetId(0, 0)hexagonal_prism.GetPointIds().SetId(1, 1)hexagonal_prism.GetPointIds().SetId(2, 2)hexagonal_prism.GetPointIds().SetId(3, 3)hexagonal_prism.GetPointIds().SetId(4, 4)hexagonal_prism.GetPointIds().SetId(5, 5)hexagonal_prism.GetPointIds().SetId(6, 6)hexagonal_prism.GetPointIds().SetId(7, 7)hexagonal_prism.GetPointIds().SetId(8, 8)hexagonal_prism.GetPointIds().SetId(9, 9)hexagonal_prism.GetPointIds().SetId(10, 10)hexagonal_prism.GetPointIds().SetId(11, 11)scale = 2.0hexagonal_prism.GetPoints().SetPoint(0, 11 / scale, 10 / scale, 10 / scale)hexagonal_prism.GetPoints().SetPoint(1, 13 / scale, 10 / scale, 10 / scale)hexagonal_prism.GetPoints().SetPoint(2, 14 / scale, 12 / scale, 10 / scale)hexagonal_prism.GetPoints().SetPoint(3, 13 / scale, 14 / scale, 10 / scale)hexagonal_prism.GetPoints().SetPoint(4, 11 / scale, 14 / scale, 10 / scale)hexagonal_prism.GetPoints().SetPoint(5, 10 / scale, 12 / scale, 10 / scale)hexagonal_prism.GetPoints().SetPoint(6, 11 / scale, 10 / scale, 14 / scale)hexagonal_prism.GetPoints().SetPoint(7, 13 / scale, 10 / scale, 14 / scale)hexagonal_prism.GetPoints().SetPoint(8, 14 / scale, 12 / scale, 14 / scale)hexagonal_prism.GetPoints().SetPoint(9, 13 / scale, 14 / scale, 14 / scale)hexagonal_prism.GetPoints().SetPoint(10, 11 / scale, 14 / scale, 14 / scale)hexagonal_prism.GetPoints().SetPoint(11, 10 / scale, 12 / scale, 14 / scale)ug = vtkUnstructuredGrid()ug.SetPoints(hexagonal_prism.GetPoints())ug.InsertNextCell(hexagonal_prism.GetCellType(), hexagonal_prism.GetPointIds())return ugif __name__ == '__main__':main()

在这里插入图片描述

RegularPolygonSource

Description

This example creates a pentagon

#!/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersGeneral import vtkShrinkPolyData
from vtkmodules.vtkFiltersSources import vtkRegularPolygonSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkProperty,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Create a pentagonpolygonSource = vtkRegularPolygonSource()polygonSource.SetNumberOfSides(5)polygonSource.SetRadius(5)polygonSource.SetCenter(0, 0, 0)shrink = vtkShrinkPolyData()shrink.SetInputConnection(polygonSource.GetOutputPort())shrink.SetShrinkFactor(0.9)mapper = vtkPolyDataMapper()mapper.SetInputConnection(shrink.GetOutputPort())back = vtkProperty()back.SetColor(colors.GetColor3d('Tomato'))actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().EdgeVisibilityOn()actor.GetProperty().SetLineWidth(5)actor.GetProperty().SetColor(colors.GetColor3d('Banana'))actor.SetBackfaceProperty(back)renderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName('RegularPolygonSource')renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('Silver'))renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

Vertex

Description

The vertex is a primary zero-dimensional cell. It is defined by a single point.

#!/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (vtkCellArray,vtkPolyData,vtkVertex
)
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()points = vtkPoints()points.InsertNextPoint(0, 0, 0)vertex = vtkVertex()vertex.GetPointIds().SetId(0, 0)vertices = vtkCellArray()vertices.InsertNextCell(vertex)polydata = vtkPolyData()polydata.SetPoints(points)polydata.SetVerts(vertices)# Setup actor and mappermapper = vtkPolyDataMapper()mapper.SetInputData(polydata)actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetPointSize(30)actor.GetProperty().SetColor(colors.GetColor3d('PeachPuff'))# Setup render window, renderer, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.SetWindowName('Vertex')renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('DarkGreen'))renderWindow.Render()renderWindowInteractor.Start()if __name__ == '__main__':main()

在这里插入图片描述

ParametricSuperEllipsoidDemo

#!/usr/bin/env python
# -*- coding: utf-8 -*-# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonComputationalGeometry import vtkParametricSuperEllipsoid
from vtkmodules.vtkCommonCore import (vtkCommand,vtkMath
)
from vtkmodules.vtkFiltersSources import vtkParametricFunctionSource
from vtkmodules.vtkInteractionWidgets import (vtkSliderRepresentation2D,vtkSliderWidget
)
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkProperty,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Set the background color.colors.SetColor('BkgColor', [26, 51, 102, 255])surface = vtkParametricSuperEllipsoid()source = vtkParametricFunctionSource()renderer = vtkRenderer()mapper = vtkPolyDataMapper()actor = vtkActor()backProperty = vtkProperty()backProperty.SetColor(colors.GetColor3d('Tomato'))# Create a parametric function source, renderer, mapper, and actorsource.SetParametricFunction(surface)mapper.SetInputConnection(source.GetOutputPort())actor.SetMapper(mapper)actor.SetBackfaceProperty(backProperty)actor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana'))actor.GetProperty().SetSpecular(.5)actor.GetProperty().SetSpecularPower(20)renderWindow = vtkRenderWindow()renderWindow.SetWindowName('ParametricSuperEllipsoidDemo')renderWindow.AddRenderer(renderer)renderWindow.SetSize(640, 480)renderer.AddActor(actor)renderer.SetBackground(colors.GetColor3d('BkgColor'))renderer.ResetCamera()renderer.GetActiveCamera().Azimuth(30)renderer.GetActiveCamera().Elevation(-30)renderer.GetActiveCamera().Zoom(0.9)renderer.ResetCameraClippingRange()interactor = vtkRenderWindowInteractor()interactor.SetRenderWindow(renderWindow)# Setup a slider widget for each varying parametertubeWidth = 0.008sliderLength = 0.008titleHeight = 0.04labelHeight = 0.04sliderRepN1 = vtkSliderRepresentation2D()sliderRepN1.SetMinimumValue(0.0)sliderRepN1.SetMaximumValue(4.0)sliderRepN1.SetValue(1.0)sliderRepN1.SetTitleText('Z squareness')sliderRepN1.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()sliderRepN1.GetPoint1Coordinate().SetValue(.1, .1)sliderRepN1.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()sliderRepN1.GetPoint2Coordinate().SetValue(.9, .1)sliderRepN1.SetTubeWidth(tubeWidth)sliderRepN1.SetSliderLength(sliderLength)sliderRepN1.SetTitleHeight(titleHeight)sliderRepN1.SetLabelHeight(labelHeight)sliderWidgetN1 = vtkSliderWidget()sliderWidgetN1.SetInteractor(interactor)sliderWidgetN1.SetRepresentation(sliderRepN1)sliderWidgetN1.SetAnimationModeToAnimate()sliderWidgetN1.EnabledOn()sliderWidgetN1.AddObserver(vtkCommand.InteractionEvent, SliderCallbackN1(surface))sliderRepN2 = vtkSliderRepresentation2D()sliderRepN2.SetMinimumValue(0.0001)sliderRepN2.SetMaximumValue(4.0)sliderRepN2.SetValue(1.0)sliderRepN2.SetTitleText('XY squareness')sliderRepN2.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()sliderRepN2.GetPoint1Coordinate().SetValue(.1, .9)sliderRepN2.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()sliderRepN2.GetPoint2Coordinate().SetValue(.9, .9)sliderRepN2.SetTubeWidth(tubeWidth)sliderRepN2.SetSliderLength(sliderLength)sliderRepN2.SetTitleHeight(titleHeight)sliderRepN2.SetLabelHeight(labelHeight)sliderWidgetN2 = vtkSliderWidget()sliderWidgetN2.SetInteractor(interactor)sliderWidgetN2.SetRepresentation(sliderRepN2)sliderWidgetN2.SetAnimationModeToAnimate()sliderWidgetN2.EnabledOn()sliderWidgetN2.AddObserver(vtkCommand.InteractionEvent, SliderCallbackN2(surface))sliderRepMinimumV = vtkSliderRepresentation2D()sliderRepN1.SetMinimumValue(.0001)sliderRepMinimumV.SetMaximumValue(.9999 * vtkMath.Pi())sliderRepMinimumV.SetValue(.0001)sliderRepMinimumV.SetTitleText('V min')sliderRepMinimumV.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()sliderRepMinimumV.GetPoint1Coordinate().SetValue(.1, .1)sliderRepMinimumV.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()sliderRepMinimumV.GetPoint2Coordinate().SetValue(.1, .9)sliderRepMinimumV.SetTubeWidth(tubeWidth)sliderRepMinimumV.SetSliderLength(sliderLength)sliderRepMinimumV.SetTitleHeight(titleHeight)sliderRepMinimumV.SetLabelHeight(labelHeight)surface.SetN1(1.0)surface.SetN2(1.0)renderer.ResetCamera()renderer.GetActiveCamera().Azimuth(30)renderer.GetActiveCamera().Elevation(-30)renderer.GetActiveCamera().Zoom(0.9)renderer.ResetCameraClippingRange()renderWindow.Render()interactor.Initialize()interactor.Start()# These callbacks do the actual work.
# Callbacks for the interactionsclass SliderCallbackN1():def __init__(self, superEllipsoid):self.superEllipsoid = superEllipsoiddef __call__(self, caller, ev):sliderWidget = callervalue = sliderWidget.GetRepresentation().GetValue()self.superEllipsoid.SetN1(value)class SliderCallbackN2():def __init__(self, superEllipsoid):self.superEllipsoid = superEllipsoiddef __call__(self, caller, ev):sliderWidget = callervalue = sliderWidget.GetRepresentation().GetValue()self.superEllipsoid.SetN2(value)if __name__ == '__main__':main()

请添加图片描述

vtkEarthSource

#!/usr/bin/env python# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersHybrid import vtkEarthSource
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (vtkActor,vtkPolyDataMapper,vtkRenderWindow,vtkRenderWindowInteractor,vtkRenderer
)def main():colors = vtkNamedColors()# Earth sourceearthSource = vtkEarthSource()earthSource.OutlineOn()earthSource.Update()r = earthSource.GetRadius()# Create a spheresphere = vtkSphereSource()sphere.SetThetaResolution(100)sphere.SetPhiResolution(100)sphere.SetRadius(earthSource.GetRadius())# Create a mapper and actormapper = vtkPolyDataMapper()mapper.SetInputConnection(earthSource.GetOutputPort())actor = vtkActor()actor.SetMapper(mapper)actor.GetProperty().SetColor(colors.GetColor3d('Black'))sphereMapper = vtkPolyDataMapper()sphereMapper.SetInputConnection(sphere.GetOutputPort())sphereActor = vtkActor()sphereActor.SetMapper(sphereMapper)sphereActor.GetProperty().SetColor(colors.GetColor3d('PeachPuff'))# Create a renderer, render window, and interactorrenderer = vtkRenderer()renderWindow = vtkRenderWindow()renderWindow.AddRenderer(renderer)renderWindowInteractor = vtkRenderWindowInteractor()renderWindowInteractor.SetRenderWindow(renderWindow)# Add the actor to the scenerenderer.AddActor(actor)renderer.AddActor(sphereActor)renderer.SetBackground(colors.GetColor3d('Black'))renderWindow.SetSize(640, 480)renderWindow.SetWindowName('EarthSource')# Render and interactrenderWindow.Render()# # screenshot code:# w2if = vtkWindowToImageFilter()# w2if.SetInput(renderWindow)# w2if.Update()## writer = vtkPNGWriter()# writer.SetFileName('TestEarthSource.png')# writer.SetInputConnection(w2if.GetOutputPort())# writer.Write()# begin interactionrenderWindowInteractor.Start()if __name__ == '__main__':main()

请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/324798.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java - Json字符串转List<LinkedHashMap<String,String>>

需求&#xff1a;在处理数据时&#xff0c;需要将一个Object类型对象集合转为有序的Map类型集合。 一、问题 1.原代码&#xff1a; 但在使用时出现报错&#xff1a; Incompatible equality constraint: LinkedHashMap<String, String> and LinkedHashMap 不兼容的相等…

【软考】模拟考卷错题本2024-05-11

1 设计模式- 适配器模式 基本上上述的图解已经涵盖了绝大多数主流的设计模式和其特点。理解记忆下即可&#xff0c;这里对下午的考题也有帮助的。 2 计算机组成原理 cpu 访问速度 这个真的是憨憨咯~看到内存就选内存&#xff0c;题目都没审好。这里的速度比cpu内部的要比外部的…

【C语言】动态内存管理

一、为什么有动态内存分配 在进入正文前&#xff0c;我们简单了解一下变量在内存中的位置&#xff08;在最后具体讲&#xff09;&#xff1a; 函数形参&#xff0c;局部变量&#xff1a;栈区 动态开辟的空间&#xff1a;堆区 全局变量&#xff0c;静态变量&#xff08;static修…

【QVariant类型剖析】

QVariant类型剖析 &#x1f31f; 官方文档中给出的定义&#x1f31f; 特性&#x1f338;QVariant实战应用&#x1f338;项目成果展示 &#x1f31f; 官方文档中给出的定义 &#x1f4d8;Because C forbids unions from including types that have non-default constructors or…

Rancher-Kubewarden-保姆级教学-含Demo测试

一、什么是Kubewarden&#xff1f; What is Kubewarden? | Kubewarden 1、就是容器集群的准入策略引擎。 1、使用的策略其实就是k8s原生的security context. 2、使用WebAssembly来编写策略。 1、WebAssembly&#xff0c;可以使用擅长的开发语言来编写策略。&#xff08;下面的…

SVM直观理解

https://tangshusen.me/2018/10/27/SVM/ https://www.bilibili.com/video/BV16T4y1y7qj/?spm_id_from333.337.search-card.all.click&vd_source8272bd48fee17396a4a1746c256ab0ae SVM是什么? 先来看看维基百科上对SVM的定义: 支持向量机&#xff08;英语&#xff1a;su…

【Linux系列】file命令

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

Kafka效率篇-提升效率三板斧

kafka在效率上做了很多的努力。最初的一个使用场景是处理网页上活跃的数据&#xff0c;它往往有非常大的体量&#xff0c;每个页面都能产生数十条写入。而且我们假设每条消息都会被至少一个消费者消费&#xff08;通常是多个&#xff09;&#xff0c;因此&#xff0c;我们努力让…

HTML【常用的标签】、CSS【选择器】

day45 HTML 继day44&#xff0c;w3cschool 常用的标签 k) 表格 表格由 table 标签来定义。每个表格均有若干行&#xff08;由 tr 标签定义&#xff09;&#xff0c;每行被分割为若干单元格&#xff08;由 标签定义&#xff09;。字母 td指表格数据&#xff08;table data&…

Linux线程(二)线程互斥

目录 一、为什么需要线程互斥 二、线程互斥的必要性 三、票务问题举例&#xff08;多个线程并发的操作共享变量引发问题&#xff09; 四、互斥锁的用法 1.互斥锁的原理 2、互斥锁的使用 1、初始化互斥锁 2、加锁和解锁 3、销毁互斥锁&#xff08;动态分配时需要&#…

【BUUCTF】Crypto_RSA(铜锁/openssl使用系列)

【BUUCTF】Crypto_RSA&#xff08;铜锁/openssl使用系列&#xff09; 1、题目 在一次RSA密钥对生成中&#xff0c;假设p473398607161&#xff0c;q4511491&#xff0c;e17 求解出d作为flga提交 2、解析 RSA加密过程&#xff1a; 1&#xff09;选择素数&#xff1a;选择两个不…

Zabbix监控中文乱码问题解决方法

一、问题描述 1.查看Zabbix仪表盘 在Zabbix的监控仪表盘界面&#xff0c;字体显示为“方框”&#xff0c;无法查看到具体的性能指标名称。 2.问题分析 Zabbix的web端没有中文字库&#xff0c;导致切换到中文页面&#xff0c;中文成了乱码这个问题&#xff0c;我们最需要把中文…

服务器远程桌面局域网连接不上的解决方法

在企业网络环境中&#xff0c;服务器远程桌面局域网连接不上是一个常见且棘手的问题。这种问题可能导致工作效率下降&#xff0c;甚至影响业务运营。因此&#xff0c;我们需要采取专业的方法来解决这一问题。 服务器远程桌面局域网连接不上的解决方法&#xff1a; 1、确保服务器…

Qt服务器端与客户端交互

Qt做客户端与服务器端交互第一步引入network 第一步引入network后继续编程首先界面设计 创建server和socket 引入QTcpServer&#xff0c;QTcpSocket MainWindow.h代码如下 #ifndef MAINWINDOW_H #define MAINWINDOW_H#include <QMainWindow> #include <QTcpServer&…

Cisco WLC 2504控制器重启后所有AP掉线故障-系统日期时间

1 故障描述 现场1台WLC 2504控制器掉电重启后&#xff0c;所有AP均无线上线&#xff0c; 正常时共有18个AP在线&#xff0c;而当前为0 AP在线数量为0 (Cisco Controller) >show ap sumNumber of APs.................................... 0Global AP User Name..........…

LeetCode 106.从中序与后序遍历序列构造二叉树

LeetCode 106.从中序与后序遍历序列构造二叉树 1、题目 题目链接&#xff1a;106. 从中序与后序遍历序列构造二叉树 给定两个整数数组 inorder 和 postorder &#xff0c;其中 inorder 是二叉树的中序遍历&#xff0c; postorder 是同一棵树的后序遍历&#xff0c;请你构造并…

SSM【Spring SpringMVC Mybatis】——Mybatis

目录 1、初识Mybatis 1.1Mybatis简介 1.2 官网地址 2、搭建Mybatis框架 2.1 准备 2.2 搭建Mybatis框架步骤 1. 导入jar包 2. 编写核心配置文件【mybatis-config.xml】 3. 书写相关接口及映射文件 4. 测试【SqlSession】 2.3 添加Log4j日志框架 导入jar包 编写配置文…

hive日常使用时忘记部分补充(不定时)

1、date_formate、unix_timestamp、from_unixtime用法&#xff1a; 2、lag&#xff08;&#xff09;、lead()用法&#xff1a; lag&#xff08;)窗口函数返回分区中当前行之前行&#xff08;可以指定第几行&#xff09;的值。 如果没有行&#xff0c;则返回null。 lead()窗口…

搭建Docker私服镜像仓库Harbor

1、概述 Harbor是由VMware公司开源的企业级的Docker Registry管理项目&#xff0c;它包括权限管理(RBAC)、LDAP、日志审核、管理界面、自我注册、镜像复制和中文支持等功能。 Harbor 的所有组件都在 Dcoker 中部署&#xff0c;所以 Harbor 可使用 Docker Compose 快速部署。 …

C++ | Leetcode C++题解之第80题删除有序数组中的重复项II

题目&#xff1a; 题解&#xff1a; class Solution { public:int removeDuplicates(vector<int>& nums) {int n nums.size();if (n < 2) {return n;}int slow 2, fast 2;while (fast < n) {if (nums[slow - 2] ! nums[fast]) {nums[slow] nums[fast];slo…