Vtk,(visualization toolkit)是一个开源的免费软件系统,主要用于三维计算机图形学、图像处理和可视化。Vtk是在面向对象原理的基础上设计和实现的,它的内核是用C++构建的,包含有大约250,000行代码,2000多个类,还包含有几个转换界面,因此也可以自由的通过Java,Tcl/Tk和Python各种语言使用vtk。以下介绍VTK对于STL图像的基本操作
STL图像加载、缩放、旋转
import os
import vtk
base_file = "E:\\study\\company\\model"
test_file = "dongmai.stl"
actor = vtk.vtkActor()
def show(file_name):
# load stl file
reader = vtk.vtkSTLReader()
reader.SetFileName(file_name)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(reader.GetOutputPort())
actor.SetMapper(mapper)
# actor.RotateY(45)
# Create a rendering window and renderer
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
# Create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Assign actor to the renderer
ren.AddActor(actor)
# Enable user interface interactor
iren.Initialize()
renWin.Render()
iren.Start()
return iren
# 绕x轴旋转
def rotate_x(num):
actor.RotateX(num)
def rotate_y(num):
actor.RotateY(num)
def rotate_z(num):
actor.RotateZ(num)
# 设置方向
def set_origin(x, y, z):
actor.SetOrientation(x, y, z)
def get_origin():
return actor.GetOrientation()
# 缩放
def set_scale(x, y, z):
actor.SetScale(x, y, z)
def main():
show(os.path.join(base_file, test_file))
if __name__ == ‘__main__‘:
main()
显示结果
鼠标事件监听
# 监听事件
class MyEvent(vtk.vtkInteractorStyleTrackballCamera):
def __init__(self, parent=None):
# 鼠标中键
self.AddObserver("MiddleButtonPressEvent", self.middle_button_press_event)
self.AddObserver("MiddleButtonReleaseEvent", self.middle_button_release_event)
# 鼠标左键
self.AddObserver("LeftButtonPressEvent", self.left_button_press_event)
self.AddObserver("LeftButtonReleaseEvent", self.left_button_release_event)
# 鼠标右键
self.AddObserver("RightButtonPressEvent", self.right_button_press_event)
self.AddObserver("RightButtonReleaseEvent", self.right_button_release_event)
def middle_button_press_event(self, obj, event):
print("Middle Button pressed")
self.OnMiddleButtonDown()
return
def middle_button_release_event(self, obj, event):
print("Middle Button released")
self.OnMiddleButtonUp()
return
def left_button_press_event(self, obj, event):
print("Left Button pressed")
self.OnLeftButtonDown()
return
def left_button_release_event(self, obj, event):
print("Left Button released")
self.OnLeftButtonUp()
return
def right_button_press_event(self, obj, event):
print("right Button pressed")
self.OnRightButtonDown()
return
def right_button_release_event(self, obj, event):
print("right Button released")
self.OnLeftButtonUp()
return
# 引入上一段代码调用
iren.SetInteractorStyle(MyEvent())
结果
参考文档
VTK笔记——模型的空间变换(Transform).平移、旋转和缩放
原文地址:https://www.cnblogs.com/zhhfan/p/10312170.html
时间: 2024-11-06 11:41:51