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.mzph.cn/bicheng/10338.shtml

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

相关文章

标准参编征集|《第三方运维服务水平评价指南 工业废水处理设施》

目前&#xff0c;对于工业废水处理设施第三方运维服务的标准&#xff0c;国家和行业未曾出台有针对性的评价标准和规范&#xff0c;工业企业和工业园区对第三方运维服务的监督、考核、评价体系需要进一步补充和完善。 本标准的编制旨在帮助第三方运营单位从运营技术和管理举措…

PDF文件恢复:四种实用方法全解析

如何恢复已删除的PDF文件&#xff1f; PDF是Portable Document Format&#xff08;便携式文档格式&#xff09;的缩写&#xff0c;是一种由Adobe Systems开发的文件格式。PDF文件可以包含文本、图形、链接、多媒体以及其他各种元素&#xff0c;并且能够在各种操作系统和设备上…

[数据集][目标检测]纸箱子检测数据集VOC+YOLO格式8375张1类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;8375 标注数量(xml文件个数)&#xff1a;8375 标注数量(txt文件个数)&#xff1a;8375 标注…

车辆充电桩|基于Springboot+vue的车辆充电桩管理系统的设计与实现(源码+数据库+文档)

车辆充电桩管理系统 目录 基于Springboot&#xff0b;vue的车辆充电桩管理系统设计与实现 一、前言 二、系统设计 三、系统功能设计 1 前台功能模块 4.1.1 首页功能 4.1.2 用户后台管理 2 后台功能模块 4.2.1 管理员功能 4.2.2 维修员功能 四、数据库设计 五、核…

解决“电脑开机黑屏Explorer进程卡死“问题

今天&#xff0c;给台式机按电源键&#xff0c;进入windows系统时&#xff0c;发现电脑黑屏了&#xff0c;昨天还好好的&#xff0c;怎么今天电脑桌面进不去了&#xff1f;想起Windows XP、Windows 7、Windows 10 、Windows 11等系统&#xff0c;在使用多个文件拷贝时&#xff…

AI写作推荐-写文ai-AI在线写作生成器-3步完成写作任务

AI写作利器&#xff1a;推荐几款神助攻文案创作工具 随着技术的进步&#xff0c;人工智能&#xff08;AI&#xff09;已达到高级水平&#xff0c;在众多领域展现其强大能力。 在文本创作的领域&#xff0c;人工智能&#xff08;AI&#xff09;应用已显著地提升了写作效率和创意…

2024数维杯数学建模B题生物质和煤共热解问题的研究原创论文分享

大家好&#xff0c;从昨天肝到现在&#xff0c;终于完成了2024数维杯数学建模挑战赛B题的完整论文啦。 实在精力有限&#xff0c;具体的讲解大家可以去讲解视频&#xff1a; 2024数维杯数学建模B题煤共热解每一问高质量完整代码讲解&#xff01;_哔哩哔哩_bilibili 2024数维杯…

学习Java的日子 Day44 初识前端

Day44 HTML 学习路线&#xff1a; 前端&#xff1a;展示页面、与用户交互 — HTML 后端&#xff1a;数据的交互和传递 — JavaEE/JavaWeb 1.B/S和C/S B/S&#xff1a;浏览器/服务器 教务系统 C/S&#xff1a;客户端/服务器 优缺点 1.开发/维护成本&#xff1a;B/S相对低 2.运算…

IPv6资产测绘哪家强?揭秘新一代网络空间资产测绘平台的独门秘籍

网络空间资产测绘&#xff0c;即通过一系列技术手段&#xff0c;对网络中的各类资产进行全面的发现、分类和定位&#xff0c;为各类用户提供精准的数据支撑和决策依据。网络空间资产测绘作为一门新兴的交叉学科&#xff0c;融合了计算机网络技术、数据挖掘、人工智能、信息安全…

解构复合人工智能系统(Compound AI Systems):关键术语、理论、思路、实践经验

编者按&#xff1a; 大模型的出现为构建更智能、更复杂的人工智能系统带来了新的契机。然而&#xff0c;单一的大模型难以应对现实世界中错综复杂的问题&#xff0c;需要与其他模块相结合&#xff0c;构建出复合人工智能系统&#xff08;Compound AI Systems&#xff09;。 本文…

