def __init__(self): super(PointsShow, self).__init__() self._screen_size = QApplication.primaryScreen().size() # WIDGET self._widget = QWidget(self) self._widget.setAttribute(Qt.WA_TranslucentBackground) self.setCentralWidget(self._widget) self._widget.resize(self._screen_size) # VTK self._vtk_widget = QVTKRenderWindowInteractor(self._widget) self._vtk_widget.SetInteractorStyle(all.vtkInteractorStyleMultiTouchCamera()) self._vtk_widget.resize(self._screen_size) self._ren_win = self._vtk_widget.GetRenderWindow() self._render = all.vtkRenderer() sw, sh = self._screen_size.width(), self._screen_size.height() self.resize(int(sw * 0.9), int(sh * 0.9)) self.move(int(sw * (1 - 0.8) / 2), int(sh * (1 - 0.8) / 2)) # POINTS self._points = VtkPoints(size=3, opacity=1) self._render.AddActor(self._points.actor) # LINE self._lines = VtkLine(color=(1, 0, 0), width=4) self._lines.set_point([0.0, 0.0, 0.0]) self._lines.set_point([1.0, 0.0, 0.0]) self._lines.set_line(0, 0) self._render.AddActor(self._lines.actor) # COPY_FUN self.add_points = self._points.add_points self.set_color = self._points.set_color # SHOW self._ren_win.AddRenderer(self._render) self._vtk_widget.Start() self._render.Render()
def init_vtk_view(self): # 在之前创建的view_widget上添加vtk控件 self.vtk_vertical_layout = QVBoxLayout(self.view_widget) self.vtk_widget = QVTKRenderWindowInteractor(self.view_widget) self.vtk_vertical_layout.addWidget(self.vtk_widget) # 1.创建RenderWindow窗口 self.render_window = self.vtk_widget.GetRenderWindow() # 2.创建render self.renderer = vtk.vtkRenderer() self.renderer.SetBackground(1.0, 1.0, 1.0) # 设置页面底部颜色值 self.renderer.SetBackground2(0.1, 0.2, 0.4) # 设置页面顶部颜色值 self.renderer.SetGradientBackground(1) # 开启渐变色背景设置 self.render_window.AddRenderer(self.renderer) self.render_window.Render() # 3.设置交互方式 self.iren = self.render_window.GetInteractor() # 获取交互器 self.style = vtk.vtkInteractorStyleTrackballCamera( ) # 交互器样式的一种,该样式下,用户是通过控制相机对物体作旋转、放大、缩小等操作 # self.style = MyInteractor(self) self.style.SetDefaultRenderer(self.renderer) self.iren.SetInteractorStyle(self.style) # 拾取器 cellPicker = vtk.vtkCellPicker() self.iren.SetPicker(cellPicker) # 4.添加坐标轴(加self,血的教训) axesActor = vtk.vtkAxesActor() self.axes_widget = vtk.vtkOrientationMarkerWidget() self.axes_widget.SetOrientationMarker(axesActor) self.axes_widget.SetInteractor(self.iren) self.axes_widget.EnabledOn() self.axes_widget.InteractiveOff() # 坐标系是否可移动 # 5.添加Actor self.original_actor = vtk.vtkActor()
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.frame = QtWidgets.QFrame() self.vl = QtWidgets.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.vtkWidget) self.dicom_image_path = './IM-0008-0034.dcm' # '----------set up dicom reader---------------' self.dcmReader = vtk.vtkDICOMImageReader() self.dcmReader.SetDataByteOrderToLittleEndian() self.dcmReader.SetDirectoryName( r"D:\Users\user\Desktop\NTUCT\1323\Ct_Without_ContrastBrain - 1323\InnerEar_C_06_U70u_4" ) self.dcmReader.Update() # '----------init render---------------' self.ren = vtk.vtkRenderer() # '---------set up mapper----------' self.slice_mapper = vtk.vtkImageSliceMapper() self.slice_mapper.SetInputConnection(self.dcmReader.GetOutputPort()) # set random slice number # self.slice_mapper.SetSliceNumber(50) # set up image_slice self.image_slice = vtk.vtkImageSlice() self.image_slice.SetMapper(self.slice_mapper) # '-----set up window and level of image_slice----' # self.MinMax = self.dcmReader.GetOutput().GetScalarRange() # self.image_slice_property = self.image_slice.GetProperty() # self.image_slice_property.SetColorWindow(self.MinMax[1]) # self.image_slice_property.SetColorLevel((self.MinMax[1] - self.MinMax[0]) / 2) # self.image_slice.Update() # '---------set image_slice as input for renderer------' self.ren.AddViewProp(self.image_slice) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self.dcmReader.GetOutputPort()) # # Create an actor # actor = vtk.vtkActor() # actor.SetMapper(mapper) # self.ren.AddActor(actor) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() self.ren.ResetCamera() self.frame.setLayout(self.vl) self.setCentralWidget(self.frame) self.show() self.iren.Initialize()
def close(self) -> None: """Quit application.""" if self._closed: return if hasattr(self, "render_timer"): self.render_timer.stop() BasePlotter.close(self) QVTKRenderWindowInteractor.close(self)
def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.frame = QtWidgets.QFrame() self.vl = QtWidgets.QVBoxLayout() self.QtInteractor = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.QtInteractor) self.dicom_image_path = 'IM-0008-0034.dcm' # '----------set up dicom reader---------------' self.dcmReader = vtk.vtkDICOMImageReader() self.dcmReader.SetDataByteOrderToLittleEndian() self.dcmReader.SetFileName(self.dicom_image_path) self.dcmReader.Update() # '----------init render---------------' self.ren = vtk.vtkRenderer() # show the dicom flie self.imageViewer = vtk.vtkImageViewer2() self.imageViewer.SetInputConnection(self.dcmReader.GetOutputPort()) self.renderWindowInteractor = vtk.vtkRenderWindowInteractor() self.imageViewer.SetupInteractor(self.renderWindowInteractor) self.imageViewer.Render() self.imageViewer.GetRenderer().ResetCamera() self.imageViewer.Render() self.renderWindowInteractor.Start()
def __init__(self, ui: Ui_MainWindow, led: LedWall): super().__init__() # SIGNAL SIGNAL.sign_is_online.connect(self._is_online) self._screen_size = QApplication.primaryScreen().size() # WIDGET self._widget = QWidget(self) self._widget.setAttribute(Qt.WA_TranslucentBackground) self.setCentralWidget(self._widget) self.resize(self._screen_size) self._widget.setStyleSheet(""" QWidget { border: 1px solid black; background-color: rgba(255, 255, 255, 0.2); } """) # VTK_WIDGET self._vtk_widget = QVTKRenderWindowInteractor(self._widget) self._vtk_widget.SetInteractorStyle(all.vtkInteractorStyleMultiTouchCamera()) self._vtk_widget.resize(self._screen_size) self._ren_win = self._vtk_widget.GetRenderWindow() self._render = VtkRenderer(ren_win=self._ren_win) # SCREEN_SIZE sw, sh = self._screen_size.width(), self._screen_size.height() self.resize(int(sw * 0.7), int(sh * 0.7)) self.move(int(sw * 0.3 / 2), int(sh * 0.3 / 2)) # UI self._ui = ui self._ui.setupUi(self._widget) # TCP_LED self._tcp_led = {1: self._ui.led_bot1, 2: self._ui.led_bot2} # LED self._led = led self._led.set_render(render=self._render) # BTN self._ui.link.stateChanged.connect(self._set_link) # COLOR self._ui.btn_r.clicked.connect(self._set_r) self._ui.btn_g.clicked.connect(self._set_g) self._ui.btn_b.clicked.connect(self._set_b) self._ui.btn_colorful.clicked.connect(self._set_colorful) # SHOW self._ui.btn_img.clicked.connect(self._read_img) self._ui.btn_video.clicked.connect(self._read_video) # VTK_START self._vtk_widget.Start()
def init3dWidget(self): widget3d = QVTKRenderWindowInteractor() widget3d.Initialize() widget3d.Start() self.render = vtk.vtkRenderer() self.render.SetBackground(params.BackgroundColor) widget3d.GetRenderWindow().AddRenderer(self.render) self.interactor = widget3d.GetRenderWindow().GetInteractor() self.interactor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() self.axesWidget = gui_utils.createAxes(self.interactor) return widget3d
def __init__( self, parent: MainWindow = None, title: str = None, off_screen: bool = None, multi_samples: int = None, line_smoothing: bool = False, point_smoothing: bool = False, polygon_smoothing: bool = False, auto_update: Union[float, bool] = 5.0, **kwargs: Any, ) -> None: # pylint: disable=too-many-branches """Initialize Qt interactor.""" LOG.debug("QtInteractor init start") self.url: QtCore.QUrl = None # Cannot use super() here because # QVTKRenderWindowInteractor silently swallows all kwargs # because they use **kwargs in their constructor... qvtk_kwargs = dict(parent=parent) for key in ("stereo", "iren", "rw", "wflags"): if key in kwargs: qvtk_kwargs[key] = kwargs.pop(key) with _no_base_plotter_init(): QVTKRenderWindowInteractor.__init__(self, **qvtk_kwargs) BasePlotter.__init__(self, **kwargs) # backward compat for when we had this as a separate class self.interactor = self if multi_samples is None: multi_samples = global_theme.multi_samples self.setAcceptDrops(True) # Create and start the interactive renderer self.ren_win = self.GetRenderWindow() self.ren_win.SetMultiSamples(multi_samples) if line_smoothing: self.ren_win.LineSmoothingOn() if point_smoothing: self.ren_win.PointSmoothingOn() if polygon_smoothing: self.ren_win.PolygonSmoothingOn() for renderer in self.renderers: renderer.view_isometric() self.ren_win.AddRenderer(renderer) self.render_signal.connect(self._render) self.key_press_event_signal.connect(super().key_press_event) self.background_color = global_theme.background if self.title: self.setWindowTitle(title) if off_screen is None: off_screen = pyvista.OFF_SCREEN self._setup_interactor(off_screen) if off_screen: self.ren_win.SetOffScreenRendering(1) else: self._setup_key_press() # Make the render timer but only activate if using auto update self.render_timer = QTimer(parent=parent) if float(auto_update) > 0.0: # Can be False as well # Spawn a thread that updates the render window. # Sometimes directly modifiying object data doesn't trigger # Modified() and upstream objects won't be updated. This # ensures the render window stays updated without consuming too # many resources. twait = int((auto_update ** -1) * 1000.0) self.render_timer.timeout.connect(self.render) self.render_timer.start(twait) if global_theme.depth_peeling["enabled"]: if self.enable_depth_peeling(): for renderer in self.renderers: renderer.enable_depth_peeling() self._first_time = False # Crucial! LOG.debug("QtInteractor init stop")
def __init__(self, parent=None, dcm_dir='', view_plane='Transverse'): """ 建立DICOM VTK 畫布 :param dcm_dir: 影像路徑 :param view_plane: 切面:預設'Transverse',可選'Coronal','Sagittal' """ QtWidgets.QMainWindow.__init__(self, parent) self.frame = QtWidgets.QFrame() self.vl = QtWidgets.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self) self.vl.addWidget(self.vtkWidget) if dcm_dir != '': self.dcm_series_path = Path(dcm_dir).expanduser() # set up VTK dicom reader self.dcmReader = vtkDICOMImageReader() self.dcmReader.SetDataByteOrderToLittleEndian() self.dcmReader.SetDirectoryName(str(self.dcm_series_path)) self.dcmRescaleSlope = self.dcmReader.GetRescaleSlope() self.dcmRescaleOffset = self.dcmReader.GetRescaleOffset() self.dcmReader.Update() # '------default with WW & WL-----' self.ww = 3500 # WW self.wl = 600 # WL # '----------viewer---------' self.dcmViewer = vtk.vtkImageViewer2() self.dcmViewer.SetInputConnection(self.dcmReader.GetOutputPort()) self.dcmViewer.SetColorLevel(500) self.dcmViewer.SetColorWindow(3500) self.dcmViewer.SetSize(600, 600) self.dcmViewer.UpdateDisplayExtent() # #!下面那一行確保不會多渲染出一個視窗物件! ## self.dcmViewer.SetRenderWindow( self.vtkWidget.GetRenderWindow()) # #!這一行確保不會多渲染出一個視窗物件! # # # #!上面那一行確保不會多渲染出一個視窗物件! ## # 下面三個方法可渲染不同人體不同的切面 self.viewPlane = view_plane if self.viewPlane == 'Coronal': self.dcmViewer.SetSliceOrientationToXZ() # 冠狀面 (Coronal plane) elif self.viewPlane == 'Sagittal': self.dcmViewer.SetSliceOrientationToYZ() # 縱切面 (Sagittal plane) else: self.dcmViewer.SetSliceOrientationToXY( ) # Default: 橫狀面 (Transverse plane) # '----------TextOverLay---------' # slice status message self.sliceTextProp = vtk.vtkTextProperty() self.sliceTextProp.SetFontFamilyToCourier() self.sliceTextProp.SetFontSize(60) self.sliceTextProp.SetVerticalJustificationToBottom() self.sliceTextProp.SetJustificationToLeft() # '---------set up Text Overlay mapper----------' self.sliceTextMapper = vtk.vtkTextMapper() self.current_slice = self.dcmViewer.GetSlice() print('cur_slice = ', self.current_slice, ' viewer.GetSliceMax() = ', self.dcmViewer.GetSliceMax()) msg = ( ' %d / %d ' % (self.dcmViewer.GetSlice() + 1, self.dcmViewer.GetSliceMax() + 1)) self.sliceTextMapper.SetInput(msg) # '---------set up Text Overlay Actor----------' self.sliceTextActor = vtk.vtkActor2D() self.sliceTextActor.SetMapper(self.sliceTextMapper) self.sliceTextActor.SetPosition(15, 10) # ########--Get RENDERER--############ self.renderer = self.dcmViewer.GetRenderer() self.renderer.AddActor2D(self.sliceTextActor) # ########--Set Up RENDER Window--############ self.renderWindow = self.vtkWidget.GetRenderWindow() self.renderWindow.AddRenderer(self.renderer) self.vtkWidget.GetRenderWindow().AddRenderer(self.renderer) # '--------- Interactor ----------' self.inter = self.renderWindow.GetInteractor() # ----!Stay in 2D View!----- self.inter.SetInteractorStyle( vtkInteractionStyle.vtkInteractorStyleImage()) # '----------add keyboard observer---------' self.vtkWidget.AddObserver(vtk.vtkCommand.KeyPressEvent, self.keyboard_callback_func) self.cam = self.renderer.GetActiveCamera() if self.viewPlane == 'Coronal': # self.cam.SetFocalPoint(0, 0, 0) # 设焦点 # self.cam.SetPosition(0, 0, -1) # Camera in Z so it display XY planes. # 设观察对象位 self.cam.SetViewUp( 0, 0, -1 ) # Up direction is the X not the y. #(0,0,-1) for Coronal plane # self.cam.ComputeViewPlaneNormal() # 自动 self.renderer.ResetCamera() self.frame.setLayout(self.vl) self.setCentralWidget(self.frame) self.show() self.inter.Initialize()
class GuiNUC(QMainWindow): def __init__(self, ui: Ui_MainWindow, led: LedWall): super().__init__() # SIGNAL SIGNAL.sign_is_online.connect(self._is_online) self._screen_size = QApplication.primaryScreen().size() # WIDGET self._widget = QWidget(self) self._widget.setAttribute(Qt.WA_TranslucentBackground) self.setCentralWidget(self._widget) self.resize(self._screen_size) self._widget.setStyleSheet(""" QWidget { border: 1px solid black; background-color: rgba(255, 255, 255, 0.2); } """) # VTK_WIDGET self._vtk_widget = QVTKRenderWindowInteractor(self._widget) self._vtk_widget.SetInteractorStyle(all.vtkInteractorStyleMultiTouchCamera()) self._vtk_widget.resize(self._screen_size) self._ren_win = self._vtk_widget.GetRenderWindow() self._render = VtkRenderer(ren_win=self._ren_win) # SCREEN_SIZE sw, sh = self._screen_size.width(), self._screen_size.height() self.resize(int(sw * 0.7), int(sh * 0.7)) self.move(int(sw * 0.3 / 2), int(sh * 0.3 / 2)) # UI self._ui = ui self._ui.setupUi(self._widget) # TCP_LED self._tcp_led = {1: self._ui.led_bot1, 2: self._ui.led_bot2} # LED self._led = led self._led.set_render(render=self._render) # BTN self._ui.link.stateChanged.connect(self._set_link) # COLOR self._ui.btn_r.clicked.connect(self._set_r) self._ui.btn_g.clicked.connect(self._set_g) self._ui.btn_b.clicked.connect(self._set_b) self._ui.btn_colorful.clicked.connect(self._set_colorful) # SHOW self._ui.btn_img.clicked.connect(self._read_img) self._ui.btn_video.clicked.connect(self._read_video) # VTK_START self._vtk_widget.Start() def _is_online(self, bot_id, is_online, ip, port): QTools.set_led_style(ui_btn=self._tcp_led[bot_id], color=[0, CONST.SHOW.COLOR[CONST.SHOW.G], 0] if is_online else [CONST.SHOW.COLOR[CONST.SHOW.R], 0, 0]) def _set_r(self): for bot_id, ui_drv_id in {1: self._ui.drv_bot1, 2: self._ui.drv_bot2}.items(): if ui_drv_id.isChecked(): self._led[bot_id].set_r() def _set_g(self): for bot_id, ui_drv_id in {1: self._ui.drv_bot1, 2: self._ui.drv_bot2}.items(): if ui_drv_id.isChecked(): self._led[bot_id].set_g() def _set_b(self): for bot_id, ui_drv_id in {1: self._ui.drv_bot1, 2: self._ui.drv_bot2}.items(): if ui_drv_id.isChecked(): self._led[bot_id].set_b() def _set_colorful(self): for bot_id, ui_drv_id in {1: self._ui.drv_bot1, 2: self._ui.drv_bot2}.items(): if ui_drv_id.isChecked(): self._led[bot_id].set_colorful() def _read_img(self): img_id = self._ui.show.value() if img_id in [CONST.SHOW.WELCOME, CONST.SHOW.THANKS]: for bot_id, ui_drv_id in {1: self._ui.drv_bot1, 2: self._ui.drv_bot2}.items(): if ui_drv_id.isChecked(): self._led[bot_id].read_img(img_id=img_id, bot_id=bot_id) else: print('\033[1;33m [LIQUID_TYPE_ERR] 无此节目 \033[0m') def _read_video(self): video_id = self._ui.show.value() if video_id in [CONST.SHOW.SEA, CONST.SHOW.SKY]: for bot_id, ui_drv_id in {1: self._ui.drv_bot1, 2: self._ui.drv_bot2}.items(): if ui_drv_id.isChecked(): self._led[bot_id].read_video(video_id=video_id, bot_id=bot_id) else: print('\033[1;33m [LIQUID_TYPE_ERR] 无此节目 \033[0m') def _set_link(self, link: bool): self._led.set_link(link=link)
class MainApp(QMainWindow, main_ui): # 主操作界面 # 定义构造方法 def __init__(self): QMainWindow.__init__(self) self.setupUi(self) self.pick_actor = vtk.vtkActor() self.init_vtk_view() self.handle_events() # 绑定事件 def handle_events(self): self.import_geometry_action.triggered.connect(self.show_geometry) self.point_pick.triggered.connect(self.pick_point) # 初始化vtk视图区域 def init_vtk_view(self): # 在之前创建的view_widget上添加vtk控件 self.vtk_vertical_layout = QVBoxLayout(self.view_widget) self.vtk_widget = QVTKRenderWindowInteractor(self.view_widget) self.vtk_vertical_layout.addWidget(self.vtk_widget) # 1.创建RenderWindow窗口 self.render_window = self.vtk_widget.GetRenderWindow() # 2.创建render self.renderer = vtk.vtkRenderer() self.renderer.SetBackground(1.0, 1.0, 1.0) # 设置页面底部颜色值 self.renderer.SetBackground2(0.1, 0.2, 0.4) # 设置页面顶部颜色值 self.renderer.SetGradientBackground(1) # 开启渐变色背景设置 self.render_window.AddRenderer(self.renderer) self.render_window.Render() # 3.设置交互方式 self.iren = self.render_window.GetInteractor() # 获取交互器 self.style = vtk.vtkInteractorStyleTrackballCamera( ) # 交互器样式的一种,该样式下,用户是通过控制相机对物体作旋转、放大、缩小等操作 # self.style = MyInteractor(self) self.style.SetDefaultRenderer(self.renderer) self.iren.SetInteractorStyle(self.style) # 拾取器 cellPicker = vtk.vtkCellPicker() self.iren.SetPicker(cellPicker) # 4.添加坐标轴(加self,血的教训) axesActor = vtk.vtkAxesActor() self.axes_widget = vtk.vtkOrientationMarkerWidget() self.axes_widget.SetOrientationMarker(axesActor) self.axes_widget.SetInteractor(self.iren) self.axes_widget.EnabledOn() self.axes_widget.InteractiveOff() # 坐标系是否可移动 # 5.添加Actor self.original_actor = vtk.vtkActor() # 加载几何模型 def show_geometry(self): # 使用QSettings记录上次打开路径 qSettings = QSettings() lastPath = qSettings.value("LastFilePath") # 文件选择器 filename, _ = QFileDialog.getOpenFileName(self, '打开文件 - vtk文件', lastPath, '(*.vtk)') # 如果刚才已经打开过模型,则删除上一个 if self.original_actor: self.renderer.RemoveActor(self.original_actor) # 如果上一次选点,则取消上一次选点标记 if self.pick_actor: self.renderer.RemoveActor(self.pick_actor) if filename: # 1.数据源:读取stl文件 self.original_model = vtk.vtkPolyDataReader() self.original_model.SetFileName(filename) self.original_model.Update() self.output_point() # 2.创建mapper,建图 self.original_mapper = vtk.vtkPolyDataMapper() self.original_mapper.SetInputConnection( self.original_model.GetOutputPort()) # 3.设置执行单元:演员 self.original_actor.SetMapper(self.original_mapper) self.original_actor.GetProperty().SetColor(0.5, 0.5, 0.5) # 4.渲染renderer self.renderer.AddActor(self.original_actor) self.renderer.ResetCamera() # 交互器初始化,否则需要点一下才能显示模型 self.iren.Initialize() self.iren.Start() self.OutputBrowser.append('成功导入模型!') def output_point(self): polydata = self.original_model.GetOutput() string = "Number of Cells:" + str(polydata.GetNumberOfCells()) self.OutputBrowser.append(string) string = "Number of Points:" + str(polydata.GetNumberOfPoints()) self.OutputBrowser.append(string) def pick_point(self): self.style.AddObserver("RightButtonPressEvent", self.RightButtonPressEvent) # 右键拾取点 def RightButtonPressEvent(self, obj, event): # 选择当前像素 clickPos = self.render_window.GetInteractor().GetEventPosition() self.OutputBrowser.append("Picking pixel: " + str(clickPos)) picker = self.render_window.GetInteractor().GetPicker() picker.Pick(clickPos[0], clickPos[1], 0, self.renderer) # 选取到模型上一点 if (picker.GetCellId() != -1): self.OutputBrowser.append("Pick position is: " + str(picker.GetPickPosition())) self.OutputBrowser.append("Cell id is:" + str(picker.GetCellId())) self.OutputBrowser.append("Point id is:" + str(picker.GetPointId())) point_position = self.original_model.GetOutput().GetPoint( picker.GetPointId()) # 如果上一次选点,则取消上一次选点标记 if self.pick_actor: self.renderer.RemoveActor(self.pick_actor) # 创建点标识 sphereSource = vtk.vtkSphereSource() sphereSource.SetCenter(point_position) sphereSource.SetRadius(0.2) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(sphereSource.GetOutputPort()) self.pick_actor.SetMapper(mapper) self.pick_actor.GetProperty().SetColor(1.0, 0.0, 0.0) self.renderer.AddActor(self.pick_actor) # Forward events self.style.OnRightButtonDown() return