八月 5

python VTK 笔记:几何的旋转和平移

在python vtk中,我们可以使用transform进行转换,也可以直接使用actor.SetUserMatrix方法对原几何进行旋转和平移

import vtk
import numpy as np

# create two cones, rotate one of them.

# create a rendering window and renderer
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
WIDTH = 640
HEIGHT = 480
renWin.SetSize(WIDTH, HEIGHT)

# create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# create cone
source = vtk.vtkConeSource()
source.SetResolution(60)
source.SetCenter(-2, 0, 0)

# create a transform that rotates the cone
transform = vtk.vtkTransform()

matrix = np.array([[1, 0, 0, 0],
                   [0, 1, 0, 0],
                   [0, 0, 1, 2],
                   [0, 0, 0, 1]])
obj_mat = vtk.vtkMatrix4x4()
for i in range(4):
    for j in range(4):
        obj_mat.SetElement(i, j, matrix[i, j])

transform.SetMatrix(obj_mat)
transformFilter = vtk.vtkTransformPolyDataFilter()
transformFilter.SetTransform(transform)
transformFilter.SetInputConnection(source.GetOutputPort())
transformFilter.Update()

# mapper for original cone
coneMapper1 = vtk.vtkPolyDataMapper()
coneMapper1.SetInputConnection(source.GetOutputPort())

# another mapper for the rotated cone
coneMapper2 = vtk.vtkPolyDataMapper()
coneMapper2.SetInputConnection(transformFilter.GetOutputPort())

matrix2 = np.array([[0, 1, 0, 0],
                   [1, 0, 0, 0],
                   [0, 0, 1, 0],
                   [0, 0, 0, 1]])
obj_mat2 = vtk.vtkMatrix4x4()
for i in range(4):
    for j in range(4):
        obj_mat2.SetElement(i, j, matrix2[i, j])
# actor for original cone
actor1 = vtk.vtkActor()

# 直接使用变换矩阵进行旋转和平移
actor1.SetUserMatrix(obj_mat2)
actor1.SetMapper(coneMapper1)

# actor for rotated cone
actor2 = vtk.vtkActor()
actor2.SetMapper(coneMapper2)

# color the original cone red
actor1.GetProperty().SetColor(1, 0, 0)  # (R,G,B)
# color rotated cone blue
actor2.GetProperty().SetColor(0, 0, 1)  # (R,G,B)

# assign actor to the renderer
ren.AddActor(actor1)
ren.AddActor(actor2)

# enable user interface interactor
iren.Initialize()
renWin.Render()
iren.Start()


文章由安静原创,发表于www.ajnote.com。转载请注明出处

发表 2020年8月5日 自 anjing 类别 "python VTK学习笔记

发表评论

电子邮件地址不会被公开。 必填项已用*标注