Python经典案例爬取豆瓣Top250电影数据

随着网络数据的日益丰富&#xff0c;如何从海量的信息中快速、准确地提取出有价值的数据&#xff0c;成为了许多开发者和技术爱好者关注的焦点。在这个过程中&#xff0c;网络爬虫技术凭借其强大的数据获取能力&#xff0c;成为了数据分析和挖掘的重要工具。本文将通过一个经典…

修改表空间对应数据文件的大小

Oracle从入门到总裁:​​​​​​https://blog.csdn.net/weixin_67859959/article/details/135209645 表空间与数据文件紧密相连&#xff0c;相互依存&#xff0c;创建表空间的时候需设置数据文件大小。 在后期实际应用中&#xff0c;如果实际存储的数据量超出事先设置的数据…

Spring-Bean 作用域

作用域 作用域案例 public class BeanScopeDemo {AutowiredQualifier("singletonPerson")Person person;AutowiredQualifier("prototypePerson")Person person1;AutowiredQualifier("prototypePerson")Person person2;AutowiredSet<Person&g…

程序环境和预处理、编译链接过程、编译的几个阶段、运行环境、预定义符号等的介绍

文章目录 前言一、程序的翻译环境和执行环境二、编译链接过程三、编译的几个阶段四、运行环境五、预定义符号总结 前言 程序环境和预处理、编译链接过程、编译的几个阶段、运行环境、预定义符号的介绍。 一、程序的翻译环境和执行环境 在 ANSI C 的任何一种实现中&#xff0c…

CLIP 浅析

CLIP 浅析 文章目录 CLIP 浅析概述如何训练CLIP如何使用Clip进行图像分类优缺点分析优点缺点 概述 CLIP的英文全称是Contrastive Language-Image Pre-training&#xff0c;即一种基于对比文本-图像对的预训练方法或者模型。 如何训练CLIP CLIP包括两个模型&#xff1a;Text …

【数据结构】顺序表与链表的差异

顺序表和链表都是线性表&#xff0c;它们有着相似的部分&#xff0c;但是同时也有着很大的差异。 存储空间上的差异&#xff1a; 对于插入上的不同点&#xff0c;顺序表在空间不够时需要扩容&#xff0c;而如果在使用realloc函数去扩容&#xff0c;会有原地扩容和异地扩容两种情…

Spring Security基础教程:从入门到实战

作者介绍&#xff1a;✌️大厂全栈码农|毕设实战开发&#xff0c;专注于大学生项目实战开发、讲解和毕业答疑辅导。 推荐订阅精彩专栏 &#x1f447;&#x1f3fb; 避免错过下次更新 Springboot项目精选实战案例 更多项目&#xff1a;CSDN主页YAML墨韵 学如逆水行舟&#xff0c…

电脑复制和粘贴的时候会出现Hello!

电脑不管是Microsoft Excel还是Microsoft Word复制之后粘贴过来就出现HELLO&#xff0c;当复制粘贴文件的时候就会出现WINFILE&#xff1b; 具体现象看下面两个图片&#xff1a; 这是因为winfile 文件病毒&#xff08;幽灵蠕虫病毒&#xff09;,每月的28号发作&#xff1b; 症状…

wangEditor富文本编辑器与layui图片上传

记录&#xff1a;js 显示默认的wangEditor富文本编辑器内容和图片 <style>body {background-color: #ffffff;}.layui-form-select dl{z-index:100000;} </style> <div class"layui-form layuimini-form"><div class"layui-form-item"…

ubuntu系统在有无NVIDIA驱动下查看显卡型号

在ubuntu系统下&#xff0c;分别在有nvidia显卡驱动和无nvidia显卡驱动时&#xff0c;查看nvidia显卡型号。 1、有nvidia显卡驱动时的查看方式 nvidia-smi -L会显示如下信息&#xff1a; GPU 0: NVIDIA GEForce GTX 1660 SUPER (UUID: GPU-*****)2、无nvidia显卡驱动时的查看…