def vtkRenderWidgetConeExample(): """Like it says, just a simple example """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # create root window root = tkinter.Tk() # create vtkTkRenderWidget pane = vtkTkRenderWidget(root,width=300,height=300) ren = vtkRenderer() pane.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # pack the pane into the tk root pane.pack() # start the tk mainloop root.mainloop()
def create_cone_actor(vertex: Tuple[float, float, float], angle: float, h: float): # TODO maybe it is not good to pass cone object destructed (hard to add new parameters) """ :param angle: angle between z-axis and generaxis """ sign = lambda x: 0 if not x else int(x / abs(x)) coneSource = vtkConeSource() coneSource.SetHeight(h) # coneSource.SetAngle(angle) coneSource.SetResolution(120) # coneSource.SetHeight(vertex[2]) import math coneSource.SetRadius(h * math.tan(math.radians(math.fabs(angle)))) coneSource.SetCenter(vertex[0], vertex[1], (vertex[2] - (h / 2) if angle > 0 else vertex[2] + h / 2)) coneSource.SetDirection(0, 0, 1 * sign(angle)) # update parameters mapper = vtkPolyDataMapper() mapper.SetInputConnection(coneSource.GetOutputPort()) actor = vtkActor() actor.SetMapper(mapper) # create a checkbox for visualization actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetColor(get_color(sett().colors.splane)) return actor
def _silhouette(self, mesh, color=None, line_width=None, alpha=None, decimate=None): mesh = mesh.decimate(decimate) if decimate is not None else mesh silhouette_filter = vtkPolyDataSilhouette() silhouette_filter.SetInputData(mesh) silhouette_filter.SetCamera(self.plotter.renderer.GetActiveCamera()) silhouette_filter.SetEnableFeatureAngle(0) silhouette_mapper = vtkPolyDataMapper() silhouette_mapper.SetInputConnection(silhouette_filter.GetOutputPort()) actor, prop = self.plotter.add_actor(silhouette_mapper, reset_camera=False, name=None, culling=False, pickable=False, render=False) if color is not None: prop.SetColor(*color) if alpha is not None: prop.SetOpacity(alpha) if line_width is not None: prop.SetLineWidth(line_width) _hide_testing_actor(actor) return actor
def QVTKRenderWidgetConeExample(): """A simple example that uses the QVTKRenderWindowInteractor class.""" from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # every QT app needs an app app = QApplication(['QVTKRenderWindowInteractor']) # create the widget widget = QVTKRenderWindowInteractor() widget.Initialize() widget.Start() # if you don't want the 'q' key to exit comment this. widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit()) ren = vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the widget widget.show() # start event processing app.exec_()
def wxVTKRenderWindowConeExample(): """Like it says, just a simple example. """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # every wx app needs an app app = wx.App(False) # create the widget frame = wx.Frame(None, -1, "wxVTKRenderWindow", size=(400,400)) widget = wxVTKRenderWindow(frame, -1) ren = vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the window frame.Show() app.MainLoop()
def slice_obj(self, printer: PrintSetting, printhead: PixelPrinthead, print_param: GenericPrintParameter) -> None: # TODO not taking advantage of pipeline check later why self.actor.ComputeMatrix() full_trs = vtkTransform() full_trs.SetMatrix(self.actor.GetMatrix()) self._coord_converter.SetTransform(full_trs) self._coord_converter.Update() self._voxelizer.set_settings(printer, printhead, print_param) self._voxelizer.Update() surf = vtkMarchingCubes() surf.SetValue(0, 255) surf.AddInputData(self._voxelizer.GetOutputDataObject(0)) surf.Update() polymap = vtkPolyDataMapper() polymap.SetInputData(surf.GetOutput()) actor = vtkActor() actor.SetMapper(polymap) self._init_output_id_key(actor) self.results.ShallowCopy(actor) self.render_res_sig.emit(self.id)
def GetPeelActor(self, p): lut = vtkWindowLevelLookupTable() lut.SetWindow(self.window_width) lut.SetLevel(self.window_level) lut.Build() init = self.window_level - self.window_width / 2 end = self.window_level + self.window_width / 2 # Set mapper auto mapper = vtkPolyDataMapper() mapper.SetInputData(self.peel[p]) mapper.SetScalarRange(init, end) mapper.SetLookupTable(lut) mapper.InterpolateScalarsBeforeMappingOn() # Set actor self.currentPeelActor.SetMapper(mapper) currentPeel = self.TransformPeelPosition(p) self.locator.SetDataSet(currentPeel) self.locator.BuildLocator() self.peel_centers = GetCenters(currentPeel) self.peel_normals = GetNormals(currentPeel) return self.currentPeelActor
def main(): ren = vtkRenderer() for item in glob.iglob(pattern, recursive=True): reader = vtk.vtkPolyDataReader() reader.SetFileName(item) reader.Update() polydata = reader.GetOutput() mapper = vtkPolyDataMapper() mapper.SetInputData(polydata) actor = vtkActor() actor.SetMapper(mapper) ren.AddActor(actor) renWin = vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName('DDD') iren = vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renWin.Render() iren.Start()
def __init__(self, poly_src: vtkPolyDataAlgorithm, parent: Optional['QObject'] = None) -> None: super().__init__(parent=parent) self._poly_src = poly_src self.id = QUuid.createUuid().toString() self.actor = vtkActor() mapper = vtkPolyDataMapper() mapper.SetInputConnection(poly_src.GetOutputPort()) self.actor.SetMapper(mapper) user_transform = vtkTransform() user_transform.Identity() user_transform.PostMultiply() self.actor.SetUserTransform(user_transform) self.actor.ComputeMatrix() transform = vtkTransform() transform.SetMatrix(self.actor.GetMatrix()) self._coord_converter = vtkTransformPolyDataFilter() self._coord_converter.SetTransform(transform) self._coord_converter.AddInputData(poly_src.GetOutput()) self._coord_converter.Update() self._voxelizer = VoxelSlicer() self._voxelizer.SetInputConnection( self._coord_converter.GetOutputPort()) self.results = vtkActor() self._init_input_id_key() self._init_output_id_key(self.results)
def SetInput(self, imagedata): axes = PLANE_DATA[self.orientation][0] # "x", "y" or "z" colour = PLANE_DATA[self.orientation][1] #if self.orientation == SAGITAL: # spacing = min(imagedata.GetSpacing()) # permute = vtk.vtkImagePermute() # permute.SetInput(imagedata) # permute.GetOutput().ReleaseDataFlagOn() # permute.SetOutputSpacing(spacing, spacing, spacing) # imagedata = permute.GetOutput() # Picker for enabling plane motion. # Allows selection of a cell by shooting a ray into graphics window picker = vtkCellPicker() picker.SetTolerance(0.005) picker.PickFromListOn() # 3D widget for reslicing image data. # This 3D widget defines a plane that can be interactively placed in an image volume. widget = vtkImagePlaneWidget() widget.SetInput(imagedata) widget.SetSliceIndex(self.index) widget.SetPicker(picker) widget.SetKeyPressActivationValue(axes) widget.SetInteractor(self.iren) widget.TextureVisibilityOff() widget.DisplayTextOff() widget.RestrictPlaneToVolumeOff() exec("widget.SetPlaneOrientationTo" + axes.upper() + "Axes()") widget.AddObserver("InteractionEvent", self.Update) self.widget = widget prop = widget.GetPlaneProperty() prop.SetColor(colour) # Syncronize coloured outline with texture appropriately source = vtkPlaneSource() source.SetOrigin(widget.GetOrigin()) source.SetPoint1(widget.GetPoint1()) source.SetPoint2(widget.GetPoint2()) source.SetNormal(widget.GetNormal()) self.source = source mapper = vtkPolyDataMapper() mapper.SetInput(source.GetOutput()) actor = vtkActor() actor.SetMapper(mapper) actor.SetTexture(widget.GetTexture()) actor.VisibilityOff() self.actor = actor self.render.AddActor(actor)
def main(): from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # The main window window = gtk.GtkWindow(gtk.WINDOW_TOPLEVEL) window.set_title("A GtkVTKRenderWindow Demo!") window.connect("destroy", gtk.mainquit) window.connect("delete_event", gtk.mainquit) window.set_border_width(10) # A VBox into which widgets are packed. vbox = gtk.GtkVBox(spacing=3) window.add(vbox) vbox.show() # The GtkVTKRenderWindow gvtk = GtkVTKRenderWindowInteractor() #gvtk.SetDesiredUpdateRate(1000) gvtk.set_usize(400, 400) vbox.pack_start(gvtk) gvtk.show() gvtk.Initialize() gvtk.Start() # prevents 'q' from exiting the app. gvtk.AddObserver("ExitEvent", lambda o, e, x=None: x) # The VTK stuff. cone = vtkConeSource() cone.SetResolution(80) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) #coneActor = vtkLODActor() coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(0.5, 0.5, 1.0) ren = vtkRenderer() gvtk.GetRenderWindow().AddRenderer(ren) ren.AddActor(coneActor) # A simple quit button quit = gtk.GtkButton("Quit!") quit.connect("clicked", gtk.mainquit) vbox.pack_start(quit) quit.show() # show the main window and start event processing. window.show() gtk.mainloop()
def wxVTKRenderWindowInteractorConeExample(): """Like it says, just a simple example """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # every wx app needs an app app = wx.App(False) # create the top-level frame, sizer and wxVTKRWI frame = wx.Frame(None, -1, "wxVTKRenderWindowInteractor", size=(400, 400)) widget = wxVTKRenderWindowInteractor(frame, -1) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(widget, 1, wx.EXPAND) frame.SetSizer(sizer) frame.Layout() # It would be more correct (API-wise) to call widget.Initialize() and # widget.Start() here, but Initialize() calls RenderWindow.Render(). # That Render() call will get through before we can setup the # RenderWindow() to render via the wxWidgets-created context; this # causes flashing on some platforms and downright breaks things on # other platforms. Instead, we call widget.Enable(). This means # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE, # that doesn't matter. widget.Enable(1) widget.AddObserver("ExitEvent", lambda o, e, f=frame: f.Close()) ren = vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the window frame.Show() app.MainLoop()
def main(): from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # The main window window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("A GtkVTKRenderWindow Demo!") window.connect("destroy", gtk.mainquit) window.connect("delete_event", gtk.mainquit) window.set_border_width(10) # A VBox into which widgets are packed. vbox = gtk.VBox(spacing=3) window.add(vbox) vbox.show() # The GtkVTKRenderWindow gvtk = GtkGLExtVTKRenderWindowInteractor() #gvtk.SetDesiredUpdateRate(1000) gvtk.set_size_request(400, 400) vbox.pack_start(gvtk) gvtk.show() gvtk.Initialize() gvtk.Start() # prevents 'q' from exiting the app. gvtk.AddObserver("ExitEvent", lambda o,e,x=None: x) # The VTK stuff. cone = vtkConeSource() cone.SetResolution(80) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) #coneActor = vtkLODActor() coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(0.5, 0.5, 1.0) ren = vtkRenderer() gvtk.GetRenderWindow().AddRenderer(ren) ren.AddActor(coneActor) # A simple quit button quit = gtk.Button("Quit!") quit.connect("clicked", gtk.mainquit) vbox.pack_start(quit) quit.show() # show the main window and start event processing. window.show() gtk.mainloop()
def QVTKRenderWidgetConeExample(): """A simple example that uses the QVTKRenderWindowInteractor class.""" from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # every QT app needs an app app = QApplication(['QVTKRenderWindowInteractor']) window = QMainWindow() # create the widget widget = QVTKRenderWindowInteractor(window) window.setCentralWidget(widget) # if you don't want the 'q' key to exit comment this. widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit()) ren = vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the widget window.show() widget.Initialize() widget.Start() # start event processing # Source: https://doc.qt.io/qtforpython/porting_from2.html # 'exec_' is deprecated and will be removed in the future. # Use 'exec' instead. try: app.exec() except AttributeError: app.exec_()
def __init__(self, linuxcncDataSource, model_path): super(SpindleActor, self).__init__() self._datasource = linuxcncDataSource self._tool_table = self._datasource.getToolTable() tool = self._tool_table[0] if self._datasource.isMachineMetric(): self.height = 25.4 * 2.0 else: self.height = 2.0 start_point = [-tool.xoffset, -tool.yoffset, -tool.zoffset] end_point = [0, 0, 0] filename = model_path # filename = os.path.join(os.path.dirname(__file__), "models/laser.stl") source = vtk.vtkSTLReader() source.SetFileName(filename) transform = vtk.vtkTransform() # transform.RotateWXYZ(180, 1, 0, 0) transform_filter = vtk.vtkTransformPolyDataFilter() transform_filter.SetTransform(transform) transform_filter.SetInputConnection(source.GetOutputPort()) transform_filter.Update() colors = vtkNamedColors() # Create a mapper and actor for the arrow mapper = vtkPolyDataMapper() mapper.SetInputConnection(transform_filter.GetOutputPort()) self.SetMapper(mapper) self.GetProperty().SetDiffuse(0.8) self.GetProperty().SetDiffuseColor(colors.GetColor3d('LightSteelBlue')) self.GetProperty().SetSpecular(0.3) self.GetProperty().SetSpecularPower(60.0) # Avoid visible backfaces on Linux with some video cards like intel # From: https://stackoverflow.com/questions/51357630/vtk-rendering-not-working-as-expected-inside-pyqt?rq=1#comment89720589_51360335 self.GetProperty().SetBackfaceCulling(1)
def OnLoadSurfaceDict(self, surface_dict): for key in surface_dict: surface = surface_dict[key] # Map polygonal data (vtkPolyData) to graphics primitives. normals = vtkPolyDataNormals() normals.SetInputData(surface.polydata) normals.SetFeatureAngle(80) normals.AutoOrientNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() # Improve performance stripper = vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) stripper.PassThroughCellIdsOn() stripper.PassThroughPointIdsOn() mapper = vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) mapper.ScalarVisibilityOff() # mapper.ImmediateModeRenderingOn() # improve performance # Represent an object (geometry & properties) in the rendered scene actor = vtkActor() actor.GetProperty().SetBackfaceCulling(1) actor.SetMapper(mapper) # Set actor colour and transparency actor.GetProperty().SetColor(surface.colour[:3]) actor.GetProperty().SetOpacity(1 - surface.transparency) self.actors_dict[surface.index] = actor # Send actor by pubsub to viewer's render Publisher.sendMessage('Load surface actor into viewer', actor=actor) Publisher.sendMessage('Update status text in GUI', label=_("Ready")) # The following lines have to be here, otherwise all volumes disappear Publisher.sendMessage('Update surface info in GUI', surface=surface) if not surface.is_shown: self.ShowActor(key, False)
def main(): from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # The main window window = gtk.Window() window.set_title("A GtkGLExtVTKRenderWindow Demo!") window.connect("destroy", gtk.mainquit) window.connect("delete_event", gtk.mainquit) window.set_border_width(10) vtkgtk = GtkGLExtVTKRenderWindow() vtkgtk.show() vbox = gtk.VBox(spacing=3) vbox.show() vbox.pack_start(vtkgtk) button = gtk.Button('My Button') button.show() vbox.pack_start(button) window.add(vbox) window.set_size_request(400, 400) # The VTK stuff. cone = vtkConeSource() cone.SetResolution(80) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) #coneActor = vtkLODActor() coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(0.5, 0.5, 1.0) ren = vtkRenderer() vtkgtk.GetRenderWindow().AddRenderer(ren) ren.AddActor(coneActor) # show the main window and start event processing. window.show() gtk.mainloop()
def vtkRenderWindowInteractorConeExample(): """Like it says, just a simple example """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # create root window root = tkinter.Tk() # create vtkTkRenderWidget pane = vtkTkRenderWindowInteractor(root, width=300, height=300) pane.Initialize() def quit(obj=root): obj.quit() pane.AddObserver("ExitEvent", lambda o, e, q=quit: q()) ren = vtkRenderer() pane.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # pack the pane into the tk root pane.pack(fill='both', expand=1) pane.Start() # start the tk mainloop root.mainloop()
def createLine(point1: tuple, point2: tuple, color: str = "Black") -> vtkActor: """ :param point1: :param point2: :param color: :return: """ line = vtkLineSource() line.SetPoint1(*point1) line.SetPoint2(*point2) mapper = vtkPolyDataMapper() mapper.SetInputConnection(line.GetOutputPort()) actor = vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(vtkNamedColors().GetColor3d(color)) return actor
def vtkRenderWindowInteractorConeExample(): """Like it says, just a simple example https://gitlab.kitware.com/vtk/vtk/-/blob/master/Wrapping/Python/vtkmodules/tk/vtkTkRenderWindowInteractor.py """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer from vtkmodules.tk.vtkTkRenderWindowInteractor import vtkTkRenderWindowInteractor # create root window root = tkinter.Tk() # create vtkTkRenderWidget pane = vtkTkRenderWindowInteractor(root, width=300, height=300) pane.Initialize() def quit(obj=root): obj.quit() pane.AddObserver("ExitEvent", lambda o,e,q=quit: q()) ren = vtkRenderer() pane.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # pack the pane into the tk root pane.pack(fill='both', expand=1) pane.Start() # start the tk mainloop root.mainloop()
def main(): from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # The main window window = gtk.Window() window.set_title("A GtkGLExtVTKRenderWindow Demo!") window.connect("destroy", gtk.mainquit) window.connect("delete_event", gtk.mainquit) window.set_border_width(10) vtkgtk = GtkGLExtVTKRenderWindow() vtkgtk.show() vbox = gtk.VBox(spacing=3) vbox.show() vbox.pack_start(vtkgtk) button = gtk.Button('My Button') button.show() vbox.pack_start(button) window.add(vbox) window.set_size_request(400, 400) # The VTK stuff. cone = vtkConeSource() cone.SetResolution(80) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) #coneActor = vtkLODActor() coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(0.5, 0.5, 1.0) ren = vtkRenderer() vtkgtk.GetRenderWindow().AddRenderer(ren) ren.AddActor(coneActor) # show the main window and start event processing. window.show() gtk.mainloop()
def __init__(self, linuxcncDataSource): super(ToolOffsetActor, self).__init__() self._datasource = linuxcncDataSource self._tool_table = self._datasource.getToolTable() tool = self._tool_table[0] if self._datasource.isMachineMetric(): self.height = 25.4 * 2.0 else: self.height = 2.0 start_point = [-tool.xoffset, -tool.yoffset, -tool.zoffset] end_point = [0, 0, 0] source = vtkCylinderSource() transform = vtk.vtkTransform() source.SetHeight(tool.zoffset) source.SetCenter(-tool.xoffset, -tool.zoffset / 2, -tool.yoffset) source.SetRadius(tool.diameter / 2) source.SetResolution(64) transform.RotateWXYZ(90, 1, 0, 0) transform_filter = vtk.vtkTransformPolyDataFilter() transform_filter.SetTransform(transform) transform_filter.SetInputConnection(source.GetOutputPort()) transform_filter.Update() colors = vtkNamedColors() # Create a mapper and actor for the arrow mapper = vtkPolyDataMapper() mapper.SetInputConnection(transform_filter.GetOutputPort()) self.SetMapper(mapper) # Avoid visible backfaces on Linux with some video cards like intel # From: https://stackoverflow.com/questions/51357630/vtk-rendering-not-working-as-expected-inside-pyqt?rq=1#comment89720589_51360335 self.GetProperty().SetBackfaceCulling(1)
def Create(self): self.plane_widget = plane_widget = vtkImagePlaneWidget() plane_widget.SetInputData(self.img) plane_widget.SetPlaneOrientationToXAxes() #plane_widget.SetResliceInterpolateToLinear() plane_widget.TextureVisibilityOff() #Set left mouse button to move and rotate plane plane_widget.SetLeftButtonAction(1) #SetColor margin to green margin_property = plane_widget.GetMarginProperty() margin_property.SetColor(0, 0.8, 0) #Disable cross cursor_property = plane_widget.GetCursorProperty() cursor_property.SetOpacity(0) self.plane_source = plane_source = vtkPlaneSource() plane_source.SetOrigin(plane_widget.GetOrigin()) plane_source.SetPoint1(plane_widget.GetPoint1()) plane_source.SetPoint2(plane_widget.GetPoint2()) plane_source.SetNormal(plane_widget.GetNormal()) plane_mapper = self.plane_mapper = vtkPolyDataMapper() plane_mapper.SetInputData(plane_source.GetOutput()) self.plane_actor = plane_actor = vtkActor() plane_actor.SetMapper(plane_mapper) plane_actor.GetProperty().BackfaceCullingOn() plane_actor.GetProperty().SetOpacity(0) plane_widget.AddObserver("InteractionEvent", self.Update) Publisher.sendMessage('AppendActor', actor=self.plane_actor) Publisher.sendMessage('Set Widget Interactor', widget=self.plane_widget) plane_actor.SetVisibility(1) plane_widget.On() self.plane = plane = vtkPlane() plane.SetNormal(self.plane_source.GetNormal()) plane.SetOrigin(self.plane_source.GetOrigin()) self.volume_mapper.AddClippingPlane(plane) #Storage First Position self.origin = plane_widget.GetOrigin() self.p1 = plane_widget.GetPoint1() self.p2 = plane_widget.GetPoint2() self.normal = plane_widget.GetNormal()
def vtkRenderWindowInteractorConeExample(): """Like it says, just a simple example """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # create root window root = tkinter.Tk() # create vtkTkRenderWidget pane = vtkTkRenderWindowInteractor(root, width=300, height=300) pane.Initialize() def quit(obj=root): obj.quit() pane.AddObserver("ExitEvent", lambda o,e,q=quit: q()) ren = vtkRenderer() pane.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # pack the pane into the tk root pane.pack(fill='both', expand=1) pane.Start() # start the tk mainloop root.mainloop()
def GetCurrentPeelActor(self, currentPeel): lut = vtkWindowLevelLookupTable() lut.SetWindow(self.window_width) lut.SetLevel(self.window_level) lut.Build() init = self.window_level - self.window_width / 2 end = self.window_level + self.window_width / 2 # Set mapper auto mapper = vtkPolyDataMapper() mapper.SetInputData(currentPeel) mapper.SetScalarRange(init, end) mapper.SetLookupTable(lut) mapper.InterpolateScalarsBeforeMappingOn() # Set actor self.currentPeelActor.SetMapper(mapper) self.currentPeelActor.GetProperty().SetBackfaceCulling(1) self.currentPeelActor.GetProperty().SetOpacity(0.5) self.currentPeelActor.GetProperty().SetSpecular(0.25) return self.currentPeelActor
def _volume(self, dimensions, origin, spacing, scalars, surface_alpha, resolution, blending, center): # Now we can actually construct the visualization grid = pyvista.UniformGrid() grid.dimensions = dimensions + 1 # inject data on the cells grid.origin = origin grid.spacing = spacing _cell_data(grid)['values'] = scalars # Add contour of enclosed volume (use GetOutput instead of # GetOutputPort below to avoid updating) if surface_alpha > 0 or resolution is not None: grid_alg = vtkCellDataToPointData() grid_alg.SetInputDataObject(grid) grid_alg.SetPassCellData(False) grid_alg.Update() else: grid_alg = None if surface_alpha > 0: grid_surface = vtkMarchingContourFilter() grid_surface.ComputeNormalsOn() grid_surface.ComputeScalarsOff() grid_surface.SetInputData(grid_alg.GetOutput()) grid_surface.SetValue(0, 0.1) grid_surface.Update() grid_mesh = vtkPolyDataMapper() grid_mesh.SetInputData(grid_surface.GetOutput()) else: grid_mesh = None mapper = vtkSmartVolumeMapper() if resolution is None: # native mapper.SetScalarModeToUseCellData() mapper.SetInputDataObject(grid) else: upsampler = vtkImageReslice() upsampler.SetInterpolationModeToLinear() # default anyway upsampler.SetOutputSpacing(*([resolution] * 3)) upsampler.SetInputConnection(grid_alg.GetOutputPort()) mapper.SetInputConnection(upsampler.GetOutputPort()) # Additive, AverageIntensity, and Composite might also be reasonable remap = dict(composite='Composite', mip='MaximumIntensity') getattr(mapper, f'SetBlendModeTo{remap[blending]}')() volume_pos = vtkVolume() volume_pos.SetMapper(mapper) dist = grid.length / (np.mean(grid.dimensions) - 1) volume_pos.GetProperty().SetScalarOpacityUnitDistance(dist) if center is not None and blending == 'mip': # We need to create a minimum intensity projection for the neg half mapper_neg = vtkSmartVolumeMapper() if resolution is None: # native mapper_neg.SetScalarModeToUseCellData() mapper_neg.SetInputDataObject(grid) else: mapper_neg.SetInputConnection(upsampler.GetOutputPort()) mapper_neg.SetBlendModeToMinimumIntensity() volume_neg = vtkVolume() volume_neg.SetMapper(mapper_neg) volume_neg.GetProperty().SetScalarOpacityUnitDistance(dist) else: volume_neg = None return grid, grid_mesh, volume_pos, volume_neg
def ribbon(molecule): """Create an actor for ribbon molecular representation. Parameters ---------- molecule : Molecule The molecule to be rendered. Returns ------- molecule_actor : vtkActor Actor created to render the rubbon representation of the molecule to be visualized. References ---------- Richardson, J.S. The anatomy and taxonomy of protein structure `Advances in Protein Chemistry, 1981, 34, 167-339. <https://doi.org/10.1016/S0065-3233(08)60520-3>`_ """ coords = get_all_atomic_positions(molecule) all_atomic_numbers = get_all_atomic_numbers(molecule) num_total_atoms = molecule.total_num_atoms secondary_structures = np.ones(num_total_atoms) for i in range(num_total_atoms): secondary_structures[i] = ord('c') resi = molecule.residue_seq[i] for j, _ in enumerate(molecule.sheet): sheet = molecule.sheet[j] if molecule.chain[i] != sheet[0] or resi < sheet[1] or \ resi > sheet[3]: continue secondary_structures[i] = ord('s') for j, _ in enumerate(molecule.helix): helix = molecule.helix[j] if molecule.chain[i] != helix[0] or resi < helix[1] or \ resi > helix[3]: continue secondary_structures[i] = ord('h') output = cdmvtk.vtkPolyData() # for atomic numbers atomic_num_arr = numpy_to_vtk(num_array=all_atomic_numbers, deep=True, array_type=ccvtk.VTK_ID_TYPE) # setting the array name to atom_type as vtkProteinRibbonFilter requires # the array to be named atom_type atomic_num_arr.SetName("atom_type") output.GetPointData().AddArray(atomic_num_arr) # for atom names atom_names = ccvtk.vtkStringArray() # setting the array name to atom_types as vtkProteinRibbonFilter requires # the array to be named atom_types atom_names.SetName("atom_types") atom_names.SetNumberOfTuples(num_total_atoms) for i in range(num_total_atoms): atom_names.SetValue(i, molecule.atom_names[i]) output.GetPointData().AddArray(atom_names) # for residue sequences residue_seq = numpy_to_vtk(num_array=molecule.residue_seq, deep=True, array_type=ccvtk.VTK_ID_TYPE) residue_seq.SetName("residue") output.GetPointData().AddArray(residue_seq) # for chain chain = numpy_to_vtk(num_array=molecule.chain, deep=True, array_type=ccvtk.VTK_UNSIGNED_CHAR) chain.SetName("chain") output.GetPointData().AddArray(chain) # for secondary structures s_s = numpy_to_vtk(num_array=secondary_structures, deep=True, array_type=ccvtk.VTK_UNSIGNED_CHAR) s_s.SetName("secondary_structures") output.GetPointData().AddArray(s_s) # for secondary structures begin newarr = np.ones(num_total_atoms) s_sb = numpy_to_vtk(num_array=newarr, deep=True, array_type=ccvtk.VTK_UNSIGNED_CHAR) s_sb.SetName("secondary_structures_begin") output.GetPointData().AddArray(s_sb) # for secondary structures end newarr = np.ones(num_total_atoms) s_se = numpy_to_vtk(num_array=newarr, deep=True, array_type=ccvtk.VTK_UNSIGNED_CHAR) s_se.SetName("secondary_structures_end") output.GetPointData().AddArray(s_se) # for is_hetatm is_hetatm = numpy_to_vtk(num_array=molecule.is_hetatm, deep=True, array_type=ccvtk.VTK_UNSIGNED_CHAR) is_hetatm.SetName("ishetatm") output.GetPointData().AddArray(is_hetatm) # for model model = numpy_to_vtk(num_array=molecule.model, deep=True, array_type=ccvtk.VTK_UNSIGNED_INT) model.SetName("model") output.GetPointData().AddArray(model) table = PeriodicTable() # for colors and radii of hetero-atoms radii = np.ones((num_total_atoms, 3)) rgb = np.ones((num_total_atoms, 3)) for i in range(num_total_atoms): radii[i] = np.repeat(table.atomic_radius(all_atomic_numbers[i], 'VDW'), 3) rgb[i] = table.atom_color(all_atomic_numbers[i]) Rgb = numpy_to_vtk(num_array=rgb, deep=True, array_type=ccvtk.VTK_UNSIGNED_CHAR) Rgb.SetName("rgb_colors") output.GetPointData().SetScalars(Rgb) Radii = numpy_to_vtk(num_array=radii, deep=True, array_type=ccvtk.VTK_FLOAT) Radii.SetName("radius") output.GetPointData().SetVectors(Radii) # setting the coordinates points = numpy_to_vtk_points(coords) output.SetPoints(points) ribbonFilter = dcvtk.vtkProteinRibbonFilter() ribbonFilter.SetInputData(output) ribbonFilter.SetCoilWidth(0.2) ribbonFilter.SetDrawSmallMoleculesAsSpheres(0) mapper = rcvtk.vtkPolyDataMapper() mapper.SetInputConnection(ribbonFilter.GetOutputPort()) molecule_actor = rcvtk.vtkActor() molecule_actor.SetMapper(mapper) return molecule_actor
def wxVTKRenderWindowInteractorConeExample(): """Like it says, just a simple example https://discourse.vtk.org/t/interactor-start-blocking-execution/1095/2 https://gitlab.kitware.com/vtk/vtk/-/blob/master/Wrapping/Python/vtkmodules/wx/wxVTKRenderWindowInteractor.py ipython --gui=wx #gui wx run learn_vtk.py """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer from vtkmodules.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor import wx colors = vtk.vtkNamedColors() # every wx app needs an app app = wx.App(False) # create the top-level frame, sizer and wxVTKRWI frame = wx.Frame(None, -1, "wxVTKRenderWindowInteractor", size=(400,400)) widget = wxVTKRenderWindowInteractor(frame, -1) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(widget, 1, wx.EXPAND) frame.SetSizer(sizer) frame.Layout() # It would be more correct (API-wise) to call widget.Initialize() and # widget.Start() here, but Initialize() calls RenderWindow.Render(). # That Render() call will get through before we can setup the # RenderWindow() to render via the wxWidgets-created context; this # causes flashing on some platforms and downright breaks things on # other platforms. Instead, we call widget.Enable(). This means # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE, # that doesn't matter. widget.Enable(1) widget.AddObserver("ExitEvent", lambda o,e,f=frame: f.Close()) ren = vtkRenderer() renwin = widget.GetRenderWindow() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the window frame.Show() # It works! # wx.CallLater(1000*5, lambda : ren.SetBackground(colors.GetColor3d('Blue'))) # wx.CallLater(1000*8, lambda : renwin.Render()) # colors = vtk.vtkNamedColors() # wx.CallAfter(lambda : ren.SetBackground(colors.GetColor3d('Blue'))) # wx.CallAfter(lambda : renwin.Render()) def fn(): ren.SetBackground(colors.GetColor3d('Blue')) renwin.Render() wx.CallLater(1000*3, fn) #app.MainLoop() # comment out to interact in ipython return app, ren, renwin
def CreateSurfaceFromPolydata(self, polydata, overwrite=False, index=None, name=None, colour=None, transparency=None, volume=None, area=None, scalar=False): if self.convert_to_inv: # convert between invesalius and world space with shift in the Y coordinate matrix_shape = sl.Slice().matrix.shape spacing = sl.Slice().spacing img_shift = spacing[1] * (matrix_shape[1] - 1) affine = sl.Slice().affine.copy() affine[1, -1] -= img_shift affine_vtk = vtk_utils.numpy_to_vtkMatrix4x4(affine) polydata_transform = vtkTransform() polydata_transform.PostMultiply() polydata_transform.Concatenate(affine_vtk) transformFilter = vtkTransformPolyDataFilter() transformFilter.SetTransform(polydata_transform) transformFilter.SetInputData(polydata) transformFilter.Update() polydata = transformFilter.GetOutput() self.convert_to_inv = False normals = vtkPolyDataNormals() normals.SetInputData(polydata) normals.SetFeatureAngle(80) normals.AutoOrientNormalsOn() normals.Update() mapper = vtkPolyDataMapper() mapper.SetInputData(normals.GetOutput()) if scalar: mapper.ScalarVisibilityOn() else: mapper.ScalarVisibilityOff() # mapper.ImmediateModeRenderingOn() # improve performance actor = vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetBackfaceCulling(1) if overwrite: if index is None: index = self.last_surface_index surface = Surface(index=index) else: surface = Surface() if not colour: surface.colour = random.choice(const.SURFACE_COLOUR) else: surface.colour = colour surface.polydata = polydata if transparency: surface.transparency = transparency if name: surface.name = name # Append surface into Project.surface_dict proj = prj.Project() if overwrite: proj.ChangeSurface(surface) else: index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index # Set actor colour and transparency actor.GetProperty().SetColor(surface.colour) actor.GetProperty().SetOpacity(1 - surface.transparency) if overwrite and self.actors_dict.keys(): try: old_actor = self.actors_dict[index] Publisher.sendMessage('Remove surface actor from viewer', actor=old_actor) except KeyError: pass self.actors_dict[surface.index] = actor session = ses.Session() session.ChangeProject() # The following lines have to be here, otherwise all volumes disappear if not volume or not area: triangle_filter = vtkTriangleFilter() triangle_filter.SetInputData(polydata) triangle_filter.Update() measured_polydata = vtkMassProperties() measured_polydata.SetInputConnection( triangle_filter.GetOutputPort()) measured_polydata.Update() volume = measured_polydata.GetVolume() area = measured_polydata.GetSurfaceArea() surface.volume = volume surface.area = area print(">>>>", surface.volume) else: surface.volume = volume surface.area = area self.last_surface_index = surface.index Publisher.sendMessage('Load surface actor into viewer', actor=actor) Publisher.sendMessage('Update surface info in GUI', surface=surface) return surface.index
def _show_surface(self, surface_filename, surface_measures, overwrite, surface_name, colour, dialog): print(surface_filename, surface_measures) reader = vtkXMLPolyDataReader() reader.SetFileName(surface_filename) reader.Update() polydata = reader.GetOutput() # Map polygonal data (vtkPolyData) to graphics primitives. mapper = vtkPolyDataMapper() mapper.SetInputData(polydata) mapper.ScalarVisibilityOff() # mapper.ReleaseDataFlagOn() # mapper.ImmediateModeRenderingOn() # improve performance # Represent an object (geometry & properties) in the rendered scene actor = vtkActor() actor.GetProperty().SetBackfaceCulling(1) actor.SetMapper(mapper) del mapper #Create Surface instance if overwrite: surface = Surface(index=self.last_surface_index) else: surface = Surface(name=surface_name) surface.colour = colour surface.polydata = polydata surface.volume = surface_measures['volume'] surface.area = surface_measures['area'] del polydata # Set actor colour and transparency actor.GetProperty().SetColor(colour) actor.GetProperty().SetOpacity(1 - surface.transparency) prop = actor.GetProperty() interpolation = int(ses.Session().surface_interpolation) prop.SetInterpolation(interpolation) proj = prj.Project() if overwrite: proj.ChangeSurface(surface) else: index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index session = ses.Session() session.ChangeProject() Publisher.sendMessage('Load surface actor into viewer', actor=actor) # Send actor by pubsub to viewer's render if overwrite and self.actors_dict.keys(): old_actor = self.actors_dict[self.last_surface_index] Publisher.sendMessage('Remove surface actor from viewer', actor=old_actor) # Save actor for future management tasks self.actors_dict[surface.index] = actor Publisher.sendMessage('Update surface info in GUI', surface=surface) Publisher.sendMessage('End busy cursor') dialog.running = False
def main(): colors = vtkNamedColors() operation = "intersection" reader = vtkUnstructuredGridReader() reader.SetFileName(ATRIA_VTK_FILE) geo_filter = vtkGeometryFilter() geo_filter.SetInputConnection(reader.GetOutputPort()) geo_filter.Update() poly1 = geo_filter.GetOutput() tri1 = vtkTriangleFilter() tri1.SetInputData(poly1) clean1 = vtkCleanPolyData() clean1.SetInputConnection(tri1.GetOutputPort()) clean1.Update() input1 = clean1.GetOutput() sphereSource1 = vtkSphereSource() sphereSource1.SetCenter(20.43808060942321, 18.333007878470767, 34.5753857481471) sphereSource1.SetRadius(0.5) # sphereSource1.SetPhiResolution(21) # sphereSource1.SetThetaResolution(21) sphereSource1.Update() input2 = sphereSource1.GetOutput() input1Mapper = vtkPolyDataMapper() input1Mapper.SetInputData(input1) input1Mapper.ScalarVisibilityOff() input1Actor = vtkActor() input1Actor.SetMapper(input1Mapper) input1Actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Tomato")) input1Actor.GetProperty().SetSpecular(0.6) input1Actor.GetProperty().SetSpecularPower(20) # input1Actor.SetPosition(input1.GetBounds()[1] - input1.GetBounds()[0], 0, 0) input2Mapper = vtkPolyDataMapper() input2Mapper.SetInputData(input2) input2Mapper.ScalarVisibilityOff() input2Actor = vtkActor() input2Actor.SetMapper(input2Mapper) input2Actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Mint")) input2Actor.GetProperty().SetSpecular(0.6) input2Actor.GetProperty().SetSpecularPower(20) # input2Actor.SetPosition(-(input1.GetBounds()[1] - input1.GetBounds()[0]), 0, 0) booleanOperation = vtkBooleanOperationPolyDataFilter() if operation.lower() == "union": booleanOperation.SetOperationToUnion() elif operation.lower() == "intersection": booleanOperation.SetOperationToIntersection() elif operation.lower() == "difference": booleanOperation.SetOperationToDifference() else: print("Unknown operation:", operation) return booleanOperation.SetInputData(0, input1) booleanOperation.SetInputData(1, input2) booleanOperationMapper = vtkPolyDataMapper() booleanOperationMapper.SetInputConnection(booleanOperation.GetOutputPort()) booleanOperationMapper.ScalarVisibilityOff() booleanOperationActor = vtkActor() booleanOperationActor.SetMapper(booleanOperationMapper) booleanOperationActor.GetProperty().SetDiffuseColor( colors.GetColor3d("Banana")) booleanOperationActor.GetProperty().SetSpecular(0.6) booleanOperationActor.GetProperty().SetSpecularPower(20) renderer = vtkRenderer() renderer.AddViewProp(input1Actor) renderer.AddViewProp(input2Actor) renderer.AddViewProp(booleanOperationActor) renderer.SetBackground(colors.GetColor3d("Silver")) renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetSize(640, 480) renderWindow.SetWindowName("BooleanOperationPolyDataFilter") viewUp = [0.0, 0.0, 1.0] position = [0.0, -1.0, 0.0] PositionCamera(renderer, viewUp, position) renderer.GetActiveCamera().Dolly(1.4) renderer.ResetCameraClippingRange() renWinInteractor = vtkRenderWindowInteractor() renWinInteractor.SetRenderWindow(renderWindow) renderWindow.Render() renWinInteractor.Start()