def make_render_window_populate_views(self): self.renderWindow.SetSize(self.rendererSize * self.gridDimensions, self.rendererSize * self.gridDimensions) self.cameras = [vtk.vtkCamera()] * 4 for row in range(self.gridDimensions): for col in range(self.gridDimensions): idx = row * self.gridDimensions + col self.viewports[:] = [] self.renderers[idx].ResetCamera() self.viewports.append(float(col) * self.rendererSize / (self.gridDimensions * self.rendererSize)) self.viewports.append(float(self.gridDimensions - (row+1)) * self.rendererSize / (self.gridDimensions * self.rendererSize)) self.viewports.append(float(col+1) * self.rendererSize / (self.gridDimensions * self.rendererSize)) self.viewports.append(float(self.gridDimensions - row) * self.rendererSize / (self.gridDimensions * self.rendererSize)) if idx > (4 - 1): continue self.renderers[idx].SetViewport(self.viewports) ### make camera views / view ports camera = vtk.vtkCamera() camera.SetPosition(self.camera_positions[idx]) camera.SetRoll(self.camera_rolls[idx]) camera.SetFocalPoint(self.camera_focal_point[idx]) camera.Azimuth(self.camera_azimuth[idx]) camera.Elevation(self.camera_elevation[idx]) self.renderers[idx].SetActiveCamera(camera) ### add actors to model for actor in self.actors: self.renderers[idx].AddActor(actor) self.renderers[idx].AddViewProp(self.legend) self.renderers[idx].AddViewProp(self.timer_text) self.renderers[idx].SetBackground(0.3, 0.3, 0.3)
def __init__(self): # No cmd line time_index, use on screen rendering self.onScreen = len(sys.argv) == 1 self.SetBackground( 0, 0, 0) self.renWin = vtk.vtkRenderWindow() self.renWin.AddRenderer( self ) if self.onScreen: self.renWin.FullScreenOn() self.iren = vtk.vtkRenderWindowInteractor() self.iren.SetRenderWindow( self.renWin ) self.iren.AddObserver("KeyPressEvent", self.Keypress_ShiftTime) else: self.renWin.OffScreenRenderingOn() self.renWin.SetSize( 1280, 720 ) self.axesActor = vtk.vtkCubeAxesActor(); self.axesActor.SetFlyModeToStaticTriad() #actorAxes->SetCamera(camOrtho); #double b[6] = {2,16,2,16,3,8}; #actorAxes->SetBounds(b); self.axesCamera = vtk.vtkCamera() self.axesCamera.SetPosition( 7, 7, 7) self.axesCamera.SetFocalPoint( 0, 0, 0) self.axesActor.SetCamera( self.axesCamera ) self.AddActor( self.axesActor )
def _makeImagePlane(imageData) : ''' Takes a vtkImageData object and returns a plane textured with that image and a camera for the background renderer http://www.vtk.org/Wiki/VTK/Examples/Cxx/Images/BackgroundImage was the basis for this function ''' imageActor = vtk.vtkImageActor() if vtk.VTK_MAJOR_VERSION <= 5 : imageActor.SetInput(imageData) else : imageActor.SetInputData(imageData) origin = imageData.GetOrigin() spacing = imageData.GetSpacing() extent = imageData.GetExtent() camera = vtk.vtkCamera() camera.ParallelProjectionOn() xc = origin[0] + 0.5*(extent[0] + extent[1])*spacing[0] yc = origin[1] + 0.5*(extent[2] + extent[3])*spacing[1] yd = (extent[3] - extent[2] + 1)*spacing[1] d = camera.GetDistance() camera.SetParallelScale(0.5*yd) camera.SetFocalPoint(xc,yc,0.0) camera.SetPosition(xc,yc,d) return camera, imageActor
def create_render_window(actors, callbacks, **kwargs): """ Creates VTK render window with an interactor. :param actors: list of VTK actors :type actors: list, tuple :param callbacks: callback functions for registering custom events :type callbacks: dict """ # Get keyword arguments figure_size = kwargs.get('figure_size', (800, 600)) camera_position = kwargs.get('camera_position', (0, 0, 100)) # Find camera focal point center_points = [] for actor in actors: center_points.append(actor.GetCenter()) camera_focal_point = linalg.vector_mean(*center_points) # Create camera camera = vtk.vtkCamera() camera.SetPosition(*camera_position) camera.SetFocalPoint(*camera_focal_point) # Create renderer renderer = vtk.vtkRenderer() renderer.SetActiveCamera(camera) renderer.SetBackground(1.0, 1.0, 1.0) # Add actors to the scene for actor in actors: renderer.AddActor(actor) # Render window render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetSize(*figure_size) # Render window interactor window_interactor = vtk.vtkRenderWindowInteractor() window_interactor.SetRenderWindow(render_window) # Add event observers for cb in callbacks: window_interactor.AddObserver(cb, callbacks[cb][0], callbacks[cb][1]) # cb name, cb function ref, cb priority # Render actors render_window.Render() # Set window name after render() is called render_window.SetWindowName("geomdl") # Use trackball camera interactor_style = vtk.vtkInteractorStyleTrackballCamera() window_interactor.SetInteractorStyle(interactor_style) # Start interactor window_interactor.Start() # Return window interactor instance return window_interactor
def testChangeFiles(self): """ Test that new files load when selected and save camera state. """ self._widget.FilePlugin.onSetFilenames(self._filenames) # Setup a camera camera = vtk.vtkCamera() camera.SetViewUp(-0.7786, 0.2277, 0.5847) camera.SetPosition(9.2960, -0.4218, 12.6685) camera.SetFocalPoint(0.0000, 0.0000, 0.1250) self._window.onCameraChanged(camera) # The current view self.assertEqual(camera.GetViewUp(), self._window._result.getVTKRenderer().GetActiveCamera().GetViewUp()) self._window.onResultOptionsChanged({'variable':'diffused'}) self._window.onWindowRequiresUpdate() self.assertImage('testChangeFiles0.png') # Switch files self._widget.FilePlugin.AvailableFiles.setCurrentIndex(1) self._window.onResultOptionsChanged({'variable':'vel_'}) self._window.onWindowRequiresUpdate() self.assertImage('testChangeFiles1.png') self.assertNotEqual(camera.GetViewUp(), self._window._result.getVTKRenderer().GetActiveCamera().GetViewUp()) # Switch back to initial (using same file name as before) self._widget.FilePlugin.AvailableFiles.setCurrentIndex(0) self.assertEqual(camera.GetViewUp(), self._window._result.getVTKRenderer().GetActiveCamera().GetViewUp()) self._window.onResultOptionsChanged({'variable':'diffused'}) self._window.onWindowRequiresUpdate() self.assertImage('testChangeFiles0.png')
def Render(self): self.Viewport1 = [0.0, 0.0, 0.5, 0.5] self.Viewport2 = [0.5, 0.0, 1.0, 0.5] self.Viewport3 = [0.0, 0.5, 0.5, 1.0] self.Viewport4 = [0.5, 0.5, 1.0, 1.0] self.Renderer1 = vtk.vtkRenderer() self.Renderer2 = vtk.vtkRenderer() self.Renderer3 = vtk.vtkRenderer() self.Renderer4 = vtk.vtkRenderer() self.renderWindow.AddRenderer(self.Renderer1) self.Renderer1.SetViewport(self.Viewport1) self.Renderer1.SetBackground(0.6, 0.5, 0.3) self.renderWindow.AddRenderer(self.Renderer2) self.Renderer2.SetViewport(self.Viewport2) self.Renderer2.SetBackground(0.5, 0.5, 0.4) self.renderWindow.AddRenderer(self.Renderer3) self.Renderer3.SetViewport(self.Viewport3) self.Renderer3.SetBackground(0.4, 0.5, 0.5) self.renderWindow.AddRenderer(self.Renderer4) self.Renderer4.SetViewport(self.Viewport4) self.Renderer4.SetBackground(0.0, 0.5, 0.6) self.Renderer1.AddActor(self.inputActor1) self.Renderer2.AddActor(self.inputActor2) self.Renderer3.AddActor(self.inputActor3) self.Renderer4.AddActor(self.inputActor4) self.camera = vtk.vtkCamera() self.Renderer1.SetActiveCamera(self.camera) self.Renderer2.SetActiveCamera(self.camera) self.Renderer3.SetActiveCamera(self.camera) self.Renderer4.SetActiveCamera(self.camera) self.Renderer1.ResetCamera() self.renderWindow.Render() self.interactor.Start()
def testCameraLink(self): """ Test the gold toggle is working. """ self.assertTrue(self._widget.GoldDiffPlugin.LinkToggle.isEnabled()) self._widget.GoldDiffPlugin.DiffToggle.setChecked(QtCore.Qt.Checked) self._widget.GoldDiffPlugin.DiffToggle.clicked.emit(True) self._window.onResultOptionsChanged({'variable':'diffused'}) self._window.onWindowRequiresUpdate() camera = vtk.vtkCamera() camera.SetViewUp(-0.7786, 0.2277, 0.5847) camera.SetPosition(9.2960, -0.4218, 12.6685) camera.SetFocalPoint(0.0000, 0.0000, 0.1250) self._window.onCameraChanged(camera) self._window.cameraChanged.emit(self._window._result.getVTKRenderer().GetActiveCamera()) self.assertImage('testCameraLink.png', window=self._widget.GoldDiffPlugin.DiffVTKWindow) # Disconnect link, move the main window, the diff shouldn't move self._widget.GoldDiffPlugin.LinkToggle.setChecked(QtCore.Qt.Unchecked) self._widget.GoldDiffPlugin.LinkToggle.clicked.emit(False) camera.SetViewUp(0.7786, -0.2277, 0.5847) camera.SetPosition(9.2960, 0.4218, 12.6685) camera.SetFocalPoint(0.0000, 0.0000, 0.1250) self._window.onCameraChanged(camera) self._window.cameraChanged.emit(self._window._result.getVTKRenderer().GetActiveCamera()) self.assertImage('testCameraLink.png', window=self._widget.GoldDiffPlugin.DiffVTKWindow)
def __init__(self): self.outputs=[] self.paint=rgbPainter() self.scalingFactor=1.0 self.showAxes=True self.showScalarBar=True self.showCaption=True self.showXYPlane=True self.showYZPlane=True self.showZXPlane=True self.nbSize=80 self.sampleSpacing=8.0 self.camera = vtk.vtkCamera() self.ren = vtk.vtkRenderer(); self.renWin = vtk.vtkRenderWindow(); self.renWin.AddRenderer(self.ren); self.renWin.SetWindowName("DESICOS-viewer v0.1 ") self.iren = vtk.vtkRenderWindowInteractor(); self.iren.SetRenderWindow(self.renWin); style1 = vtk.vtkInteractorStyleTrackballCamera() self.iren.SetInteractorStyle(style1) self.ren.SetBackground(1, 1, 1); self.renWin.SetSize(800, 600);
def draw(self): # Update location and movement self.update() # create a rendering window and renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetSize(1200, 900) renWin.AddRenderer(ren) # Create camera camera = vtk.vtkCamera() #camera.SetPosition(0.5,10.0,0.0); #camera.Roll(-90) #ren.SetActiveCamera(camera) # create a renderwindowinteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add actors ren.AddActor(self.modelActor) ren.AddActor(self.axesActor) # enable user interface interactor iren.Initialize() renWin.Render() style = vtk.vtkInteractorStyleMultiTouchCamera() iren.SetInteractorStyle(style) iren.Start()
def testCloneClose(self): """ Test clone button works. """ self._widget.cornerWidget().clone.emit() self._widget.currentWidget().VariablePlugin.VariableList.setCurrentIndex(2) self._widget.currentWidget().VariablePlugin.VariableList.currentIndexChanged.emit(2) self.assertEqual(self._widget.count(), 2) self.assertEqual(self._widget.tabText(self._widget.currentIndex()), 'Results (2)') self.assertTrue(self._widget.cornerWidget().CloseButton.isEnabled()) if sys.platform == 'darwin': self.assertImage('testInitial.png') # Change camera on cloned tab camera = vtk.vtkCamera() camera.SetViewUp(-0.7786, 0.2277, 0.5847) camera.SetPosition(9.2960, -0.4218, 12.6685) camera.SetFocalPoint(0.0000, 0.0000, 0.1250) self._widget.currentWidget().VTKWindowPlugin.onCameraChanged(camera) if sys.platform == 'darwin': self.assertImage('testClone.png') # Switch to first tab self._widget.setCurrentIndex(0) self.assertEqual(self._widget.tabText(self._widget.currentIndex()), 'Results') if sys.platform == 'darwin': self.assertImage('testInitial.png') # Close the first tab self._widget.cornerWidget().close.emit() self.assertEqual(self._widget.count(), 1) self.assertEqual(self._widget.tabText(self._widget.currentIndex()), 'Results (2)') self.assertFalse(self._widget.cornerWidget().CloseButton.isEnabled())
def main(): fan = ColorFan() # The usual (almost boilerplate for examples) rendering stuff. camera = vtk.vtkCamera() camera.SetPosition(1,1,1) camera.SetFocalPoint(0,0,0) renderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renderer.AddActor( fan.getActor() ) renderer.SetActiveCamera(camera) renderer.ResetCamera() renderer.SetBackground(1,1,1) renWin.SetSize(300,300) # interact with data renWin.Render() iren.Start()
def RenderImageData(self, ID, imgReader): # check if this is the first loaded image set if self.CISID == -1: self.imageLayer = {} self.CISID = ID self.imageLayer[self.CISID] = IBCRenderer(self.renderer, self.iren.Render) self.imageLayer[self.CISID].SetImageSet(ID) locator = self.imageLayer[self.CISID].Render(imgReader) self.initPicker() self.picker.AddLocator(locator) self.initBoxWidgetInteraction(imgReader.VolumeReader.GetOutput()) if self.firstRender: self.iren.AddObserver("MouseMoveEvent", self.MoveCursor) self.iren.AddObserver("LeftButtonPressEvent", self.LeftClick) self.iren.AddObserver("RightButtonPressEvent", self.RightClick) # It is convenient to create an initial view of the data. The FocalPoint # and Position form a vector direction. Later on (ResetCamera() method) # this vector is used to position the camera to look at the data in # this direction. self.viewCam = vtk.vtkCamera() self.viewCam.SetViewUp(0, 0, -1) self.viewCam.SetPosition(0, 1.1, 2) self.viewCam.SetFocalPoint(0, -0.25, 0) self.viewCam.ComputeViewPlaneNormal() # This camera should generally stay stationary, # and only be used for taking screenshots self.picCam = vtk.vtkCamera() self.picCam.SetViewUp(0, 0, -1) self.picCam.SetPosition(0, 1.1, 2) self.picCam.SetFocalPoint(0, -0.25, 0) self.picCam.ComputeViewPlaneNormal() # Actors are added to the renderer. An initial camera view is created. # The Dolly() method moves the camera towards the FocalPoint, # thereby enlarging the image. self.renderer.SetActiveCamera(self.viewCam) self.renderer.ResetCamera() self.viewCam.Dolly(1.0) self.renderer.ResetCameraClippingRange() self.iren.Render() self.firstRender = False
def visualize(): A = initPoints(particleA) B = initPoints(particleB) C = initPoints(particleC) displayDict = {} # Set up the renderer and redering window renderer = vtk.vtkRenderer() renwin = vtk.vtkRenderWindow() renwin.SetSize(1600, 1400) renwin.StereoCapableWindowOn() renwin.StereoRenderOn() renwin.SetStereoTypeToCrystalEyes() renwin.AddRenderer(renderer) ptsComp = vtk.vtkPoints() posComp = vnp.numpy_to_vtk(np.array([[0, 0, 0]], order='C'), deep=True) ptsComp.SetData(posComp) polyDataComp = vtk.vtkPolyData() polyDataComp.SetPoints(ptsComp) sourceComp = vtk.vtkCylinderSource() sourceComp.SetResolution(20) sourceComp.SetRadius(compartment['radius'] + particleScale) sourceComp.SetHeight(compartment['length'] + 2 * particleScale) sourceComp.SetCenter(0, -compartment['length']/2, 0) glyphComp = vtk.vtkGlyph3D() glyphComp.SetSource(sourceComp.GetOutput()) glyphComp.SetInput(polyDataComp) glyphComp.ScalingOff() # glyphComp.SetScaleModeToDefault() # glyphComp.SetScaleFactor(particleScale) mapperComp = vtk.vtkPolyDataMapper() mapperComp.SetInput(glyphComp.GetOutput()) mapperComp.ImmediateModeRenderingOn() actorComp = vtk.vtkActor() actorComp.SetMapper(mapperComp) actorComp.GetProperty().SetOpacity(0.2) actorComp.GetProperty().SetColor(1, 1, 1) actorComp.SetOrientation(0, 90, 90) renderer.AddActor(actorComp) renderer.AddActor(A['actor']) renderer.AddActor(B['actor']) renderer.AddActor(C['actor']) print 'Create camera' camera = vtk.vtkCamera() camera.SetPosition(300e-6, 200.0e-6, -300.0e-6) camera.SetFocalPoint(0, 0, 0) camera.ComputeViewPlaneNormal() renderer.SetActiveCamera(camera) renderer.ResetCamera() interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) callback = TimerCallback(A, B, C) interactor.Initialize() interactor.AddObserver('TimerEvent', callback.execute) timerId = interactor.CreateRepeatingTimer(1) print 'Here' # renwin.FullScreenOn() interactor.Start()
def __set_pure_state__(self, state): """ Update the item """ TrackItem.TrackItem.__set_pure_state__(self, state) self.point = state.point self.cam = vtk.vtkCamera() GUI.Urmas.UrmasPersist.setVTKState(self.cam, state.cam) self.parent.setSplinePoint(self.itemnum, self.point)
def create_camera(position=(0, 0, 0), focal_point=(1, 0, 0), view_up=(0, 0, 1), zoom=1): camera = vtk.vtkCamera() camera.SetPosition(*position) camera.SetFocalPoint(*focal_point) camera.SetViewUp(*view_up) camera.Zoom(zoom) return camera
def __init__(self): # ODE initialization self.world = ode.World() self.world.setGravity(GRAVITY) self.world.setERP(ERP) self.world.setCFM(CFM) self.space = ode.Space() self.floor = ode.GeomPlane(self.space, (0.0,1.0,0.0), 0.0) self.jointGroup = ode.JointGroup() self.time = 0.0 # VTK initialization self.renderer = vtk.vtkRenderer() self.renderer.SetBackground(102.0/255.0,204/255.0,1.0) self.window = vtk.vtkRenderWindow() self.window.SetSize(WINDOW_WIDTH,WINDOW_HEIGHT) self.window.AddRenderer(self.renderer) self.interactor = vtk.vtkRenderWindowInteractor() self.interactor.SetRenderWindow(self.window) self.axes = vtk.vtkAxesActor() self.axes.SetAxisLabels(0) transform = vtk.vtkTransform() transform.Scale(0.1,0.1,0.1) self.axes.SetUserTransform(transform) self.renderer.AddActor(self.axes) # Create ground plane visualization self.floorVisual = vtk.vtkPlaneSource() self.floorVisual.SetNormal((0.0,1.0,0.0)) self.floorVisual.SetResolution(10,10) self.floorReader = vtk.vtkJPEGReader() self.floorReader.SetFileName(FLOOR_IMAGE) self.floorTexture = vtk.vtkTexture() transform = vtk.vtkTransform() transform.Scale(50.0,50.0,50.0) self.floorTexture.SetTransform(transform) self.floorTexture.SetInput(self.floorReader.GetOutput()) self.floorMap = vtk.vtkTextureMapToPlane() self.floorMap.SetInput(self.floorVisual.GetOutput()) self.floorMapper = vtk.vtkPolyDataMapper() self.floorMapper.SetInput(self.floorMap.GetOutput()) self.floorActor = vtk.vtkActor() transform = vtk.vtkTransform() transform.Scale(100.0,100.0,100.0) self.floorActor.SetUserTransform(transform) self.floorActor.SetMapper(self.floorMapper) self.floorActor.SetTexture(self.floorTexture) self.renderer.AddActor(self.floorActor) # VTK camera setup self.camera = vtk.vtkCamera() self.renderer.SetActiveCamera(self.camera) self.cameraFocus = [0.0, 0.0, 0.0] self.cameraPos = [4.0, 2.5, 1.5] self.cameraOffset = [0.0,1.0,3.0] self.cameraRoll = 0.0 # Keep track of the simulated bodies and robots self.bodies = [] self.robots = [] self.controllers = []
def __init__(self, body_fixed=True): """ body_fixed: if true Body part is automatically placed at origin """ self.body_fixed = body_fixed # vtk objects for rendering self.vtkrenderer = vtk.vtkRenderer() self.viewpoint_count = len(self.camera_pos) self.vtkcamera = [] # one camera for each viewpoint for pos, up in zip(self.camera_pos, self.camera_up): camera = vtk.vtkCamera() camera.SetPosition(pos) camera.SetFocalPoint(0, 0, 0) camera.SetViewUp(up) self.vtkcamera.append(camera) self.vtkviewcamera = vtk.vtkCamera(); self.vtkviewcamera.SetPosition(self.view_camera_pos); self.vtkviewcamera.SetFocalPoint(0, 0, 0); self.vtkviewcamera.SetViewUp(self.camera_up[0]) self.vtkrender_window = vtk.vtkRenderWindow() self.vtkrender_window.AddRenderer(self.vtkrenderer) self.vtkrender_window.SetSize(self.render_size) self.vtkrender_window_interactor = vtk.vtkRenderWindowInteractor() self.vtkrender_window_interactor.SetRenderWindow(self.vtkrender_window) # vtk objects for reading, and rendering object parts self.vtkreader = {} self.vtkpolydata = {} self.vtkmapper = {} # read each part from its stl file for part in self.parts: self.vtkreader[part] = vtk.vtkSTLReader() self.vtkreader[part].SetFileName(self.models_folder + part + '.stl') self.vtkpolydata[part] = self.vtkreader[part].GetOutput() self.vtkmapper[part] = vtk.vtkPolyDataMapper() self.vtkmapper[part].SetInput(self.vtkpolydata[part]) if self.body_fixed: # actor for body part (every object has part named body at origin) self.vtkbodyactor = vtk.vtkActor() self.vtkbodyactor.SetMapper(self.vtkmapper['Body']) self.vtkbodyactor.SetPosition(0, 0, 0)
def _cameraFromMatrix(camMatrix, imageDims, windowDims) : ''' Takes a camera matrix derived from OpenCV returns a camera for registration http://stackoverflow.com/questions/25539898/how-to-apply-the-camera-pose-transformation-computed-using-epnp-to-the-vtk-camer was a great help Input: camMatrix (np.ndarray) = 4x4 camera intrinsic matrix imageDims ((float, float)) = width and height of image to register imageDims ((float, float)) = width and height of render window Output: camera (vtk.vtkCamera) = camera to use for registration ''' # Initialize camera camera = vtk.vtkCamera() # Set view angle focalLengthY = camMatrix[1,1] if( windowDims[1] != imageDims[1] ): factor = float(windowDims[1])/float(imageDims[1]) focalLengthY = camMatrix[1,1] * factor viewAngle = np.arctan((windowDims[1]/2.0)/focalLengthY)*360/np.pi camera.SetViewAngle(viewAngle) #Set window center py = 0 height = 0 if imageDims[0] != windowDims[0] or imageDims[1] != windowDims[1] : factor = float(windowDims[1])/float(imageDims[1]) px = factor * camMatrix[0,2] width = windowDims[0] expectedWindowSize = np.round(factor * float(imageDims[0])) if( expectedWindowSize != windowDims[0] ): diffX = (windowDims[0] - expectedWindowSize) / 2 px = px + diffX py = factor * camMatrix[1,2] height = windowDims[1] else : px = camMatrix[0,2] width = imageDims[0] py = camMatrix[1,2] height = imageDims[1] cx = width - px cy = py windowCenter = [0,0] windowCenter[0] = cx / ( ( width-1)/2 ) - 1 windowCenter[1] = cy / ( ( height-1)/2 ) - 1 camera.SetWindowCenter(windowCenter[0],windowCenter[1]) # Set camera to look forward from center camera.SetPosition(0,0,0) camera.SetFocalPoint(0,0,1) return camera
def __create_camera(self): # Create a camera camera = vtk.vtkCamera() camera.SetFocalPoint(numpy.array(self.settings.camera_focal_point) * self.settings.scaling) camera.SetPosition(numpy.array(self.settings.camera_base_position) * self.settings.scaling) camera.Azimuth(self.settings.camera_azimuth) camera.Elevation(self.settings.camera_elevation) camera.SetViewAngle(self.settings.camera_view_angle) return camera
def build_panel(self): self._iren = MyRenderWindowInteractor(self, wx.ID_ANY, size=self.GetSize()) self._iren.SetPosition((0,0)) # define interaction style self._iren.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # change interaction style self._iren.Enable(1) # create renderer self._renderer = vtk.vtkRenderer() self._iren.GetRenderWindow().AddRenderer(self._renderer) # cam stuff self.camera=vtk.vtkCamera() # create camera self._renderer.SetActiveCamera(self.camera) # associate camera to renderer self.camera.SetFocalPoint(0, 0, 0) self.camera.SetPosition(0, 0, 20) self.__pickerObserverId = None self.picker = vtk.vtkCellPicker() self.picker.SetTolerance(0.005) self._iren.AddObserver("TimerEvent", self.on_timer) self._iren.RemoveObservers("CharEvent") self._iren.AddObserver("CharEvent", self.on_keyboard_input) self._iren.AddObserver("LeftButtonPressEvent", self.emulate_focus) pub.subscribe(self.check_switch_consistancy, ('Switch')) self._iren.Bind(wx.EVT_CONTEXT_MENU, self.on_show_popup_menu) self._mgr.AddPane(self._iren, aui.AuiPaneInfo().Dock().Center().CaptionVisible(False).CloseButton(False)) self._mgr.Update() self._first = True self._timerCounter = 0 self._timerInterval = 5 self._animationLoop = False self._trajectoryLoaded = False self._currentFrame = 0 self._maxLaps = 100 self.display_bbox = False self.bbox = None self._surface = None self._iso = None # Atoms picked from mouse or selection box. self.__pickedAtoms = set() self.SetFocusIgnoringChildren()
def setZAxisView(self): """ set z axis view """ cam = vtk.vtkCamera() cam.ParallelProjectionOff() cam.SetViewUp(0, 1, 0) cam.SetPosition(0, 0, self.distance) cam.SetFocalPoint(0, 0, -self.center[2]) self.renderer.SetActiveCamera(cam) self.renderer.ResetCamera() self.renderer.ResetCameraClippingRange() self.redraw()
def visualize(meshFname = None, dumpFname = None, nFrames = 100): # Create a rendering window and renderer transform = vtk.vtkTransform() transform.Scale(10.0, 10.0, 10.0) axes = vtk.vtkAxesActor() axes.SetUserTransform(transform) transform.Translate(2.0, -1.0, 0.0) axes.SetUserTransform(transform) renderer = vtk.vtkRenderer() renderer.AddActor(axes) camera = vtk.vtkCamera() camera.SetFocalPoint(0, 0, 0); renderer.SetActiveCamera(camera); renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) # Create a RenderWindowInteractor to permit manipulating the camera iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) scale = 0.1 if dumpFname is not None: with open(dumFname) as fp: lines = (line for line in fp if not line.strip()[:3].isalpha()) sphereData = np.array(lines) Natoms = len(sphereData) - nFrames for i in range(nFrames): for data in sphereData[Natoms * nFrames: Natoms * (nFrames+1)]: plotSpheres(ren, data[1] * scale, data[2] * scale, data[3] * scale, 0.001) if meshFname is not None: polydata = loadStl(meshFname) renderer.AddActor(polyDataToActor(polydata)) renderer.SetBackground(0.1, 0.1, 0.1) style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) renderer.ResetCamera() iren.Initialize() renWin.Render() iren.Start()
def testPython(self): """ Test generic python script. """ camera = vtk.vtkCamera() camera.SetViewUp(-0.7786, 0.2277, 0.5847) camera.SetPosition(9.2960, -0.4218, 12.6685) camera.SetFocalPoint(0.0000, 0.0000, 0.1250) self._window.onCameraChanged(camera) imagename = '{}_{}'.format(self.__class__.__name__, 'basic.png') self.python(imagename)
def __init__(self): """ Initializes VTK objects for rendering. """ # vtk objects for rendering self.vtkrenderer = vtk.vtkRenderer() self.vtkcamera = vtk.vtkCamera() self.vtkcamera.SetPosition(self.camera_pos) self.vtkcamera.SetFocalPoint(0, 0, 0) self.vtkcamera.SetViewUp(self.camera_up) # lighting self.light1 = vtk.vtkLight() self.light1.SetIntensity(.4) self.light1.SetPosition(10, -10, 10) self.light1.SetDiffuseColor(1, 1, 1) self.light2 = vtk.vtkLight() self.light2.SetIntensity(.4) self.light2.SetPosition(-10, -10, 10) self.light2.SetDiffuseColor(1, 1, 1) self.light3 = vtk.vtkLight() self.light3.SetIntensity(.4) self.light3.SetPosition(10, -10, -10) self.light3.SetDiffuseColor(1, 1, 1) self.light4 = vtk.vtkLight() self.light4.SetIntensity(.4) self.light4.SetPosition(-10, -10, -10) self.light4.SetDiffuseColor(1, 1, 1) self.vtkrenderer.AddLight(self.light1) self.vtkrenderer.AddLight(self.light2) self.vtkrenderer.AddLight(self.light3) self.vtkrenderer.AddLight(self.light4) self.vtkrenderer.SetBackground(0.1, 0.1, 0.1) # Background color self.vtkrender_window = vtk.vtkRenderWindow() self.vtkrender_window.AddRenderer(self.vtkrenderer) self.vtkrender_window.SetSize(self.render_size) self.vtkrender_window_interactor = vtk.vtkRenderWindowInteractor() self.vtkrender_window_interactor.SetRenderWindow(self.vtkrender_window) # vtk objects for reading, and rendering object parts self.part_source = vtk.vtkCubeSource() self.part_output = self.part_source.GetOutput() self.part_mapper = vtk.vtkPolyDataMapper() self.part_mapper.SetInput(self.part_output) # exporters self.vtkvrml_exporter = vtk.vtkVRMLExporter() self.vtkobj_exporter = vtk.vtkOBJExporter() self.stl_writer = vtk.vtkSTLWriter()
def testPythonContour(self): """ Test python script with contours. """ camera = vtk.vtkCamera() camera.SetViewUp(-0.7786, 0.2277, 0.5847) camera.SetPosition(9.2960, -0.4218, 12.6685) camera.SetFocalPoint(0.0000, 0.0000, 0.1250) self._window.onCameraChanged(camera) self._widget.ContourPlugin.ContourToggle.setChecked(True) self._widget.ContourPlugin.ContourToggle.clicked.emit(True) imagename = '{}_{}'.format(self.__class__.__name__, 'contour.png') self.python(imagename)
def testPythonScale(self): """ Test python script with scale. """ camera = vtk.vtkCamera() camera.SetViewUp(-0.7786, 0.2277, 0.5847) camera.SetPosition(9.2960, -0.4218, 12.6685) camera.SetFocalPoint(0.0000, 0.0000, 0.1250) self._window.onCameraChanged(camera) self._widget.MeshPlugin.ScaleY.setValue(1.5) self._widget.MeshPlugin.ScaleY.editingFinished.emit() imagename = '{}_{}'.format(self.__class__.__name__, 'scale.png') self.python(imagename)
def getThumbnail(self): """ Get the thumbnail image """ self.image = self.parent.splineEditor.getAsImage() vx, vy, vz = self.image.GetDimensions() img = lib.ImageOperations.vtkImageDataToWxImage(self.image) f = (self.height - self.labelheight) / float(img.GetHeight()) img = img.Mirror(0) self.thumbnailbmp = img.Scale(vx * f, self.height - self.labelheight).ConvertToBitmap() cam = self.parent.splineEditor.getCamera() self.cam = vtk.vtkCamera() for i in ["Position", "FocalPoint", "ViewUp", "ViewAngle", "ParallelScale", "ClippingRange"]: eval("self.cam.Set%s(cam.Get%s())" % (i, i))
def testCamera(self): """ Test that the camera can be modified. """ camera = vtk.vtkCamera() camera.SetViewUp(-0.7786, 0.2277, 0.5847) camera.SetPosition(9.2960, -0.4218, 12.6685) camera.SetFocalPoint(0.0000, 0.0000, 0.1250) self._window.onFileChanged(self._filename) self._window.onCameraChanged(camera) self._window.onResultOptionsChanged({'variable':'diffused'}) self._window.onWindowRequiresUpdate() self.assertEqual(camera.GetViewUp(), self._window._result.getVTKRenderer().GetActiveCamera().GetViewUp()) self.assertImage('testCamera.png')
def setDefaultView(self): """ set default view """ cam = vtk.vtkCamera() cam.ParallelProjectionOff() cam.SetViewUp(0, 0, 1) cam.SetPosition(self.position) cam.SetFocalPoint(self.center) cam.Azimuth(self.rotateZ) cam.Elevation(self.rotateX) self.renderer.SetActiveCamera(cam) self.renderer.ResetCamera() cam.Zoom(self.zoomFactor) self.renderer.ResetCameraClippingRange() self.redraw()
def display(self, animate=True, movie=False, filename=None): print 'TraubDataVis.display::Start: animate: %d, movie: %d, filename: %s' % (animate, movie, filename) self.camera = vtk.vtkCamera() #self.renderer.GetActiveCamera() self.camera.SetPosition(0.0, 500.0, -1200.0) self.camera.SetFocalPoint(0, 0, -1200) self.camera.ComputeViewPlaneNormal() self.renderer.SetActiveCamera(self.camera) self.renderer.ResetCamera() if not animate: self.interactor = vtk.vtkRenderWindowInteractor() self.interactor.SetRenderWindow(self.renwin) self.interactor.Initialize() self.interactor.Start() else: # self.renwin.SetOffScreenRendering(True) # self.win2image = vtk.vtkWindowToImageFilter() # self.win2image.SetInput(self.renwin) if movie: self.moviewriter = vtk.vtkFFMPEGWriter() self.moviewriter.SetQuality(2) self.moviewriter.SetRate(10) self.moviewriter.SetInputConnection(self.win2image.GetOutputPort()) self.moviewriter.SetFileName(filename) self.moviewriter.Start() else: pass # self.imwriter = vtk.vtkPNGWriter() # self.imwriter.SetInputConnection(self.win2image.GetOutputPort()) time = 0.0 for ii in range(self.datahandler.num_time): time += self.datahandler.plotdt print 'Time:', time for cellclass in self.datahandler.cellclass: vm = self.datahandler.get_vm(cellclass, ii) if (vm is None) or len(vm) == 0: # print 'Error:', cellclass, vm continue self.positionSource[cellclass].GetPointData().SetScalars(vtknp.numpy_to_vtk(vm)) self.renwin.Render() # self.win2image.Modified() if movie: self.moviewriter.Write() else: pass # self.imwriter.SetFileName('frame_%05d.png' % (ii)) # self.imwriter.Write() if movie: self.moviewriter.End() print 'TraubDataVis.display::End'
mapperBone.SetInputConnection(o.GetOutputPort()) mapperBone.SetScalarRange( o.GetOutput().GetPointData().GetScalars().GetRange()[0], o.GetOutput().GetPointData().GetScalars().GetRange()[1]) actor = vtk.vtkActor() actor.SetMapper(mapperBone) return actor read = vtk.vtkSLCReader() read.SetFileName("vw_knee.slc") read.Update() cam = vtk.vtkCamera() cam.SetFocalPoint(0, 0, 0) cam.SetPosition(0, 0, 100) cam.SetViewUp(0, 0, 0) cam.Roll(180) cam.Elevation(90) cam.OrthogonalizeViewUp() renWin = vtk.vtkRenderWindow() renWin.SetSize(600, 600) bone = CreateBone(read) skin = CreateSkin(read) actorOutliner = CreateActor(CreateOutliner(read)) # REN 1
def main(): colors = vtk.vtkNamedColors() textureFile, motorFile = get_program_parameters() # Create the Renderer, RenderWindow and RenderWindowInteractor. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Create the cutting planes. planes = vtk.vtkPlanes() points = vtk.vtkPoints() norms = vtk.vtkFloatArray() norms.SetNumberOfComponents(3) points.InsertPoint(0, 0.0, 0.0, 0.0) norms.InsertTuple3(0, 0.0, 0.0, 1.0) points.InsertPoint(1, 0.0, 0.0, 0.0) norms.InsertTuple3(1, -1.0, 0.0, 0.0) planes.SetPoints(points) planes.SetNormals(norms) # Get the texture. texReader = vtk.vtkStructuredPointsReader() texReader.SetFileName(textureFile) texture = vtk.vtkTexture() texture.SetInputConnection(texReader.GetOutputPort()) texture.InterpolateOff() texture.RepeatOff() # Set up the pipelines for the parts of the motor. # We will use lists of pipeline objects. numberOfParts = 5 byu = list() normals = list() tex = list() byuMapper = list() byuActor = list() partColours = [ 'cold_grey', 'peacock', 'raw_sienna', 'banana', 'peach_puff' ] # Use this to control which parts to display. displayParts = [True] * numberOfParts # If displayParts[2] = False then an image like that in the VTK tests is produced. # Build the pipelines. for i in range(0, numberOfParts): byu.append(vtk.vtkBYUReader()) byu[i].SetGeometryFileName(motorFile) byu[i].SetPartNumber(i + 1) normals.append(vtk.vtkPolyDataNormals()) normals[i].SetInputConnection(byu[i].GetOutputPort()) tex.append(vtk.vtkImplicitTextureCoords()) tex[i].SetInputConnection(normals[i].GetOutputPort()) tex[i].SetRFunction(planes) # tex[i].FlipTextureOn() byuMapper.append(vtk.vtkDataSetMapper()) byuMapper[i].SetInputConnection(tex[i].GetOutputPort()) byuActor.append(vtk.vtkActor()) byuActor[i].SetMapper(byuMapper[i]) byuActor[i].SetTexture(texture) byuActor[i].GetProperty().SetColor(colors.GetColor3d(partColours[i])) ren.AddActor(byuActor[i]) if displayParts[i]: byuActor[i].VisibilityOn() else: byuActor[i].VisibilityOff() ren.SetBackground(colors.GetColor3d('AliceBlue')) renWin.SetSize(512, 512) camera = vtk.vtkCamera() camera.SetFocalPoint(0.0286334, 0.0362996, 0.0379685) camera.SetPosition(1.37067, 1.08629, -1.30349) camera.SetViewAngle(17.673) camera.SetClippingRange(1, 10) camera.SetViewUp(-0.376306, -0.5085, -0.774482) ren.SetActiveCamera(camera) # Render the image. iren.Initialize() iren.Start()
def main(): # setup the dataset filepath filename = "yC31/pv_insitu_300x300x300_07678.vti" #filename = "yC31/pv_insitu_300x300x300_08415.vti" # the name of data array which is used in this example daryName = "v03" #'v03' 'prs' 'tev' # for accessomg build-in color access colors = vtk.vtkNamedColors() # Create the renderer, the render window, and the interactor. # The renderer draws into the render window. # The interactor enables mouse and keyboard-based interaction # with the data within the render windows. aRenderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(aRenderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Set a background color for the renderer # and set the size of the render window. aRenderer.SetBackground(colors.GetColor3d("Silver")) renWin.SetSize(600, 600) # data reader reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) reader.Update() # specify the data array in the file to process reader.GetOutput().GetPointData().SetActiveAttribute(daryName, 0) # convert the data array to numpy array and get the min and maximum value dary = VN.vtk_to_numpy( reader.GetOutput().GetPointData().GetScalars(daryName)) dary = dary[dary != 0] dMax = np.amax(dary) dMin = np.amin(dary) dRange = dMax - dMin dMean = np.mean(dary) dMedian = np.median(dary) print("Data array max: ", dMax) print("Data array min: ", dMin) print("Data array range: ", dRange) print("Data array mean: ", dMean) print("Data array median: ", dMedian) ############ setup color map ######### # Now create a loopup table that consists of the full hue circle # (from HSV). hueLut = vtk.vtkLookupTable() hueLut.SetTableRange(dMin, dMax) hueLut.Build() # An outline provides context around the data. outlineData = vtk.vtkOutlineFilter() outlineData.SetInputConnection(reader.GetOutputPort()) outlineData.Update() mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outlineData.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(mapOutline) outline.GetProperty().SetColor(colors.GetColor3d("Black")) #################### create isosurface v03 = mean ###################################### # isosurface iso = vtk.vtkContourFilter() iso.SetInputConnection(reader.GetOutputPort()) iso.Update() iso.SetValue(0, dMean) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(iso.GetOutputPort()) normals.SetFeatureAngle(45) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(normals.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetColor(colors.GetColor3d("bisque")) isoActor.GetProperty().SetOpacity(0.3) #isoActor.GetProperty().SetColor(0, 0, 1); ################################################################################################# aCamera = vtk.vtkCamera() aCamera.SetViewUp(0, 0, 1) aCamera.SetPosition(0, -1, 0) aCamera.SetFocalPoint(0, 0, 0) aCamera.ComputeViewPlaneNormal() aCamera.Azimuth(45.0) aCamera.Elevation(45.0) ######################## create a text ##################### # create a text actor txt = vtk.vtkTextActor() txt_str = "isosurface value (mean) = " + str(dMean)[:5] txt.SetInput(txt_str) txtprop = txt.GetTextProperty() txtprop.SetFontFamilyToArial() txtprop.SetFontSize(24) txtprop.SetColor(0, 0, 0) txt.SetDisplayPosition(100, 550) ############################################################ txt2 = vtk.vtkTextActor() txt_str2 = "timestep = " + filename[27:32] txt2.SetInput(txt_str2) txtprop2 = txt2.GetTextProperty() txtprop2.SetFontFamilyToArial() txtprop2.SetFontSize(24) txtprop2.SetColor(0, 0, 0) txt2.SetDisplayPosition(100, 500) ########################################################## # Actors are added to the renderer. aRenderer.AddActor(outline) aRenderer.AddActor(isoActor) aRenderer.AddActor(txt) aRenderer.AddActor(txt2) # An initial camera view is created. The Dolly() method moves # the camera towards the FocalPoint, thereby enlarging the image. aRenderer.SetActiveCamera(aCamera) # Calling Render() directly on a vtkRenderer is strictly forbidden. # Only calling Render() on the vtkRenderWindow is a valid call. renWin.Render() aRenderer.ResetCamera() aCamera.Dolly(-2.0) # Note that when camera movement occurs (as it does in the Dolly() method), # the clipping planes often need adjusting. # Clipping planes consist of two planes: # near and far along the view direction. # The near plane clips out objects in front of the plane; # the far plane clips out objects behind the plane. # This way only what is drawn between the planes is actually rendered. aRenderer.ResetCameraClippingRange() # Interact with the data. renWin.Render() iren.Initialize() iren.Start()
def getCameraCopy(self): camera = vtk.vtkCamera() camera.DeepCopy(self.view.camera()) return camera
def main(): SHOW_AXES = True SHOW_SCENE_AXES = True SHOW_COIL_AXES = True SHOW_SKIN = True SHOW_BRAIN = True SHOW_COIL = True SHOW_MARKERS = True TRANSF_COIL = True SHOW_PLANE = False SELECT_LANDMARKS = 'scalp' # 'all', 'mri' 'scalp' SAVE_ID = True AFFINE_IMG = True NO_SCALE = True SCREENSHOT = False SHOW_OTHER = False reorder = [0, 2, 1] flipx = [True, False, False] # reorder = [0, 1, 2] # flipx = [False, False, False] # default folder and subject # subj = 's03' # for Bert image use the translation in the base_affine (fall-back) subj_list = [ 'VictorSouza', 'JaakkoNieminen', 'AinoTervo', 'JuusoKorhonen', 'BaranAydogan', 'AR', 'Bert' ] subj = 0 id_extra = False # 8, 9, 10, 12, False # data_dir = os.environ['OneDriveConsumer'] + '\\data\\nexstim_coord\\' data_dir = os.environ.get( 'OneDrive') + r'\vh\eventos\sf 2019\mri_science_factory\{}'.format( subj_list[subj]) # data_dir = os.environ.get('OneDrive') + r'\data\motor_mapping\analysis\20200419\lmm_notebook_clean' # data_subj = data_dir + subj + '\\' # simnibs_dir = data_dir + r'\simnibs\\m2m_ppM1_%s_nc\\' % subj # if id_extra: # nav_dir = data_dir + 'nav_coordinates\\ppM1_%s_%d\\' % (subj, id_extra) # else: # nav_dir = data_dir + 'nav_coordinates\\ppM1_%s\\' % subj # filenames # coil_file = data_dir + 'magstim_fig8_coil.stl' # coil_file = os.environ['OneDriveConsumer'] + '\\data\\nexstim_coord\\magstim_fig8_coil.stl' # if id_extra: # coord_file = nav_dir + 'ppM1_eximia_%s_%d.txt' % (subj, id_extra) # else: # coord_file = nav_dir + 'ppM1_eximia_%s.txt' % subj # img_file = data_subj + subj + '.nii' img_file = data_dir + r'\{}.nii'.format(subj_list[subj]) brain_file = data_dir + r'\gm.stl' skin_file = data_dir + r'\gm_sn.stl' if subj == 3: other_file = data_dir + r'\gm.ply' elif subj == 4: other_file = data_dir + r'\tracks.vtp' elif subj == 6: other_file = data_dir + r'\gm.ply' else: other_file = data_dir + r'\gm.stl' # if id_extra: # output_file = nav_dir + 'transf_mat_%s_%d' % (subj, id_extra) # else: # output_file = nav_dir + 'transf_mat_%s' % subj # coords = lc.load_nexstim(coord_file) # red, green, blue, maroon (dark red), # olive (shitty green), teal (petrol blue), yellow, orange col = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], [1., .0, 1.], [.5, .5, 0.], [0., .5, .5], [1., 1., 0.], [1., .4, .0]] # extract image header shape and affine transformation from original nifti file imagedata = nb.squeeze_image(nb.load(img_file)) imagedata = nb.as_closest_canonical(imagedata) imagedata.update_header() pix_dim = imagedata.header.get_zooms() img_shape = imagedata.header.get_data_shape() print("Pixel size: \n") print(pix_dim) print("\nImage shape: \n") print(img_shape) print("\nSform: \n") print(imagedata.get_qform(coded=True)) print("\nQform: \n") print(imagedata.get_sform(coded=True)) print("\nFall-back: \n") print(imagedata.header.get_base_affine()) scale_back, shear_back, angs_back, trans_back, persp_back = tf.decompose_matrix( imagedata.header.get_base_affine()) if AFFINE_IMG: affine = imagedata.affine # affine = imagedata.header.get_base_affine() if NO_SCALE: scale, shear, angs, trans, persp = tf.decompose_matrix(affine) affine = tf.compose_matrix(scale=None, shear=shear, angles=angs, translate=trans, perspective=persp) else: affine = np.identity(4) # affine_I = np.identity(4) # create a camera, render window and renderer camera = vtk.vtkCamera() camera.SetPosition(0, 1000, 0) camera.SetFocalPoint(0, 0, 0) camera.SetViewUp(0, 0, 1) camera.ComputeViewPlaneNormal() camera.Azimuth(90.0) camera.Elevation(10.0) ren = vtk.vtkRenderer() ren.SetActiveCamera(camera) ren.ResetCamera() camera.Dolly(1.5) ren_win = vtk.vtkRenderWindow() ren_win.AddRenderer(ren) ren_win.SetSize(800, 800) # create a renderwindowinteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(ren_win) # if SELECT_LANDMARKS == 'mri': # # MRI landmarks # coord_mri = [['Nose/Nasion'], ['Left ear'], ['Right ear'], ['Coil Loc'], ['EF max']] # pts_ref = [1, 2, 3, 7, 10] # elif SELECT_LANDMARKS == 'all': # # all coords # coord_mri = [['Nose/Nasion'], ['Left ear'], ['Right ear'], ['Nose/Nasion'], ['Left ear'], ['Right ear'], # ['Coil Loc'], ['EF max']] # pts_ref = [1, 2, 3, 5, 4, 6, 7, 10] # elif SELECT_LANDMARKS == 'scalp': # # scalp landmarks # coord_mri = [['Nose/Nasion'], ['Left ear'], ['Right ear'], ['Coil Loc'], ['EF max']] # hdr_mri = ['Nose/Nasion', 'Left ear', 'Right ear', 'Coil Loc', 'EF max'] # pts_ref = [5, 4, 6, 7, 10] # # coords_np = np.zeros([len(pts_ref), 3]) # for n, pts_id in enumerate(pts_ref): # # to keep in the MRI space use the identity as the affine # # coord_aux = n2m.coord_change(coords[pts_id][1:], img_shape, affine_I, flipx, reorder) # # affine_trans = affine_I.copy() # # affine_trans = affine.copy() # # affine_trans[:3, -1] = affine[:3, -1] # coord_aux = n2m.coord_change(coords[pts_id][1:], img_shape, affine, flipx, reorder) # coords_np[n, :] = coord_aux # [coord_mri[n].append(s) for s in coord_aux] # if SHOW_MARKERS: # marker_actor = add_marker(coord_aux, ren, col[n]) # # print('\nOriginal coordinates from Nexstim: \n') # [print(s) for s in coords] # print('\nTransformed coordinates to MRI space: \n') # [print(s) for s in coord_mri] # # # coil location, normal vector and direction vector # coil_loc = coord_mri[-2][1:] # coil_norm = coords[8][1:] # coil_dir = coords[9][1:] # # # creating the coil coordinate system by adding a point in the direction of each given coil vector # # the additional vector is just the cross product from coil direction and coil normal vectors # # origin of the coordinate system is the coil location given by Nexstim # # the vec_length is to allow line creation with visible length in VTK scene # vec_length = 75 # p1 = coords[7][1:] # p2 = [x + vec_length * y for x, y in zip(p1, coil_norm)] # p2_norm = n2m.coord_change(p2, img_shape, affine, flipx, reorder) # # p2 = [x + vec_length * y for x, y in zip(p1, coil_dir)] # p2_dir = n2m.coord_change(p2, img_shape, affine, flipx, reorder) # # coil_face = np.cross(coil_norm, coil_dir) # p2 = [x - vec_length * y for x, y in zip(p1, coil_face.tolist())] # p2_face = n2m.coord_change(p2, img_shape, affine, flipx, reorder) # Coil face unit vector (X) # u1 = np.asarray(p2_face) - np.asarray(coil_loc) # u1_n = u1 / np.linalg.norm(u1) # # Coil direction unit vector (Y) # u2 = np.asarray(p2_dir) - np.asarray(coil_loc) # u2_n = u2 / np.linalg.norm(u2) # # Coil normal unit vector (Z) # u3 = np.asarray(p2_norm) - np.asarray(coil_loc) # u3_n = u3 / np.linalg.norm(u3) # # transf_matrix = np.identity(4) # if TRANSF_COIL: # transf_matrix[:3, 0] = u1_n # transf_matrix[:3, 1] = u2_n # transf_matrix[:3, 2] = u3_n # transf_matrix[:3, 3] = coil_loc[:] # the absolute value of the determinant indicates the scaling factor # the sign of the determinant indicates how it affects the orientation: if positive maintain the # original orientation and if negative inverts all the orientations (flip the object inside-out)' # the negative determinant is what makes objects in VTK scene to become black # print('Transformation matrix: \n', transf_matrix, '\n') # print('Determinant: ', np.linalg.det(transf_matrix)) # if SAVE_ID: # coord_dict = {'m_affine': transf_matrix, 'coords_labels': hdr_mri, 'coords': coords_np} # io.savemat(output_file + '.mat', coord_dict) # hdr_names = ';'.join(['m' + str(i) + str(j) for i in range(1, 5) for j in range(1, 5)]) # np.savetxt(output_file + '.txt', transf_matrix.reshape([1, 16]), delimiter=';', header=hdr_names) if SHOW_BRAIN: # brain_actor = load_stl(brain_file, ren, colour=[0., 1., 1.], opacity=0.7, user_matrix=np.linalg.inv(affine)) affine_orig = np.identity(4) # affine_orig = affine.copy() # affine_orig[0, 3] = affine_orig[0, 3] + pix_dim[0]*img_shape[0] # affine_orig[1, 3] = affine_orig[1, 3] + pix_dim[1]*img_shape[1] # affine_orig[0, 3] = affine_orig[0, 3] + pix_dim[0]*img_shape[0] # affine_orig[0, 3] = affine_orig[0, 3] - 5 # this partially works for DTI Baran # modified close to correct [-75.99139404 123.88291931 - 148.19839478] # fall-back [87.50042766 - 127.5 - 127.5] # affine_orig[0, 3] = -trans_back[0] # affine_orig[1, 3] = -trans_back[1] # this works for the bert image # affine_orig[0, 3] = -127 # affine_orig[1, 3] = 127 # affine_orig[2, 3] = -127 # affine_orig[:3, :3] = affine[:3, :3] # affine_orig[1, 3] = -affine_orig[1, 3]+27.5 # victorsouza # affine_orig[1, 3] = -affine_orig[1, 3]+97.5 # affine_orig[1, 3] = -affine_orig[1, 3] print('Affine original: \n', affine) scale, shear, angs, trans, persp = tf.decompose_matrix(affine) print('Angles: \n', np.rad2deg(angs)) print('Translation: \n', trans) print('Affine modified: \n', affine_orig) scale, shear, angs, trans, persp = tf.decompose_matrix(affine_orig) print('Angles: \n', np.rad2deg(angs)) print('Translation: \n', trans) # colour=[0., 1., 1.], brain_actor, brain_mesh = load_stl(brain_file, ren, replace=True, colour=[1., 0., 0.], opacity=.3, user_matrix=affine_orig) # print('Actor origin: \n', brain_actor.GetPosition()) if SHOW_SKIN: # skin_actor = load_stl(skin_file, ren, opacity=0.5, user_matrix=np.linalg.inv(affine)) # affine[0, 3] = affine[0, 3] + pix_dim[0] * img_shape[0] # this is working # affine[0, 3] = affine[0, 3] + 8. affine[1, 3] = affine[1, 3] + pix_dim[1] * img_shape[1] # affine[2, 3] = affine[2, 3] + pix_dim[2] * img_shape[2] affine_inv = np.linalg.inv(affine) # affine_inv[:3, 3] = -affine[:3, 3] # affine_inv[2, 3] = -affine_inv[2, 3] skin_actor, skin_mesh = load_stl(skin_file, ren, colour="SkinColor", opacity=1., user_matrix=affine_inv) # skin_actor, skin_mesh = load_stl(skin_file, ren, colour="SkinColor", opacity=1.) skino_actor, skino_mesh = load_stl(skin_file, ren, colour=[1., 0., 0.], opacity=1.) if SHOW_OTHER: # skin_actor = load_stl(skin_file, ren, opacity=0.5, user_matrix=np.linalg.inv(affine)) affine[1, 3] = affine[1, 3] + pix_dim[1] * img_shape[1] affine_inv = np.linalg.inv(affine) # affine_inv[:3, 3] = -affine[:3, 3] affine_inv[1, 3] = affine_inv[1, 3] # other_actor, other_mesh = load_stl(other_file, ren, opacity=1., user_matrix=affine_inv) # other_actor, other_mesh = load_stl(other_file, ren, opacity=1.) # if SHOW_COIL: # # reposition STL object prior to transformation matrix # # [translation_x, translation_y, translation_z, rotation_x, rotation_y, rotation_z] # # old translation when using Y as normal vector # # repos = [0., -6., 0., 0., -90., 90.] # # Translate coil loc coordinate to coil bottom # # repos = [0., 0., 5.5, 0., 0., 180.] # repos = [0., 0., 0., 0., 0., 180.] # act_coil = load_stl(coil_file, ren, replace=repos, user_matrix=transf_matrix, opacity=.3) # # if SHOW_PLANE: # act_plane = add_plane(ren, user_matrix=transf_matrix) # Add axes to scene origin if SHOW_AXES: add_line(ren, [0, 0, 0], [150, 0, 0], color=[1.0, 0.0, 0.0]) add_line(ren, [0, 0, 0], [0, 150, 0], color=[0.0, 1.0, 0.0]) add_line(ren, [0, 0, 0], [0, 0, 150], color=[0.0, 0.0, 1.0]) # Add axes to object origin # if SHOW_COIL_AXES: # add_line(ren, coil_loc, p2_norm, color=[.0, .0, 1.0]) # add_line(ren, coil_loc, p2_dir, color=[.0, 1.0, .0]) # add_line(ren, coil_loc, p2_face, color=[1.0, .0, .0]) # Add interactive axes to scene if SHOW_SCENE_AXES: axes = vtk.vtkAxesActor() widget = vtk.vtkOrientationMarkerWidget() widget.SetOutlineColor(0.9300, 0.5700, 0.1300) widget.SetOrientationMarker(axes) widget.SetInteractor(iren) # widget.SetViewport(0.0, 0.0, 0.4, 0.4) widget.SetEnabled(1) widget.InteractiveOn() # # if SCREENSHOT: # # screenshot of VTK scene # w2if = vtk.vtkWindowToImageFilter() # w2if.SetInput(ren_win) # w2if.Update() # # writer = vtk.vtkPNGWriter() # writer.SetFileName("screenshot.png") # writer.SetInput(w2if.GetOutput()) # writer.Write() # Enable user interface interactor # ren_win.Render() ren.ResetCameraClippingRange() iren.Initialize() iren.Start()
def main(): colors = vtk.vtkNamedColors() filename = get_program_parameters() # Create the reader for the data. print("Loading ", filename) reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.Update() extractEdges = vtk.vtkExtractEdges() extractEdges.SetInputConnection(reader.GetOutputPort()) legendValues = vtk.vtkVariantArray() it = reader.GetOutput().NewCellIterator() it.InitTraversal() while not it.IsDoneWithTraversal(): cell = vtk.vtkGenericCell() it.GetCell(cell) cellName = vtk.vtkCellTypes.GetClassNameFromTypeId(cell.GetCellType()) print(cellName, "NumberOfPoints:", cell.GetNumberOfPoints(), "CellDimension:", cell.GetCellDimension()) legendValues.InsertNextValue(cellName) it.GoToNextCell() # Tube the edges tubes = vtk.vtkTubeFilter() tubes.SetInputConnection(extractEdges.GetOutputPort()) tubes.SetRadius(.05) tubes.SetNumberOfSides(21) edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(tubes.GetOutputPort()) edgeMapper.SetScalarRange(0, 26) edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.GetProperty().SetSpecular(.6) edgeActor.GetProperty().SetSpecularPower(30) # Glyph the points sphere = vtk.vtkSphereSource() sphere.SetPhiResolution(21) sphere.SetThetaResolution(21) sphere.SetRadius(.08) pointMapper = vtk.vtkGlyph3DMapper() pointMapper.SetInputConnection(reader.GetOutputPort()) pointMapper.SetSourceConnection(sphere.GetOutputPort()) pointMapper.ScalingOff() pointMapper.ScalarVisibilityOff() pointActor = vtk.vtkActor() pointActor.SetMapper(pointMapper) pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d("Banana")) pointActor.GetProperty().SetSpecular(.6) pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0) pointActor.GetProperty().SetSpecularPower(100) # Label the points labelMapper = vtk.vtkLabeledDataMapper() labelMapper.SetInputConnection(reader.GetOutputPort()) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # The geometry geometryShrink = vtk.vtkShrinkFilter() geometryShrink.SetInputConnection(reader.GetOutputPort()) geometryShrink.SetShrinkFactor(.8) # NOTE: We must copy the originalLut because the CategoricalLegend # needs an indexed lookup table, but the geometryMapper uses a # non-index lookup table categoricalLut = vtk.vtkLookupTable() originalLut = reader.GetOutput().GetCellData().GetScalars().GetLookupTable( ) categoricalLut.DeepCopy(originalLut) categoricalLut.IndexedLookupOn() geometryMapper = vtk.vtkDataSetMapper() geometryMapper.SetInputConnection(geometryShrink.GetOutputPort()) geometryMapper.SetScalarModeToUseCellData() geometryMapper.SetScalarRange(0, 11) geometryActor = vtk.vtkActor() geometryActor.SetMapper(geometryMapper) geometryActor.GetProperty().SetLineWidth(3) geometryActor.GetProperty().EdgeVisibilityOn() geometryActor.GetProperty().SetEdgeColor(0, 0, 0) # Legend for v in range(0, legendValues.GetNumberOfTuples()): categoricalLut.SetAnnotation(legendValues.GetValue(v), legendValues.GetValue(v).ToString()) legend = vtk.vtkCategoryLegend() legend.SetScalarsToColors(categoricalLut) legend.SetValues(legendValues) legend.SetTitle("Cell Type") legend.GetBrush().SetColor(colors.GetColor4ub("Silver")) placeLegend = vtk.vtkContextTransform() placeLegend.AddItem(legend) placeLegend.Translate(640 - 20, 480 - 12 * 16) contextView = vtk.vtkContextView() contextView.GetScene().AddItem(placeLegend) renderer = contextView.GetRenderer() renderWindow = contextView.GetRenderWindow() renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(geometryActor) renderer.AddActor(labelActor) renderer.AddActor(edgeActor) renderer.AddActor(pointActor) renderer.SetBackground(colors.GetColor3d("SlateGray")) aCamera = vtk.vtkCamera() aCamera.Azimuth(-40.0) aCamera.Elevation(50.0) renderer.SetActiveCamera(aCamera) renderer.ResetCamera() renderWindow.SetSize(640, 480) renderWindow.Render() renderWindowInteractor.Start()
plane1Actor = vtk.vtkActor() plane1Actor.SetMapper(plane1Map) plane1Actor.GetProperty().SetOpacity(0.999) # outline outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputData(output) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineProp = outlineActor.GetProperty() outlineProp.SetColor(0, 0, 0) # Add the actors to the renderer, set the background and size # ren1.AddActor(outlineActor) ren1.AddActor(plane1Actor) ren1.SetBackground(1, 1, 1) renWin.SetSize(300, 300) cam1 = vtk.vtkCamera() cam1.SetClippingRange(14.29, 63.53) cam1.SetFocalPoint(8.58522, 1.58266, 30.6486) cam1.SetPosition(37.6808, -20.1298, 35.4016) cam1.SetViewAngle(30) cam1.SetViewUp(-0.0566235, 0.140504, 0.98846) ren1.SetActiveCamera(cam1) iren.Initialize() # render the image # # prevent the tk window from showing up then start the event loop # --- end of script --
def main(): colors = vtk.vtkNamedColors() planes = list() titles = list() # Using frustum planes. titles.append('Using frustum planes') camera = vtk.vtkCamera() planesArray = [0] * 24 camera.GetFrustumPlanes(1, planesArray) planes.append(vtk.vtkPlanes()) planes[0].SetFrustumPlanes(planesArray) # Using bounds. titles.append('Using bounds') sphereSource = vtk.vtkSphereSource() sphereSource.Update() bounds = [0] * 6 sphereSource.GetOutput().GetBounds(bounds) planes.append(vtk.vtkPlanes()) planes[1].SetBounds(bounds) # At this point we have the planes created by both of the methods above. # You can do whatever you want with them. # For visualisation we will produce an n-sided convex hull # and visualise it. # Create a common text property. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(16) textProperty.SetJustificationToCentered() renWin = vtk.vtkRenderWindow() renWin.SetSize(600, 600) renWin.SetWindowName("Planes") iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) hulls = list() pds = list() mappers = list() actors = list() renderers = list() textMappers = list() textActors = list() for i in range(0, len(planes)): hulls.append(vtk.vtkHull()) hulls[i].SetPlanes(planes[i]) pds.append(vtk.vtkPolyData()) # To generate the convex hull we supply a vtkPolyData object and a bounding box. # We define the bounding box to be where we expect the resulting polyhedron to lie. # Make it a generous fit as it is only used to create the initial # polygons that are eventually clipped. hulls[i].GenerateHull(pds[i], -200, 200, -200, 200, -200, 200) mappers.append(vtk.vtkPolyDataMapper()) mappers[i].SetInputData(pds[i]) actors.append(vtk.vtkActor()) actors[i].SetMapper(mappers[i]) actors[i].GetProperty().SetColor(colors.GetColor3d("Moccasin")) actors[i].GetProperty().SetSpecular(0.8) actors[i].GetProperty().SetSpecularPower(30) renderers.append(vtk.vtkRenderer()) renderers[i].AddActor(actors[i]) textMappers.append(vtk.vtkTextMapper()) textMappers[i].SetInput(titles[i]) textMappers[i].SetTextProperty(textProperty) textActors.append(vtk.vtkActor2D()) textActors[i].SetMapper(textMappers[i]) textActors[i].SetPosition(100, 10) renderers[i].AddViewProp(textActors[i]) renWin.AddRenderer(renderers[i]) # Setup the viewports xGridDimensions = 2 yGridDimensions = 1 rendererSize = 300 renWin.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("DarkSlateGray")) ren.SetViewport(viewport) renWin.AddRenderer(ren) continue renderers[index].SetViewport(viewport) renderers[index].SetBackground(colors.GetColor3d("DarkSlateGray")) renderers[index].ResetCamera() renderers[index].GetActiveCamera().Azimuth(30) renderers[index].GetActiveCamera().Elevation(-30) renderers[index].ResetCameraClippingRange() iRen.Initialize() renWin.Render() iRen.Start()
#!/usr/bin/env python import chigger import sys import vtk reader = chigger.exodus.ExodusReader(sys.argv[1], timestep=int(sys.argv[2])) camera = vtk.vtkCamera() camera.SetViewUp(0.0000, 1.0000, 0.0000) camera.SetPosition(100.0000, 100.0000, 375.0) camera.SetFocalPoint(100.0000, 100.0000, 0.0000) # model = chigger.exodus.ExodusResult(reader, variable=sys.argv[3], cmap='viridis', background=[1,1,1], camera=camera) model = chigger.exodus.ExodusResult(reader, variable=sys.argv[3], camera=camera) window = chigger.RenderWindow(model, size=[800, 800], test=True) window.write('out.png') #print chigger.utils.printcamera(model.getVTKRenderer().GetActiveCamera()) window.start()
def visualization(library, data, clsfct, num_label): #------------------------------------ Read Plot File ------------------------------------ idx = 0 total_corner = 0 Total_circular_corner = 0 while (idx < len(data) - 1): if (data[idx] == 'BOUNDARIES'): idx = idx + 1 numBoundary = int(data[idx]) idx = idx + 1 Boundary = np.zeros( (numBoundary, 4 * 3)) #4 corners of each Boundary bd_total_corner = numBoundary * 4 option = 'Boundary' elif (data[idx] == 'PARTICLES'): idx = idx + 1 numParticle = int(data[idx]) idx = idx + 1 Particle = [] #number of Particles numCorner = np.zeros( numParticle) #number of corners for the Particle accumulateCornerNum = [] shape = [] #Particle Library Number for each Particle option = 'Particle' elif (data[idx] == 'CircularBOUNDARIES'): idx = idx + 1 numCircularBoundary = int(data[idx]) idx = idx + 1 CircularBoundary = [] #number of Particles CircualrCorner = np.zeros( (numCircularBoundary, 4)) #number of corners for the Particle Total_circular_corner = numCircularBoundary * 20 option = 'CircularBOUNDARIES' if (option == 'Boundary'): for i in range(0, numBoundary): # each Boundary for j in range(0, 4): #x y z of each corners Boundary[i][j * 3] = float(data[idx]) idx = idx + 1 Boundary[i][j * 3 + 1] = float(data[idx]) idx = idx + 1 Boundary[i][j * 3 + 2] = float(data[idx]) idx = idx + 1 if (option == 'CircularBOUNDARIES'): for i in range(0, numCircularBoundary): # each Boundary CircualrCorner[i][0] = float(data[idx]) idx = idx + 1 CircualrCorner[i][1] = float(data[idx]) idx = idx + 1 CircualrCorner[i][2] = float(data[idx]) idx = idx + 1 CircualrCorner[i][3] = float(data[idx]) idx = idx + 1 if (option == 'Particle'): total_corner = bd_total_corner + Total_circular_corner for i in range(0, numParticle): #for each particle size = int(data[idx]) accumulateCornerNum.append(int(total_corner)) total_corner = total_corner + size idx = idx + 1 #Particle[i] = np.zeros(size*3)#store number of corner x y z numCorner[i] = size #store number of corner shape.append(int(data[idx])) #store library number idx = idx + 1 for j in range(0, size): Particle.append(float(data[idx])) idx = 1 + idx Particle.append(float(data[idx])) idx = 1 + idx Particle.append(float(data[idx])) idx = 1 + idx # store the vertex locations. vertex_locations = vtk.vtkPoints() vertex_locations.SetNumberOfPoints(total_corner) for nb in range(0, numBoundary): for i in range(0, 4): vertex_locations.SetPoint( nb * 4 + i, (Boundary[nb][i * 3], Boundary[nb][i * 3 + 2], Boundary[nb][i * 3 + 1])) setnumber = 4 * numBoundary for nb in range(0, numCircularBoundary): for i in range(0, 20): vertex_locations.SetPoint( setnumber, (CircualrCorner[nb][0] + CircualrCorner[nb][3] * np.cos(math.radians(360 / 20 * i)), CircualrCorner[nb][2], CircualrCorner[nb][1] + CircualrCorner[nb][3] * np.sin(math.radians(360 / 20 * i)))) setnumber = setnumber + 1 i = 0 while (setnumber < total_corner): x = i y = i + 1 z = i + 2 vertex_locations.SetPoint(setnumber, (Particle[x], Particle[z], Particle[y])) setnumber = setnumber + 1 i = i + 3 del data[:] del Particle[:] lib = open("library.vlb", 'r') #--------------------------------- Read Library ------------------------------- libdata = [] for line in lib.read().split('\n'): if not line.startswith('//') and not line.startswith( 'Particle') and not line.startswith('Master'): for chunk in line.split(' '): for word in chunk.split('\t'): if word == '': continue if word == '\t': continue libdata.append(word) lib.close() idx = 0 numParticleShape = int(libdata[idx]) idx = idx + 1 numMasterShape = int(libdata[idx]) idx = idx + 1 Particlelib = [] Particles_face = [] for ns in range(0, numParticleShape): Particlelib.append([]) skip1 = int(libdata[idx]) #num of points idx = idx + 1 face = int(libdata[idx]) #num of face Particles_face.append( face) #save num of faces for each particle in library idx = idx + 1 skip2 = int(libdata[idx]) #num of edge idx = idx + 1 idx = idx + skip1 * 3 i = 0 while i < face: numface = int(libdata[idx]) # num of points on a face Particlelib[ns].append(numface) idx = idx + 1 i = i + 1 for nf in range(0, numface): Particlelib[ns].append(int(libdata[idx])) idx = idx + 1 for i in range(0, skip1): add = int(libdata[idx]) idx = idx + add + 1 idx = idx + 1 numMas = 0 for ms in range(0, numMasterShape): numslave = int(libdata[idx]) idx = idx + 2 for slav in range(0, numslave): Particlelib.append([]) skip1 = int(libdata[idx]) idx = idx + 1 face = int(libdata[idx]) Particles_face.append(face) #save num of faces for each particle idx = idx + 1 skip2 = int(libdata[idx]) idx = idx + 1 idx = idx + skip1 * 3 i = 0 while i < face: numface = int(libdata[idx]) Particlelib[numParticleShape + numMas].append(numface) idx = idx + 1 for nf in range(0, numface): Particlelib[numParticleShape + numMas].append( int(libdata[idx])) idx = idx + 1 i = i + 1 for i in range(0, skip1): add = int(libdata[idx]) idx = idx + add + 1 idx = idx + 1 + skip1 + 3 numMas = numMas + 1 del libdata[:] # ----------------------------------- Set Face ---------------------------- # describe the polygons that represent the faces using the vertex # indices in the vtkPoints that stores the vertex locations. There are a number # of ways to do this that you can find in examples on the Wiki. boundary_faces = vtk.vtkCellArray() for nb in range(0, numBoundary): if (nb != 0): continue q = vtk.vtkPolygon() q.GetPointIds().SetNumberOfIds(4) #make a quad q.GetPointIds().SetId(0, nb * 4) q.GetPointIds().SetId(1, nb * 4 + 1) q.GetPointIds().SetId(2, nb * 4 + 2) q.GetPointIds().SetId(3, nb * 4 + 3) boundary_faces.InsertNextCell(q) bd = vtk.vtkPolyData() bd.SetPoints(vertex_locations) bd.SetPolys(boundary_faces) Circular_boundary_faces = vtk.vtkCellArray() for nb in range(0, numCircularBoundary): cir = vtk.vtkPolygon() cir.GetPointIds().SetNumberOfIds(20) #make a quad for ed in range(0, 20): cir.GetPointIds().SetId(ed, nb * 20 + ed) Circular_boundary_faces.InsertNextCell(cir) # Next create a vtkPolyData to store your face and vertex information that # represents your polyhedron. cbd = vtk.vtkPolyData() cbd.SetPoints(vertex_locations) cbd.SetPolys(Circular_boundary_faces) #-----------------------color generation------------------------------------ color_list = [(255, 0, 0), (255, 128, 0), (255, 255, 0), (0, 204, 0), (0, 204, 204), (0, 0, 204), (102, 0, 204), (96, 96, 96)] # set up color Colors = vtk.vtkUnsignedCharArray() Colors.SetNumberOfComponents(3) Colors.SetName("Colors") particle_faces = vtk.vtkCellArray() for nb in range(0, numParticle): # set color for each cluster for num_face in range(0, Particles_face[shape[nb]]): label = clsfct[nb] if shape[nb] == 0: Colors.InsertNextTuple3(1, 0, 0) else: Colors.InsertNextTuple3(color_list[label][0], color_list[label][1], color_list[label][2]) i = 0 # Add the polygon to a list of polygons while (i < len(Particlelib[shape[nb]])): numVertex = Particlelib[shape[nb]][i] i = i + 1 polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(numVertex) #make a quad for nv in range(0, numVertex): polygon.GetPointIds().SetId( nv, Particlelib[shape[nb]][i] + accumulateCornerNum[nb]) #make a face i = i + 1 particle_faces.InsertNextCell(polygon) # Next you create a vtkPolyData to store your face and vertex information that # represents your polyhedron. pd = vtk.vtkPolyData() pd.SetPoints(vertex_locations) pd.SetPolys(particle_faces) pd.GetCellData().SetScalars(Colors) #---------------------# # visualization # #---------------------# mapper1 = vtk.vtkPolyDataMapper() mapper1.SetInputData(bd) actor1 = vtk.vtkActor() actor1.SetMapper(mapper1) actor1.GetProperty().SetColor(1, 0, 0) mapperC = vtk.vtkPolyDataMapper() mapperC.SetInputData(cbd) actorC = vtk.vtkActor() actorC.SetMapper(mapperC) actorC.GetProperty().SetColor(1, 0, 0) mapper2 = vtk.vtkPolyDataMapper() mapper2.SetInputData(pd) actor2 = vtk.vtkActor() actor2.SetMapper(mapper2) actor2.GetProperty().SetColor(0.5, 0.5, 0.5) actor2.GetProperty().SetOpacity(1) # -------------------------Set axes --------------------------------- transform = vtk.vtkTransform() transform.Translate(2.5, 1.0, 2.5) axes = vtk.vtkAxesActor() # The axes are positioned with a user transform axes.SetUserTransform(transform) # -------------------------Set Camera --------------------------------- camera = vtk.vtkCamera() cameraX, cameraY, cameraZ = 0, 0, 0 camera.SetPosition(float(cameraX), float(cameraY), float(cameraZ)) camera.SetFocalPoint(2.5, 0.75, 0.5) ren = vtk.vtkRenderer() ren.SetActiveCamera(camera) ren.AddActor(actor1) ren.AddActor(actorC) ren.AddActor(actor2) ren.SetBackground(1, 1, 1) # Background color white renw = vtk.vtkRenderWindow() renw.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renw) renw.Render() iren.Start()
def plot_so3(I, mask=None, shape="tric", filename=None): """ Plot (masked) image of SO(3) rotation matrices """ import vtk imagedims = I.shape[:-1] if mask is None: mask = np.zeros(imagedims, dtype=bool) M = quaternion_so3(I) if shape == "piano": # https://www.thingiverse.com/thing:148696 # CC-BY-NC-SA kazysd stl_file = "data/piano_assembly.stl" steps = 200 pos = (150, -20, 0) else: # https://www.thingiverse.com/thing:3313805 # CC-BY-NC-SA BillyOceansBlues stl_file = "data/Triceratops_plane_cut.stl" steps = 100 pos = (0, 0, 0) reader = vtk.vtkSTLReader() reader.SetFileName(stl_file) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(reader.GetOutputPort()) camzoom = 100 # simulates parallel projection camdist = camzoom * 2 * steps * max(*imagedims) campos = (0.5 * steps * (imagedims[1] - 1), -camdist, -0.5 * steps * (imagedims[0] - 1)) camera = vtk.vtkCamera() camera.SetPosition(*campos) camera.SetFocalPoint(campos[0] + 1, 0, campos[2] - 1) # bug in VTK (polar coords?) camera.Roll(45) camera.Zoom(camzoom) camera.SetClippingRange(0.5 * camdist, 2 * camdist) ren = vtk.vtkRenderer() ren.SetActiveCamera(camera) ren.SetBackground(vtk.vtkNamedColors().GetColor3d("White")) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) matrix = vtk.vtkMatrix4x4() for i in range(imagedims[0]): for j in range(imagedims[1]): actor = vtk.vtkActor() actor.SetMapper(mapper) col = (1.0, 0.4, 0.5) if mask[i, j] else (0.7, 0.7, 0.7) actor.GetProperty().SetColor(*col) actor.SetPosition(*pos) T = np.eye(4) T[:3, 3] = np.array([steps * j, 0, -steps * i]) T[:3, :3] = M[i, j] [ matrix.SetElement(k, l, T[k, l]) for k in range(4) for l in range(4) ] T = vtk.vtkTransform() T.SetMatrix(matrix) actor.SetUserTransform(T) ren.AddActor(actor) if filename is None: iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.Initialize() renWin.Render() iren.Start() else: filename = "%s.png" % filename[:-4] renWin.SetOffScreenRendering(True) renWin.Render() win2img = vtk.vtkWindowToImageFilter() win2img.SetInput(renWin) win2img.SetScale(10) win2img.SetInputBufferTypeToRGBA() writer = vtk.vtkPNGWriter() writer.SetInputConnection(win2img.GetOutputPort()) writer.SetFileName(filename) writer.Write()
def VTK3d(): aRenderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(aRenderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # The following reader is used to read a series of 2D slices(images) # that compose the volume.Theslicedimensions are set, and the # pixel spacing.The data Endianness must also be specified.The reader # uses the FilePrefix in combination with the slice number to construct # filenames using the format FilePrefix. % d.(In this case the FilePrefix # is the root name of the file. v16 = vtk.vtkDICOMImageReader() v16.SetDataByteOrderToLittleEndian() v16.SetDirectoryName( "/Users/zhangyesheng/Desktop/医学信息学/BrainMRIProcess/Dicom/brain") v16.SetDataSpacing(3.2, 3.2, 1.5) # v16.SetDataSpacing(1.0, 1.0, 1.5); # An isosurface, or contour value of 500 is known to correspond to the # skin of the patient.Once generated, a vtkPolyDataNormals filter is # used to create normals for smooth surface shading during rendering. skinExtractor = vtk.vtkContourFilter() skinExtractor.SetInputConnection(v16.GetOutputPort()) skinExtractor.SetValue(0, 500) skinNormals = vtk.vtkPolyDataNormals() skinNormals.SetInputConnection(skinExtractor.GetOutputPort()) skinNormals.SetFeatureAngle(60.0) skinMapper = vtk.vtkPolyDataMapper() skinMapper.SetInputConnection(skinNormals.GetOutputPort()) skinMapper.ScalarVisibilityOff() skin = vtk.vtkActor() skin.SetMapper(skinMapper) outlineData = vtk.vtkOutlineFilter() outlineData.SetInputConnection(v16.GetOutputPort()) mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outlineData.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(mapOutline) outline.GetProperty().SetColor(0, 0, 0) aCamera = vtk.vtkCamera() aCamera.SetViewUp(0, 0, -1) aCamera.SetPosition(0, 1, 0) aCamera.SetFocalPoint(0, 0, 0) aCamera.ComputeViewPlaneNormal() # Actors are added to the renderer.An initial camera view is created. # The Dolly() method moves the camera towards the FocalPoint, # thereby enlarging the image. aRenderer.AddActor(outline) aRenderer.AddActor(skin) aRenderer.SetActiveCamera(aCamera) aRenderer.ResetCamera() aCamera.Dolly(1.5) aRenderer.SetBackground(1, 1, 1) renWin.SetSize(640, 480) aRenderer.ResetCameraClippingRange() iren.Initialize() iren.Start() v16.Delete() skinExtractor.Delete() skinNormals.Delete() skinMapper.Delete() skin.Delete() outlineData.Delete() mapOutline.Delete() outline.Delete() aCamera.Delete() iren.Delete() renWin.Delete() aRenderer.Delete()
def main(): # Decide what approach to use. use_function_callback = True colors = vtk.vtkNamedColors() # Create the Renderer, RenderWindow and RenderWindowInteractor. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Use a cone as a source. source = vtk.vtkConeSource() source.SetCenter(0, 0, 0) source.SetRadius(1) # Use the golden ratio for the height. Because we can! source.SetHeight(1.6180339887498948482) source.SetResolution(128) source.Update() # Pipeline mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(source.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d("peacock")) # Lighting actor.GetProperty().SetAmbient(0.3) actor.GetProperty().SetDiffuse(0.0) actor.GetProperty().SetSpecular(1.0) actor.GetProperty().SetSpecularPower(20.0) # Get an outline of the data set for context. outline = vtk.vtkOutlineFilter() outline.SetInputData(source.GetOutput()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.GetProperty().SetColor(colors.GetColor3d("Black")) outlineActor.SetMapper(outlineMapper) # Add the actors to the renderer, set the background and size. ren.AddActor(actor) ren.AddActor(outlineActor) ren.SetBackground(colors.GetColor3d("AliceBlue")) renWin.SetSize(512, 512) # Set up a nice camera position. camera = vtk.vtkCamera() camera.SetPosition(4.6, -2.0, 3.8) camera.SetFocalPoint(0.0, 0.0, 0.0) camera.SetClippingRange(3.2, 10.2) camera.SetViewUp(0.3, 1.0, 0.13) ren.SetActiveCamera(camera) renWin.Render() renWin.SetWindowName("CallBack") axes1 = MakeAxesActor() om1 = vtk.vtkOrientationMarkerWidget() om1.SetOrientationMarker(axes1) # Position lower left in the viewport. om1.SetViewport(0, 0, 0.2, 0.2) om1.SetInteractor(iren) om1.EnabledOn() om1.InteractiveOn() # Set up the callback. if use_function_callback: # We are going to output the camera position when the event is triggered # so we add the active camera as an attribute. GetOrientation.cam = ren.GetActiveCamera() # Register the callback with the object that is observing. iren.AddObserver('EndInteractionEvent', GetOrientation) else: iren.AddObserver('EndInteractionEvent', OrientationObserver(ren.GetActiveCamera())) # Or: # observer = OrientationObserver(ren.GetActiveCamera()) # iren.AddObserver('EndInteractionEvent', observer) iren.Initialize() iren.Start()
def main(): """ ^y | 8----9----10---11 | / | / | / | 4----5----6----7 | / | / | / | 0----1----2----3 --> x """ ugrid = vtk.vtkUnstructuredGrid() xyzs = [ [0., 0., 0.], [1., 0., 0.], [2., 0., 0.], [3., 0., 0.], [0., 1., 0.], [1., 1., 0.], [2., 1., 0.], [3., 1., 0.], [0., 2., 0.], [1., 2., 0.], [2., 2., 0.], [3., 2., 0.], ] # we make the lower triangle first, then the upper one to finish off the quad # go accross each row, left to right tris = [ [0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [4, 5, 9], [4, 9, 8], [5, 6, 10], [5, 10, 9], [6, 7, 11], [6, 11, 10], ] ids_to_show = [ 0, 1, #2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] ids_to_show_updated = [ 0, 1, #2, 3, #4, 5, 6, 7, 8, 9, 10, 11, 12 ] nnodes = len(xyzs) points = vtk.vtkPoints() points.SetNumberOfPoints(nnodes) nid = 0 for i, xyz in enumerate(xyzs): points.InsertPoint(nid, *xyz) nid += 1 for tri in tris: elem = vtk.vtkTriangle() (n1, n2, n3) = tri elem.GetPointIds().SetId(0, n1) elem.GetPointIds().SetId(1, n2) elem.GetPointIds().SetId(2, n3) ugrid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) ugrid.SetPoints(points) grid_mapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: grid_mapper.SetInputConnection(ugrid.GetProducerPort()) else: grid_mapper.SetInputData(ugrid) input_actor = vtk.vtkActor() input_actor.SetMapper(grid_mapper) render_window = vtk.vtkRenderWindow() camera = vtk.vtkCamera() interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) print("There are %s input points" % ugrid.GetNumberOfPoints()) print("There are %s input cells" % ugrid.GetNumberOfCells()) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) ids.Allocate(len(ids_to_show)) for id_to_show in ids_to_show: ids.InsertNextValue(id_to_show) selection_node = vtk.vtkSelectionNode() selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection_node.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selection_node) extract_selection = vtk.vtkExtractSelection() if vtk.VTK_MAJOR_VERSION <= 5: extract_selection.SetInput(0, ugrid) extract_selection.SetInput(1, selection) else: extract_selection.SetInputData(0, ugrid) extract_selection.SetInputData(1, selection) extract_selection.Update() # In selection grid_selected = vtk.vtkUnstructuredGrid() grid_selected.ShallowCopy(extract_selection.GetOutput()) print("There are %s points in the selection" % grid_selected.GetNumberOfPoints()) print("There are %s cells in the selection" % grid_selected.GetNumberOfCells()) # Get points that are NOT in the selection # invert the selection selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) extract_selection.Update() not_selected = vtk.vtkUnstructuredGrid() not_selected.ShallowCopy(extract_selection.GetOutput()) print("There are %s points NOT in the selection" % not_selected.GetNumberOfPoints()) print("There are %s cells NOT in the selection" % not_selected.GetNumberOfCells()) selected_mapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: selected_mapper.SetInputConnection(grid_selected.GetProducerPort()) else: selected_mapper.SetInputData(grid_selected) selected_actor = vtk.vtkActor() selected_actor.SetMapper(selected_mapper) not_selected_mapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: not_selected_mapper.SetInputConnection(not_selected.GetProducerPort()) else: not_selected_mapper.SetInputData(not_selected) not_selected_actor = vtk.vtkActor() not_selected_actor.SetMapper(not_selected_mapper) # There will be one render window render_window = vtk.vtkRenderWindow() render_window.SetSize(900, 300) # And one interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) # Define viewport ranges # (xmin, ymin, xmax, ymax) left_viewport = [0.0, 0.0, 0.5, 1.0] right_viewport = [0.5, 0.0, 1.0, 1.0] # Create a camera for all renderers camera = vtk.vtkCamera() # Setup the renderers left_renderer = vtk.vtkRenderer() render_window.AddRenderer(left_renderer) left_renderer.SetViewport(left_viewport) left_renderer.SetBackground(.6, .5, .4) left_renderer.SetActiveCamera(camera) right_renderer = vtk.vtkRenderer() render_window.AddRenderer(right_renderer) right_renderer.SetViewport(right_viewport) right_renderer.SetBackground(.3, .1, .4) right_renderer.SetActiveCamera(camera) right_renderer.AddActor(selected_actor) left_renderer.AddActor(input_actor) right_renderer.AddActor(not_selected_actor) right_renderer.ResetCamera() interactor.Start() #----------------- ids.Reset() ids.Allocate(len(ids_to_show_updated)) for id_to_show in ids_to_show_updated: ids.InsertNextValue(id_to_show) ids.Modified() grid_selected.Modified() #ids.Update() ids.Modified() #selection_node.Update() selection_node.Modified() #selection.Update() selection.Modified() extract_selection.Update() extract_selection.Modified() #grid_selected.Update() grid_selected.Modified() selected_mapper.Update() selected_mapper.Modified() #selected_actor.Update() selected_actor.Modified() right_renderer.Modified() #right_renderer.Update() interactor.Modified() #interactor.Update() #----------------- render_window.Render() render_window.Modified()
def main(): colors = vtk.vtkNamedColors() colors.SetColor('leftBkg', [0.6, 0.5, 0.4, 1.0]) colors.SetColor('centreBkg', [0.3, 0.1, 0.4, 1.0]) colors.SetColor('rightBkg', [0.4, 0.5, 0.6, 1.0]) sphereSource = vtk.vtkSphereSource() sphereSource.Update() print("There are %s input points" % sphereSource.GetOutput().GetNumberOfPoints()) print("There are %s input cells" % sphereSource.GetOutput().GetNumberOfCells()) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) # Specify that we want to extract cells 10 through 19 i = 10 while i < 20: ids.InsertNextValue(i) i += 1 selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selectionNode) extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputConnection(0, sphereSource.GetOutputPort()) extractSelection.SetInputData(1, selection) extractSelection.Update() # In selection selected = vtk.vtkUnstructuredGrid() selected.ShallowCopy(extractSelection.GetOutput()) print("There are %s points in the selection" % selected.GetNumberOfPoints()) print("There are %s cells in the selection" % selected.GetNumberOfCells()) # Get points that are NOT in the selection selectionNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) # invert the selection extractSelection.Update() notSelected = vtk.vtkUnstructuredGrid() notSelected.ShallowCopy(extractSelection.GetOutput()) print("There are %s points NOT in the selection" % notSelected.GetNumberOfPoints()) print("There are %s cells NOT in the selection" % notSelected.GetNumberOfCells()) backfaces = vtk.vtkProperty() backfaces.SetColor(colors.GetColor3d('Red')) inputMapper = vtk.vtkDataSetMapper() inputMapper.SetInputConnection(sphereSource.GetOutputPort()) inputActor = vtk.vtkActor() inputActor.SetMapper(inputMapper) inputActor.SetBackfaceProperty(backfaces) selectedMapper = vtk.vtkDataSetMapper() selectedMapper.SetInputData(selected) selectedActor = vtk.vtkActor() selectedActor.SetMapper(selectedMapper) selectedActor.SetBackfaceProperty(backfaces) notSelectedMapper = vtk.vtkDataSetMapper() notSelectedMapper.SetInputData(notSelected) notSelectedActor = vtk.vtkActor() notSelectedActor.SetMapper(notSelectedMapper) notSelectedActor.SetBackfaceProperty(backfaces) # There will be one render window renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(900, 300) # And one interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) # Define viewport ranges # (xmin, ymin, xmax, ymax) leftViewport = [0.0, 0.0, 0.5, 1.0] centerViewport = [0.33, 0.0, .66, 1.0] rightViewport = [0.66, 0.0, 1.0, 1.0] # Create a camera for all renderers camera = vtk.vtkCamera() # Setup the renderers leftRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(leftRenderer) leftRenderer.SetViewport(leftViewport) leftRenderer.SetBackground(colors.GetColor3d('leftBkg')) leftRenderer.SetActiveCamera(camera) centerRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(centerRenderer) centerRenderer.SetViewport(centerViewport) centerRenderer.SetBackground(colors.GetColor3d('centreBkg')) centerRenderer.SetActiveCamera(camera) rightRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(rightRenderer) rightRenderer.SetViewport(rightViewport) rightRenderer.SetBackground(colors.GetColor3d('rightBkg')) rightRenderer.SetActiveCamera(camera) leftRenderer.AddActor(inputActor) centerRenderer.AddActor(selectedActor) rightRenderer.AddActor(notSelectedActor) leftRenderer.ResetCamera() renderWindow.Render() interactor.Start()
def ShowCuttingPlanesOnImage(input_file, cutting_planes): ## Get vtk format file_format = input_file.split(".")[-1] input_vtk = input_file.replace(file_format, "vtk") if file_format == "nrrd": image = Image(input_file) mesh = image.toMesh() mesh.write(input_vtk) print("\nCreating mesh from: " + input_file) print("\nSaving as: " + input_vtk) elif file_format == "ply" or file_format == "stl": mesh = Mesh(file_format) mesh.write(input_vtk) else: print("Error, file format unrecognized: " + input_file) ## VTK interactive window print('\n Use the interactive window to select your cutting plane. When you are content with your selection, simply close the window. \n') # read data from file reader = vtk.vtkPolyDataReader() reader.SetFileName(input_vtk) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() # get data data = reader.GetOutput() (xcenter, ycenter, zcenter) = data.GetCenter() #create mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(data) # The actor is a grouping mechanism actor = vtk.vtkActor() actor.SetMapper(mapper) # create camera camera = vtk.vtkCamera() camera.SetFocalPoint(xcenter, ycenter, zcenter) camera.SetPosition(100, -300, -50) camera.SetViewUp(0,0,1) # create a renderer renderer = vtk.vtkRenderer() renderer.SetActiveCamera(camera) renderer.SetBackground(0.2, 0.2, 0.5) renderer.SetBackground2(0.4, 0.4, 1.0) renderer.SetGradientBackground(True) renderer.AddActor(actor) # create a render_window render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetSize(1000,1000) # create a renderwindowiren iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(render_window) iren.Initialize() # Create a vtkImagePlaneWidget and activate it reps = [] plane_widgets = [] print(len(cutting_planes)) for plane in cutting_planes: print(plane) A = np.array(plane[0]) B = np.array(plane[1]) C = np.array(plane[2]) n = np.cross(B-A, C-A) n = n/np.linalg.norm(n) d = -np.dot(A, n) print(n, d) rep = vtk.vtkImplicitPlaneRepresentation() rep.SetPlaceFactor(1.5) rep.SetOrigin(A) rep.PlaceWidget(actor.GetBounds()) rep.SetNormal(n[0],n[1],n[2]) reps.append(rep) plane_widget = vtk.vtkImplicitPlaneWidget2() plane_widget.SetInteractor(iren) plane_widget.SetRepresentation(rep) plane_widget.On() plane_widgets.append(plane_widget) iren.Initialize() iren.Start() '''
def main(): fileName = get_program_parameters() colors = vtk.vtkNamedColors() # Set the furniture colors. colors.SetColor('Furniture', [204, 204, 153, 255]) scalarRange = [0.0, 0.0] maxTime = 0 aren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(aren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # # Read the data. # reader = vtk.vtkStructuredGridReader() reader.SetFileName(fileName) reader.Update() # Force a read to occur. reader.GetOutput().GetLength() if reader.GetOutput().GetPointData().GetScalars(): reader.GetOutput().GetPointData().GetScalars().GetRange(scalarRange) if reader.GetOutput().GetPointData().GetVectors(): maxVelocity = reader.GetOutput().GetPointData().GetVectors( ).GetMaxNorm() maxTime = 4.0 * reader.GetOutput().GetLength() / maxVelocity # # Outline around the data. # outlineF = vtk.vtkStructuredGridOutlineFilter() outlineF.SetInputConnection(reader.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outlineF.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(outlineMapper) outline.GetProperty().SetColor(colors.GetColor3d('LampBlack')) # # Set up shaded surfaces (i.e., supporting geometry). # doorGeom = vtk.vtkStructuredGridGeometryFilter() doorGeom.SetInputConnection(reader.GetOutputPort()) doorGeom.SetExtent(27, 27, 14, 18, 0, 11) mapDoor = vtk.vtkPolyDataMapper() mapDoor.SetInputConnection(doorGeom.GetOutputPort()) mapDoor.ScalarVisibilityOff() door = vtk.vtkActor() door.SetMapper(mapDoor) door.GetProperty().SetColor(colors.GetColor3d('Burlywood')) window1Geom = vtk.vtkStructuredGridGeometryFilter() window1Geom.SetInputConnection(reader.GetOutputPort()) window1Geom.SetExtent(0, 0, 9, 18, 6, 12) mapWindow1 = vtk.vtkPolyDataMapper() mapWindow1.SetInputConnection(window1Geom.GetOutputPort()) mapWindow1.ScalarVisibilityOff() window1 = vtk.vtkActor() window1.SetMapper(mapWindow1) window1.GetProperty().SetColor(colors.GetColor3d('SkyBlue')) window1.GetProperty().SetOpacity(.6) window2Geom = vtk.vtkStructuredGridGeometryFilter() window2Geom.SetInputConnection(reader.GetOutputPort()) window2Geom.SetExtent(5, 12, 23, 23, 6, 12) mapWindow2 = vtk.vtkPolyDataMapper() mapWindow2.SetInputConnection(window2Geom.GetOutputPort()) mapWindow2.ScalarVisibilityOff() window2 = vtk.vtkActor() window2.SetMapper(mapWindow2) window2.GetProperty().SetColor(colors.GetColor3d('SkyBlue')) window2.GetProperty().SetOpacity(.6) klower1Geom = vtk.vtkStructuredGridGeometryFilter() klower1Geom.SetInputConnection(reader.GetOutputPort()) klower1Geom.SetExtent(17, 17, 0, 11, 0, 6) mapKlower1 = vtk.vtkPolyDataMapper() mapKlower1.SetInputConnection(klower1Geom.GetOutputPort()) mapKlower1.ScalarVisibilityOff() klower1 = vtk.vtkActor() klower1.SetMapper(mapKlower1) klower1.GetProperty().SetColor(colors.GetColor3d('EggShell')) klower2Geom = vtk.vtkStructuredGridGeometryFilter() klower2Geom.SetInputConnection(reader.GetOutputPort()) klower2Geom.SetExtent(19, 19, 0, 11, 0, 6) mapKlower2 = vtk.vtkPolyDataMapper() mapKlower2.SetInputConnection(klower2Geom.GetOutputPort()) mapKlower2.ScalarVisibilityOff() klower2 = vtk.vtkActor() klower2.SetMapper(mapKlower2) klower2.GetProperty().SetColor(colors.GetColor3d('EggShell')) klower3Geom = vtk.vtkStructuredGridGeometryFilter() klower3Geom.SetInputConnection(reader.GetOutputPort()) klower3Geom.SetExtent(17, 19, 0, 0, 0, 6) mapKlower3 = vtk.vtkPolyDataMapper() mapKlower3.SetInputConnection(klower3Geom.GetOutputPort()) mapKlower3.ScalarVisibilityOff() klower3 = vtk.vtkActor() klower3.SetMapper(mapKlower3) klower3.GetProperty().SetColor(colors.GetColor3d('EggShell')) klower4Geom = vtk.vtkStructuredGridGeometryFilter() klower4Geom.SetInputConnection(reader.GetOutputPort()) klower4Geom.SetExtent(17, 19, 11, 11, 0, 6) mapKlower4 = vtk.vtkPolyDataMapper() mapKlower4.SetInputConnection(klower4Geom.GetOutputPort()) mapKlower4.ScalarVisibilityOff() klower4 = vtk.vtkActor() klower4.SetMapper(mapKlower4) klower4.GetProperty().SetColor(colors.GetColor3d('EggShell')) klower5Geom = vtk.vtkStructuredGridGeometryFilter() klower5Geom.SetInputConnection(reader.GetOutputPort()) klower5Geom.SetExtent(17, 19, 0, 11, 0, 0) mapKlower5 = vtk.vtkPolyDataMapper() mapKlower5.SetInputConnection(klower5Geom.GetOutputPort()) mapKlower5.ScalarVisibilityOff() klower5 = vtk.vtkActor() klower5.SetMapper(mapKlower5) klower5.GetProperty().SetColor(colors.GetColor3d('EggShell')) klower6Geom = vtk.vtkStructuredGridGeometryFilter() klower6Geom.SetInputConnection(reader.GetOutputPort()) klower6Geom.SetExtent(17, 19, 0, 7, 6, 6) mapKlower6 = vtk.vtkPolyDataMapper() mapKlower6.SetInputConnection(klower6Geom.GetOutputPort()) mapKlower6.ScalarVisibilityOff() klower6 = vtk.vtkActor() klower6.SetMapper(mapKlower6) klower6.GetProperty().SetColor(colors.GetColor3d('EggShell')) klower7Geom = vtk.vtkStructuredGridGeometryFilter() klower7Geom.SetInputConnection(reader.GetOutputPort()) klower7Geom.SetExtent(17, 19, 9, 11, 6, 6) mapKlower7 = vtk.vtkPolyDataMapper() mapKlower7.SetInputConnection(klower7Geom.GetOutputPort()) mapKlower7.ScalarVisibilityOff() klower7 = vtk.vtkActor() klower7.SetMapper(mapKlower7) klower7.GetProperty().SetColor(colors.GetColor3d('EggShell')) hood1Geom = vtk.vtkStructuredGridGeometryFilter() hood1Geom.SetInputConnection(reader.GetOutputPort()) hood1Geom.SetExtent(17, 17, 0, 11, 11, 16) mapHood1 = vtk.vtkPolyDataMapper() mapHood1.SetInputConnection(hood1Geom.GetOutputPort()) mapHood1.ScalarVisibilityOff() hood1 = vtk.vtkActor() hood1.SetMapper(mapHood1) hood1.GetProperty().SetColor(colors.GetColor3d('Silver')) hood2Geom = vtk.vtkStructuredGridGeometryFilter() hood2Geom.SetInputConnection(reader.GetOutputPort()) hood2Geom.SetExtent(19, 19, 0, 11, 11, 16) mapHood2 = vtk.vtkPolyDataMapper() mapHood2.SetInputConnection(hood2Geom.GetOutputPort()) mapHood2.ScalarVisibilityOff() hood2 = vtk.vtkActor() hood2.SetMapper(mapHood2) hood2.GetProperty().SetColor(colors.GetColor3d('Furniture')) hood3Geom = vtk.vtkStructuredGridGeometryFilter() hood3Geom.SetInputConnection(reader.GetOutputPort()) hood3Geom.SetExtent(17, 19, 0, 0, 11, 16) mapHood3 = vtk.vtkPolyDataMapper() mapHood3.SetInputConnection(hood3Geom.GetOutputPort()) mapHood3.ScalarVisibilityOff() hood3 = vtk.vtkActor() hood3.SetMapper(mapHood3) hood3.GetProperty().SetColor(colors.GetColor3d('Furniture')) hood4Geom = vtk.vtkStructuredGridGeometryFilter() hood4Geom.SetInputConnection(reader.GetOutputPort()) hood4Geom.SetExtent(17, 19, 11, 11, 11, 16) mapHood4 = vtk.vtkPolyDataMapper() mapHood4.SetInputConnection(hood4Geom.GetOutputPort()) mapHood4.ScalarVisibilityOff() hood4 = vtk.vtkActor() hood4.SetMapper(mapHood4) hood4.GetProperty().SetColor(colors.GetColor3d('Furniture')) hood6Geom = vtk.vtkStructuredGridGeometryFilter() hood6Geom.SetInputConnection(reader.GetOutputPort()) hood6Geom.SetExtent(17, 19, 0, 11, 16, 16) mapHood6 = vtk.vtkPolyDataMapper() mapHood6.SetInputConnection(hood6Geom.GetOutputPort()) mapHood6.ScalarVisibilityOff() hood6 = vtk.vtkActor() hood6.SetMapper(mapHood6) hood6.GetProperty().SetColor(colors.GetColor3d('Furniture')) cookingPlateGeom = vtk.vtkStructuredGridGeometryFilter() cookingPlateGeom.SetInputConnection(reader.GetOutputPort()) cookingPlateGeom.SetExtent(17, 19, 7, 9, 6, 6) mapCookingPlate = vtk.vtkPolyDataMapper() mapCookingPlate.SetInputConnection(cookingPlateGeom.GetOutputPort()) mapCookingPlate.ScalarVisibilityOff() cookingPlate = vtk.vtkActor() cookingPlate.SetMapper(mapCookingPlate) cookingPlate.GetProperty().SetColor(colors.GetColor3d('Tomato')) filterGeom = vtk.vtkStructuredGridGeometryFilter() filterGeom.SetInputConnection(reader.GetOutputPort()) filterGeom.SetExtent(17, 19, 7, 9, 11, 11) mapFilter = vtk.vtkPolyDataMapper() mapFilter.SetInputConnection(filterGeom.GetOutputPort()) mapFilter.ScalarVisibilityOff() sgfilter = vtk.vtkActor() sgfilter.SetMapper(mapFilter) sgfilter.GetProperty().SetColor(colors.GetColor3d('Furniture')) # # regular streamlines # line = vtk.vtkLineSource() line.SetResolution(39) line.SetPoint1(0.08, 2.50, 0.71) line.SetPoint2(0.08, 4.50, 0.71) rakeMapper = vtk.vtkPolyDataMapper() rakeMapper.SetInputConnection(line.GetOutputPort()) rake = vtk.vtkActor() rake.SetMapper(rakeMapper) streamers = vtk.vtkStreamTracer() # streamers.DebugOn() streamers.SetInputConnection(reader.GetOutputPort()) streamers.SetSourceConnection(line.GetOutputPort()) streamers.SetMaximumPropagation(maxTime) streamers.SetInitialIntegrationStep(.5) streamers.SetMinimumIntegrationStep(.1) streamers.SetIntegratorType(2) streamers.Update() streamersMapper = vtk.vtkPolyDataMapper() streamersMapper.SetInputConnection(streamers.GetOutputPort()) streamersMapper.SetScalarRange(scalarRange) lines = vtk.vtkActor() lines.SetMapper(streamersMapper) lines.GetProperty().SetColor(colors.GetColor3d('Black')) aren.TwoSidedLightingOn() aren.AddActor(outline) aren.AddActor(door) aren.AddActor(window1) aren.AddActor(window2) aren.AddActor(klower1) aren.AddActor(klower2) aren.AddActor(klower3) aren.AddActor(klower4) aren.AddActor(klower5) aren.AddActor(klower6) aren.AddActor(klower7) aren.AddActor(hood1) aren.AddActor(hood2) aren.AddActor(hood3) aren.AddActor(hood4) aren.AddActor(hood6) aren.AddActor(cookingPlate) aren.AddActor(sgfilter) aren.AddActor(lines) aren.AddActor(rake) aren.SetBackground(colors.GetColor3d('SlateGray')) aCamera = vtk.vtkCamera() aren.SetActiveCamera(aCamera) aren.ResetCamera() aCamera.SetFocalPoint(3.505, 2.505, 1.255) aCamera.SetPosition(3.505, 24.6196, 1.255) aCamera.SetViewUp(0, 0, 1) aCamera.Azimuth(60) aCamera.Elevation(30) aCamera.Dolly(1.4) aren.ResetCameraClippingRange() renWin.SetSize(640, 512) renWin.Render() renWin.SetWindowName('Kitchen') # interact with data iren.Start()
def __init__(self, context): super(FakeMotionRendererPlugin, self).__init__(context) self.setObjectName('FakeMotionRendererPlugin') self._widget = QWidget() if context.serial_number() > 1: self._widget.setWindowTitle( self._widget.windowTitle() + (' (%d)' % context.serial_number())) ui_file = os.path.join(rospkg.RosPack().get_path('motion_renderer'), 'resource', 'fake_motion_renderer.ui') loadUi(ui_file, self._widget) self._widget.resizeEvent = self.widget_resized context.add_widget(self._widget) self.frame = QFrame() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self._widget.verticalLayout.addWidget(self.vtkWidget) self._widget.update() self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() self.vtkWidget.GetRenderWindow().SetLineSmoothing(2) self.vtkWidget.GetRenderWindow().SetPointSmoothing(2) # self.vtkWidget.GetRenderWindow().SetPolygonSmoothing(2) self.vtkWidget.GetRenderWindow().AlphaBitPlanesOn() self.vtkWidget.GetRenderWindow().SetMultiSamples(32) self.eye_ball = [] self.eye_ball.append(self.add_eye_ball(pose=[-0.8, 0.0, 0.0], orientation=[90, 0, 0])) self.eye_ball.append(self.add_eye_ball(pose=[0.8, 0.0, 0.0], orientation=[90, 0, 0])) self.eye_lid = [] self.eye_lid.append(self.add_eye_lid(pose=[-0.8, 0.0, 0.0], orientation=[90, 0, 0])) self.eye_lid.append(self.add_eye_lid(pose=[0.8, 0.0, 0.0], orientation=[90, 0, 0])) self.eye_brow = [] self.eye_brow.append(self.add_eye_brow(pose=[-0.8, 0.55, 0.4], orientation=[0, 0, 0])) self.eye_brow.append(self.add_eye_brow(pose=[0.8, 0.55, 0.4], orientation=[0, 0, 0])) # Initial Pose and Rotation for Eyeball self.eye_ball[0].RotateZ(-2.0) self.eye_ball[1].RotateZ(2.0) self.eye_lid[0][0].RotateX(-30) self.eye_lid[0][1].RotateX(30) self.eye_lid[1][0].RotateX(-30) self.eye_lid[1][1].RotateX(30) self.subtitle = vtk.vtkTextActor() self.subtitle.SetInput('대화가 나타남.') self.subtitle.GetTextProperty().SetFontFamily(vtk.VTK_FONT_FILE) self.subtitle.GetTextProperty().SetFontFile('/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf') self.subtitle.GetTextProperty().SetColor(1, 1, 1) self.subtitle.GetTextProperty().SetJustificationToCentered() self.subtitle.GetTextProperty().SetBackgroundColor(0.5, 0.2, 1) self.subtitle.GetTextProperty().ShadowOn() self.subtitle.GetTextProperty().SetFontSize(26) self.subtitle.GetProperty().SetOpacity(0.5) self.ren.AddActor2D(self.subtitle) self.ren.SetBackground(0.1, 0.2, 0.3) camera = vtk.vtkCamera(); camera.SetPosition(0, 0, 5); camera.SetFocalPoint(0, 0, 0); self.iren.RemoveAllObservers() self.ren.SetActiveCamera(camera); self.iren.Initialize() self.iren.Start()
def __init__(self, parent=None): super(VTKBackPlot, self).__init__(parent) self.canon_class = VTKCanon # properties self._background_color = QColor(0, 0, 0) self._background_color2 = QColor(0, 0, 0) self._enableProgramTicks = True # Todo: get active part self.g5x_offset = [0.0] * 9 self.g92_offset = [0.0] * 9 self.rotation_offset = 0.0 self.original_g5x_offset = [0.0] * 9 self.original_g92_offset = [0.0] * 9 self.original_rotation_offset = 0.0 self.spindle_position = (0.0, 0.0, 0.0) self.tooltip_position = (0.0, 0.0, 0.0) self.parent = parent self.status = STATUS self.stat = STATUS.stat self.units = MACHINE_UNITS self.axis = self.stat.axis self.nav_style = vtk.vtkInteractorStyleTrackballCamera() self.camera = vtk.vtkCamera() self.camera.ParallelProjectionOn() self.renderer = vtk.vtkRenderer() self.renderer.SetActiveCamera(self.camera) self.GetRenderWindow().AddRenderer(self.renderer) self.SetInteractorStyle(self.nav_style) self.interactor = self.GetRenderWindow().GetInteractor() self.machine = Machine(self.axis) self.machine_actor = self.machine.get_actor() self.machine_actor.SetCamera(self.renderer.GetActiveCamera()) self.axes = Axes() self.axes_actor = self.axes.get_actor() self.path_cache = PathCache(self.tooltip_position) self.path_cache_actor = self.path_cache.get_actor() self.tool = Tool(self.stat.tool_table[0], self.stat.tool_offset) self.tool_actor = self.tool.get_actor() if not IN_DESIGNER: self.canon = self.canon_class() self.path_actor = self.canon.get_actor() self.extents = PathBoundaries(self.renderer, self.path_actor) self.extents_actor = self.extents.get_actor() self.renderer.AddActor(self.tool_actor) self.renderer.AddActor(self.machine_actor) self.renderer.AddActor(self.axes_actor) self.renderer.AddActor(self.path_cache_actor) self.renderer.ResetCamera() self.interactor.Initialize() self.interactor.Start() self.status.file.notify(self.load_program) self.status.position.notify(self.update_position) self.status.g5x_offset.notify(self.update_g5x_offset) self.status.g92_offset.notify(self.update_g92_offset) self.status.rotation_xy.notify(self.update_rotation_xy) self.status.tool_offset.notify(self.update_tool) self.status.tool_table.notify(self.update_tool) self.line = None self._last_filename = str()
def setvtkWidget(self): self.ren = vtk.vtkRenderer() self.m_widget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.m_widget.GetRenderWindow().GetInteractor() # The car model (includes a plate, two poles and four wheel) # Plate of the car # Create source plate = vtk.vtkCubeSource() plate.SetXLength(100) plate.SetYLength(60) plate.SetZLength(6) plate.SetCenter(50, 0, -3) # Create a mapper plateMapper = vtk.vtkPolyDataMapper() plateMapper.SetInputConnection(plate.GetOutputPort()) # Create a transform plateTransform = vtk.vtkTransform() # Create an actor self.plateActor = vtk.vtkActor() self.plateActor.SetMapper(plateMapper) self.plateActor.SetUserTransform(plateTransform) self.plateActor.GetProperty().SetColor(0.69, 0.77, 0.87) self.ren.AddActor(self.plateActor) # Two poles # Left pole # Create source poleL = vtk.vtkCylinderSource() poleL.SetRadius(1.0) poleL.SetHeight(50.0) poleL.SetCenter(10, 0, 0) poleL.SetResolution(100.0) # Create a mapper poleLMapper = vtk.vtkPolyDataMapper() poleLMapper.SetInputConnection(poleL.GetOutputPort()) # Create a transform poleLTransform = vtk.vtkTransform() poleLTransform.SetInput(plateTransform) # Create an actor poleLActor = vtk.vtkActor() poleLActor.SetMapper(poleLMapper) poleLActor.SetUserTransform(poleLTransform) poleLTransform.RotateX(90.0) poleLTransform.Translate(0.0, 25.0, 0.0) self.ren.AddActor(poleLActor) # Right pole # Create source poleR = vtk.vtkCylinderSource() poleR.SetRadius(1.0) poleR.SetHeight(50.0) poleR.SetCenter(90, 0, 0) poleR.SetResolution(100.0) # Create a mapper poleRMapper = vtk.vtkPolyDataMapper() poleRMapper.SetInputConnection(poleR.GetOutputPort()) # Create a transform poleRTransform = vtk.vtkTransform() poleRTransform.SetInput(plateTransform) # Create an actor poleRActor = vtk.vtkActor() poleRActor.SetMapper(poleRMapper) poleRActor.SetUserTransform(poleRTransform) poleRTransform.RotateX(90.0) poleRTransform.Translate(0.0, 25.0, 0.0) self.ren.AddActor(poleRActor) # 4 car's wheels wheel = [] wheelMapper = [] wheelTransform = [] wheelActor = [] for i in range(4): # Create source wheel.append(vtk.vtkCylinderSource()) wheel[i].SetRadius(6.0) wheel[i].SetHeight(3.0) wheel[i].SetResolution(100.0) # Create a mapper wheelMapper.append(vtk.vtkPolyDataMapper()) wheelMapper[i].SetInputConnection(wheel[i].GetOutputPort()) # Create a transform wheelTransform.append(vtk.vtkTransform()) wheelTransform[i].SetInput(plateTransform) # Create an actor wheelActor.append(vtk.vtkActor()) wheelActor[i].SetMapper(wheelMapper[i]) wheelActor[i].SetUserTransform(wheelTransform[i]) wheelActor[i].GetProperty().SetColor(1.0, 1.0, 0.6) self.ren.AddActor(wheelActor[i]) wheel[0].SetCenter(10, 25, -9.0) wheel[1].SetCenter(90, 25, -9.0) wheel[2].SetCenter(10, -25, -9.0) wheel[3].SetCenter(90, -25, -9.0) # Two spheres' model # Left sphere # Create source sphereL = vtk.vtkSphereSource() sphereL.SetRadius(5) sphereL.SetCenter(0, 0, 30) # Create a mapper sphereLMapper = vtk.vtkPolyDataMapper() sphereLMapper.SetInputConnection(sphereL.GetOutputPort()) # Create an actor sphereLActor = vtk.vtkActor() sphereLActor.SetMapper(sphereLMapper) sphereLActor.GetProperty().SetColor(1.0, 0.2, 0.2) self.ren.AddActor(sphereLActor) # Right sphere # Create source sphereR = vtk.vtkSphereSource() sphereR.SetRadius(5) sphereR.SetCenter(100, 0, 30) # Create a mapper sphereRMapper = vtk.vtkPolyDataMapper() sphereRMapper.SetInputConnection(sphereR.GetOutputPort()) # Create an actor sphereRActor = vtk.vtkActor() sphereRActor.SetMapper(sphereRMapper) sphereRActor.GetProperty().SetColor(0.0, 0.5, 1.0) self.ren.AddActor(sphereRActor) # Create a camera #self.ren.ResetCamera() camera = vtk.vtkCamera() self.ren.SetActiveCamera(camera) self.ren.GetActiveCamera().SetPosition(50, -300, 100) self.ren.GetActiveCamera().SetFocalPoint(50, 0, 0) self.ren.GetActiveCamera().SetViewUp(0, 0, 1) self.ren.GetActiveCamera().UpdateViewport(self.ren)
def main(): fileName = get_program_parameters() colors = vtk.vtkNamedColors() ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Create the pipeline. # reader = vtk.vtkStructuredPointsReader() reader.SetFileName(fileName) psource = vtk.vtkPointSource() psource.SetNumberOfPoints(25) psource.SetCenter(133.1, 116.3, 5.0) psource.SetRadius(2.0) threshold = vtk.vtkThresholdPoints() threshold.SetInputConnection(reader.GetOutputPort()) threshold.ThresholdByUpper(275) streamers = vtk.vtkStreamTracer() streamers.SetInputConnection(reader.GetOutputPort()) streamers.SetSourceConnection(psource.GetOutputPort()) # streamers.SetMaximumPropagationUnitToTimeUnit() streamers.SetMaximumPropagation(100.0) # streamers.SetInitialIntegrationStepUnitToCellLengthUnit() streamers.SetInitialIntegrationStep(0.2) streamers.SetTerminalSpeed(.01) streamers.Update() scalarRange = [0] * 2 scalarRange[0] = streamers.GetOutput().GetPointData().GetScalars( ).GetRange()[0] scalarRange[1] = streamers.GetOutput().GetPointData().GetScalars( ).GetRange()[1] print("range: ", scalarRange[0], ", ", scalarRange[1]) tubes = vtk.vtkTubeFilter() tubes.SetInputConnection(streamers.GetOutputPort()) tubes.SetRadius(0.3) tubes.SetNumberOfSides(6) tubes.SetVaryRadius(0) lut = vtk.vtkLookupTable() lut.SetHueRange(.667, 0.0) lut.Build() streamerMapper = vtk.vtkPolyDataMapper() streamerMapper.SetInputConnection(tubes.GetOutputPort()) streamerMapper.SetScalarRange(scalarRange[0], scalarRange[1]) streamerMapper.SetLookupTable(lut) streamerActor = vtk.vtkActor() streamerActor.SetMapper(streamerMapper) # Speed contours. iso = vtk.vtkContourFilter() iso.SetInputConnection(reader.GetOutputPort()) iso.SetValue(0, 175) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(iso.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetRepresentationToWireframe() isoActor.GetProperty().SetOpacity(0.25) # Outline outline = vtk.vtkOutlineFilter() outline.SetInputConnection(reader.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(colors.GetColor3d("Black")) # Add the actors to the renderer, set the background and size. # ren1.AddActor(outlineActor) ren1.AddActor(streamerActor) ren1.AddActor(isoActor) ren1.SetBackground(colors.GetColor3d("Wheat")) renWin.SetSize(640, 480) renWin.SetWindowName('CarotidFlow') cam1 = vtk.vtkCamera() cam1.SetClippingRange(17.4043, 870.216) cam1.SetFocalPoint(136.71, 104.025, 23) cam1.SetPosition(204.747, 258.939, 63.7925) cam1.SetViewUp(-0.102647, -0.210897, 0.972104) cam1.Zoom(1.2) ren1.SetActiveCamera(cam1) # Render the image. # renWin.Render() iren.Start()
def __init__(self, settings, console=None, backgroundColour = (0.329412, 0.34902, 0.427451)): # Call base class initializer. super(renderView, self).__init__() # Internalise objects. self.settings = settings self.console = console # Create the widget. # Create layout box. self.box = QtGui.QVBoxLayout() # Create vtk widget and pass main frame. self.vtkWidget = QVTKRenderWindowInteractor(self) # Pack vtk widget in box. self.box.addWidget(self.vtkWidget) # Get render window. self.renderWindow = self.vtkWidget.GetRenderWindow() # Create renderer. self.renderer = vtk.vtkRenderer() self.renderWindow.AddRenderer(self.renderer) # Create other elements. # Create camera and set view options.. self.camera =vtk.vtkCamera(); self.camera.SetViewUp(0,0,1) self.camera.SetPosition(self.settings['buildSizeX'].value/2+200, self.settings['buildSizeY'].value/2-300,300); self.camera.SetFocalPoint(self.settings['buildSizeX'].value/2, self.settings['buildSizeY'].value/2, self.settings['buildSizeZ'].value/2); self.camera.SetClippingRange(0.0001, 10000) self.renderer.SetActiveCamera(self.camera); # Background color. self.renderer.SetBackground( backgroundColour ) # Get interactor. self.renderWindowInteractor = self.renderWindow.GetInteractor() self.renderWindowInteractor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) # This is set as default. # Pack the frame into the widget. self.setLayout(self.box) # Create options box. self.boxOptions = QtGui.QHBoxLayout() self.box.addLayout(self.boxOptions) # Make reset button. self.buttonReset = monkeyprintGuiHelper.button("Reset view", self.callbackResetButton)#gtk.Button(label="Reset view") self.boxOptions.addWidget(self.buttonReset) # Make axes view toggle. self.buttonAxes = monkeyprintGuiHelper.checkbox("Show axes", self.callbackCheckButtonAxes, True)#gtk.Button(label="Reset view") self.boxOptions.addWidget(self.buttonAxes) self.boxOptions.addStretch(1) # Add text and axes info. self.createAnnotations() # Make build volume box. self.buildVolume = monkeyprintModelHandling.buildVolume([self.settings['buildSizeX'].value, self.settings['buildSizeY'].value, self.settings['buildSizeZ'].value]) self.addActor(self.buildVolume.getActor()) #self.buttonReset.connect("clicked", self.callbackResetButton) #self.optionsBox.pack_start(self.buttonReset, expand=False, fill=False) #self.buttonReset.show() '''
def __init__(self): super(MainWindow, self).__init__() self.title = 'OpenFoil' self.ui = uic.loadUi("mainwindow.ui", self) # create a VTK render window within the ui.vtkFrame object self.vtkWidget = QVTKRenderWindowInteractor(self.ui.flowFrame) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) # self.vtkWidget.setGeometry(0,0,600,400) # geo = self.ui.flowFrame.geometry() # self.vtkWidget.setGeometry(geo) # TODO: the widget should scale filling the available space self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) # Define custom interaction. self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # this way the mouse doesn't move anything # self.iren.SetInteractorStyle(None) self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) # this way we just disable the left mouse button self.iren.RemoveObservers('LeftButtonPressEvent') # self.iren.AddObserver('LeftButtonPressEvent', DummyFunc1, 1.0) # self.iren.AddObserver('LeftButtonPressEvent', DummyFunc2, -1.0) # TODO: we want to assign exactly the function of the middle # mouse button (pan) to the left mouse button # read mesh data ff = FoamFile('run/alfa200/constant/polyMesh/points') point_data = ff.readPoints() print(len(point_data)) print(point_data) ff = FoamFile('run/alfa200/constant/polyMesh/faces') face_data = ff.readFaces() print(len(face_data)) print(face_data) # Create a wire frame from the mesh data vtkPoints = vtk.vtkPoints() vtkPoints.SetNumberOfPoints(len(point_data)) # we switch coordinates y and z # the airfoils then lies in the x-y plane for i,p in enumerate(point_data): vtkPoints.SetPoint(i,p[0], p[2], p[1]) lines = vtk.vtkCellArray() for i,face in enumerate(face_data): lines.InsertNextCell(5) for ind in face: lines.InsertCellPoint(ind) lines.InsertCellPoint(face[0]) mesh = vtk.vtkPolyData() mesh.SetPoints(vtkPoints) mesh.SetLines(lines) # Create a mapper mapper = vtk.vtkPolyDataMapper() # mapper.SetInputConnection(source.GetOutputPort()) mapper.SetInputData(mesh) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) camera = vtk.vtkCamera (); camera.SetPosition(0, 0, 20); camera.SetFocalPoint(0, 0, 0); self.ren.AddActor(actor) # self.ren.ResetCamera(); self.ren.SetActiveCamera(camera); self.show() self.iren.Initialize()
def __init__(self, settings, console=None, backgroundColour = (0.329412, 0.34902, 0.427451)): # Call base class initializer. gtk.VBox.__init__(self) # Internalise objects. self.settings = settings self.console = console # Create renderer. self.renderer = vtk.vtkRenderer() self.renderer.SetBackground( backgroundColour ) # Create camera and set view options.. self.camera =vtk.vtkCamera(); self.camera.SetViewUp(0,0,1) self.camera.SetPosition(self.settings['buildSizeX'].value/2+200, self.settings['buildSizeY'].value/2-300,300); self.camera.SetFocalPoint(self.settings['buildSizeX'].value/2, self.settings['buildSizeY'].value/2, self.settings['buildSizeZ'].value/2); self.camera.SetClippingRange(0.0001, 10000) self.renderer.SetActiveCamera(self.camera); # Create render window. self.renderWindow = vtk.vtkRenderWindow() self.renderWindow.AddRenderer(self.renderer) # Create the render window interactor. self.renderWindowInteractor = gtkGLExtVTKRenderWindowInteractor.GtkGLExtVTKRenderWindowInteractor(self) # Pack it into the box. self.pack_start(self.renderWindowInteractor, expand=True, fill=True) # Set some options. # renderWindowInteractor.SetDesiredUpdateRate(1000) # self.renderWindowInteractor.set_size_request(400, 400) # prevents 'q' from exiting the app. self.renderWindowInteractor.AddObserver("ExitEvent", lambda o,e,x=None: x) # self.renderWindowInteractor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) # This is set as default. # Initialise render interactor. self.renderWindowInteractor.show() self.renderWindowInteractor.Initialize() self.renderWindowInteractor.Start() self.renderWindowInteractor.GetRenderWindow().AddRenderer(self.renderer) # self.renderWindowInteractor.SetRenderWindow(self.renderWindow) # Add text and axes info. self.createAnnotations() # Create an options panel. self.optionsBox = gtk.HBox() self.pack_start(self.optionsBox, expand=False, fill=False) self.optionsBox.show() # Make reset button. self.buttonReset = gtk.Button(label="Reset view") self.buttonReset.connect("clicked", self.callbackResetButton) self.optionsBox.pack_start(self.buttonReset, expand=False, fill=False) self.buttonReset.show() # Make colour checkbox. self.checkButtonColour = gtk.CheckButton(label="Show colours (coming soon)") self.checkButtonColour.connect("toggled", self.callbackCheckButtonColour) self.optionsBox.pack_start(self.checkButtonColour) self.checkButtonColour.show() # Make axes checkbox. self.checkButtonAxes = gtk.CheckButton(label="Show axes") self.checkButtonAxes.connect("toggled", self.callbackCheckButtonAxes) self.optionsBox.pack_start(self.checkButtonAxes) self.checkButtonAxes.set_active(True) self.checkButtonAxes.show() # Make build volume box. self.buildVolume = monkeyprintModelHandling.buildVolume([self.settings['buildSizeX'].value, self.settings['buildSizeY'].value, self.settings['buildSizeZ'].value]) self.addActor(self.buildVolume.getActor())
def hanoi(): colors = vtk.vtkNamedColors() # Create the renderer and render window interactor. ren = vtk.vtkRenderer() renWin.AddRenderer(ren) renWin.SetSize(1200, 750) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren.SetBackground(colors.GetColor3d("PapayaWhip")) camera = vtk.vtkCamera() camera.SetPosition(41.0433, 27.9637, 30.442) camera.SetFocalPoint(11.5603, -1.51931, 0.95899) camera.SetClippingRange(18.9599, 91.6042) camera.SetViewUp(0, 1, 0) ren.SetActiveCamera(camera) # Create geometry: table, pegs, and pucks. pegGeometry = vtk.vtkCylinderSource() pegGeometry.SetResolution(8) pegMapper = vtk.vtkPolyDataMapper() pegMapper.SetInputConnection(pegGeometry.GetOutputPort()) puckGeometry = vtk.vtkCylinderSource() puckGeometry.SetResolution(gv.puckResolution) puckMapper = vtk.vtkPolyDataMapper() puckMapper.SetInputConnection(puckGeometry.GetOutputPort()) tableGeometry = vtk.vtkPlaneSource() tableGeometry.SetResolution(10, 10) tableMapper = vtk.vtkPolyDataMapper() tableMapper.SetInputConnection(tableGeometry.GetOutputPort()) # Create the actors: table top, pegs, and pucks # The table table = vtk.vtkActor() ren.AddActor(table) table.SetMapper(tableMapper) # table.GetProperty().SetColor(0.9569, 0.6431, 0.3765) table.GetProperty().SetColor(colors.GetColor3d("SaddleBrown")) table.AddPosition(gv.D, 0, 0) table.SetScale(4 * gv.D, 2 * gv.D, 3 * gv.D) table.RotateX(90) # The pegs (using cylinder geometry). Note that the pegs have to translated # in the y-direction because the cylinder is centered about the origin. gv.H = 1.1 * gv.numberOfPucks * gv.L peg = list() for i in range(0, 3): peg.append(vtk.vtkActor()) ren.AddActor(peg[i]) peg[i].SetMapper(pegMapper) # peg[i].GetProperty().SetColor(1, 1, 1) peg[i].GetProperty().SetColor(colors.GetColor3d("Lavender")) peg[i].AddPosition(i * gv.D, gv.H / 2, 0) peg[i].SetScale(1, gv.H, 1) # The pucks (using cylinder geometry). Always loaded on peg# 0. puck = list() randomSequence = vtk.vtkMinimalStandardRandomSequence() randomSequence.SetSeed(1) for i in range(0, gv.numberOfPucks): puck.append(vtk.vtkActor()) puck[i].SetMapper(puckMapper) color = [0, 0, 0] for j in range(0, 3): color[j] = randomSequence.GetValue() randomSequence.Next() puck[i].GetProperty().SetColor(*color) puck[i].AddPosition(0, i * gv.L + gv.L / 2, 0) scale = gv.rMax - i * (gv.rMax - gv.rMin) / (gv.numberOfPucks - 1) puck[i].SetScale(scale, 1, scale) ren.AddActor(puck[i]) pegStack[0].append(puck[i]) # Reset the camera to view all actors. renWin.Render() renWin.SetWindowName("Towers of Hanoi") if gv.configuration == 3: WriteImage("hanoi0.png", renWin, rgba=False) if gv.configuration != 1: # Begin recursion. Hanoi(gv.numberOfPucks - 1, 0, 2, 1) Hanoi(1, 0, 1, 2) if not gv.gotFigure2: Hanoi(gv.numberOfPucks - 1, 2, 1, 0) renWin.Render() if gv.configuration == 3: WriteImage("hanoi2.png", renWin, rgba=False) # Report output. s = 'Number of moves: {:d}\nPolygons rendered each frame: {:d}\nTotal number of frames: {:d}' print( s.format(gv.numberOfMoves, 3 * 8 + 1 + gv.numberOfPucks * (2 + gv.puckResolution), gv.numberOfMoves * 3 * gv.numberOfSteps)) iren.AddObserver('EndInteractionEvent', OrientationObserver(ren.GetActiveCamera())) # Render the image. iren.Initialize() iren.Start()
def render_actors_360(actors, directory, nframes, camera_start=None, start_frame=0, video_width=1280, video_height=720, scale=4, do_save=True, back_color=(1, 1, 1)): """ Function to create a series of png frames which rotates around the Azimuth angle of a starting camera This will save images as a series of png images in the directory specified. The movie will start at time 0 and will go to frame nframes, completing a 360 degree rotation in that many frames. Keep in mind that typical movies are encoded at 15-30 frames per second and nframes is units of frames. Parameters ---------- actors : list of vtkActor's list of vtkActors to render directory : str folder to save images into nframes : int number of frames to render camera_start : vtk.Camera camera to start rotation, default=None will fit actors in scene start_frame : int number to save the first frame number as... (default 0) i.e. frames will start_frame = 5, first file would be 005.png video_width : int size of video in pixels video_height : int size of the video in pixels scale : int how much to expand the image do_save : bool whether to save the images to disk or just play interactively back_color : iterable a len(3) iterable with the background color [0,1]rgb Returns ------- vtkRenderer the renderer used to render endframe the last frame written Example ------- :: from meshparty import trimesh_io, trimesh_vtk mm = trimesh_io.MeshMeta(disk_cache_path = 'meshes') mesh = mm.mesh(filename='mymesh.obj') mesh_actor = trimesh_vtk.mesh_actor(mesh) mesh_center = np.mean(mesh.vertices, axis=0) camera_start = trimesh_vtk.oriented_camera(mesh_center) render_actors_360([mesh_actor], 'movie', 360, camera_start=camera_start) """ print('starting') if camera_start is None: frame_0_file = os.path.join(directory, "0000.png") ren = render_actors(actors, do_save=True, filename=frame_0_file, video_width=video_width, video_height=video_height, back_color=back_color) print('done rendering') camera_start = ren.GetActiveCamera() print('camera_start done') cameras = [] times = [] for k, angle in enumerate(np.linspace(0, 360, nframes)): angle_cam = vtk.vtkCamera() angle_cam.ShallowCopy(camera_start) angle_cam.SetParallelProjection(camera_start.GetParallelProjection()) angle_cam.SetParallelScale(camera_start.GetParallelScale()) angle_cam.Azimuth(angle) cameras.append(angle_cam) times.append(k) print('cameras ready') return render_movie(actors, directory, times=times, cameras=cameras, video_height=video_height, video_width=video_width, scale=scale, do_save=do_save, start_frame=start_frame, back_color=back_color)
def main(): colors = vtk.vtkNamedColors() # x = array of 8 3-tuples of float representing the vertices of a cube: x = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0)] # pts = array of 6 4-tuples of vtkIdType (int) representing the faces # of the cube in terms of the above vertices pts = [(0, 1, 2, 3), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] # We'll create the building blocks of polydata including data attributes. cube = vtk.vtkPolyData() points = vtk.vtkPoints() polys = vtk.vtkCellArray() scalars = vtk.vtkFloatArray() # Load the point, cell, and data attributes. for i, xi in enumerate(x): points.InsertPoint(i, xi) for pt in pts: polys.InsertNextCell(mkVtkIdList(pt)) for i, _ in enumerate(x): scalars.InsertTuple1(i, i) # We now assign the pieces to the vtkPolyData. cube.SetPoints(points) cube.SetPolys(polys) cube.GetPointData().SetScalars(scalars) # Now we'll look at it. cubeMapper = vtk.vtkPolyDataMapper() cubeMapper.SetInputData(cube) cubeMapper.SetScalarRange(cube.GetScalarRange()) cubeActor = vtk.vtkActor() cubeActor.SetMapper(cubeMapper) # The usual rendering stuff. camera = vtk.vtkCamera() camera.SetPosition(1, 1, 1) camera.SetFocalPoint(0, 0, 0) renderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renderer.AddActor(cubeActor) renderer.SetActiveCamera(camera) renderer.ResetCamera() renderer.SetBackground(colors.GetColor3d("Cornsilk")) renWin.SetSize(600, 600) renWin.SetWindowName("Cube") # interact with data renWin.Render() iren.Start()
def render_movie_flexible(actors, directory, times, frame_change_function, start_frame=0, video_width=1280, video_height=720, scale=4, camera=None, do_save=True, back_color=(1, 1, 1)): """ Function to create a series of png frames based upon a defining a frame change function that will alter actors and camera at each time point This will save images as a series of png images in the directory specified. The movie will start at time 0 and will go to frame np.max(times) Reccomend to make times start at 0 and the length of the movie you want. Keep in mind that typical movies are encoded at 15-30 frames per second and times is units of frames. This is the most general of the movie making functions, and can be used to custom change coloring of actors or their positions over time using tranformations. Parameters ---------- actors : list of vtkActor's list of vtkActors to render directory : str folder to save images into times : np.array array of K frame times to set the camera to frame_change_function : func a function that takes (actors, camera, t) as arguments. where actors are the list of actors passed here, camera is the camera for the rendering, and t is the current frame number. This function may alter the actors and camera as a function of time in some user defined manner. start_frame : int number to save the first frame number as... (default 0) i.e. frames will start_frame = 5, first file would be 005.png video_width : int size of video in pixels video_height : int size of the video in pixels scale : int how much to expand the image do_save : bool whether to save the images to disk or just play interactively Returns ------- vtkRenderer the renderer used to render endframe the last frame written Example ------- :: from meshparty import trimesh_io, trimesh_vtk mm = trimesh_io.MeshMeta(disk_cache_path = 'meshes') mesh = mm.mesh(filename='mymesh.obj') mesh_actor = trimesh_vtk.mesh_actor(mesh) mesh_center = np.mean(mesh.vertices, axis=0) camera_start = trimesh_vtk.oriented_camera(mesh_center, backoff = 10000, backoff_vector=(0, 0, 1)) camera_180 = trimesh_vtk.oriented_camera(mesh_center, backoff = 10000, backoff_vector=(0, 0, -1)) times = np.array([0, 90, 180]) cameras = [camera_start, camera_180, camera_start] render_movie([mesh_actor], 'movie', times, cameras) """ if not os.path.isdir(directory): os.makedirs(directory) if camera is None: camera = vtk.vtkCamera() # create a rendering window and renderer ren, renWin, iren = _setup_renderer(video_width, video_height, back_color, camera=camera) for a in actors: # assign actor to the renderer ren.AddActor(a) imageFilter = vtk.vtkWindowToImageFilter() imageFilter.SetInput(renWin) imageFilter.SetScale(scale) imageFilter.SetInputBufferTypeToRGB() imageFilter.ReadFrontBufferOff() imageFilter.Update() # Setup movie writer if do_save: moviewriter = vtk.vtkPNGWriter() moviewriter.SetInputConnection(imageFilter.GetOutputPort()) renWin.OffScreenRenderingOn() for i in np.arange(0, np.max(times) + 1): frame_change_function(actors, camera, i) ren.ResetCameraClippingRange() camera.ViewingRaysModified() renWin.Render() if do_save: filename = os.path.join(directory, "%04d.png" % (i + start_frame)) moviewriter.SetFileName(filename) # Export a current frame imageFilter.Update() imageFilter.Modified() moviewriter.Write() renWin.Finalize() return renWin, i + start_frame
def main(): # x = array of 8 3-tuples of float representing the vertices of a cube: x = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0 ,1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0)] # pts = array of 6 4-tuples of vtkIdType (int) representing the faces # of the cube in terms of the above vertices pts = [(0,1,2,3), (4,5,6,7), (0,1,5,4), (1,2,6,5), (2,3,7,6), (3,0,4,7)] # We'll create the building blocks of polydata including data attributes. cube = vtk.vtkPolyData() points = vtk.vtkPoints() polys = vtk.vtkCellArray() scalars = vtk.vtkFloatArray() # Load the point, cell, and data attributes. for i in range(8): points.InsertPoint(i, x[i]) for i in range(6): polys.InsertNextCell( mkVtkIdList(pts[i]) ) for i in range(8): scalars.InsertTuple1(i,i) # We now assign the pieces to the vtkPolyData. cube.SetPoints(points) del points cube.SetPolys(polys) del polys cube.GetPointData().SetScalars(scalars) del scalars # Now we'll look at it. cubeMapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: cubeMapper.SetInput(cube) else: cubeMapper.SetInputData(cube) cubeMapper.SetScalarRange(0,7) cubeActor = vtk.vtkActor() cubeActor.SetMapper(cubeMapper) # The usual rendering stuff. camera = vtk.vtkCamera() camera.SetPosition(1,1,1) camera.SetFocalPoint(0,0,0) renderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renderer.AddActor(cubeActor) renderer.SetActiveCamera(camera) renderer.ResetCamera() renderer.SetBackground(1,1,1) renWin.SetSize(300,300) # interact with data renWin.Render() iren.Start() # Clean up del cube del cubeMapper del cubeActor del camera del renderer del renWin del iren
def SelectCuttingPlane(input_file): ## Get vtk format file_format = input_file.split(".")[-1] input_vtk = input_file.replace(file_format, "vtk") if file_format == "nrrd": image = Image(input_file) mesh = image.toMesh(image) mesh.write(input_vtk) print("\nCreating mesh from: " + input_file) print("\nSaving as: " + input_vtk) elif file_format == "ply" or file_format == "stl": mesh = Mesh(file_format) mesh.write(input_vtk) else: print("Error, file format unrecognized: " + input_file) ## VTK interactive window print('\n Use the interactive window to select your cutting plane. When you are content with your selection, simply close the window. \n') # read data from file reader = vtk.vtkPolyDataReader() reader.SetFileName(input_vtk) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() # get data data = reader.GetOutput() (xcenter, ycenter, zcenter) = data.GetCenter() #create mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(data) # The actor is a grouping mechanism actor = vtk.vtkActor() actor.SetMapper(mapper) # create camera camera = vtk.vtkCamera() camera.SetFocalPoint(xcenter, ycenter, zcenter) camera.SetPosition(100, -300, -50) camera.SetViewUp(0,0,1) # create a renderer renderer = vtk.vtkRenderer() renderer.SetActiveCamera(camera) renderer.SetBackground(0.2, 0.2, 0.5) renderer.SetBackground2(0.4, 0.4, 1.0) renderer.SetGradientBackground(True) renderer.AddActor(actor) # create a render_window render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetSize(1000,1000) # create a renderwindowiren iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(render_window) iren.Initialize() rep = vtk.vtkImplicitPlaneRepresentation() rep.SetPlaceFactor(1.25) rep.PlaceWidget(actor.GetBounds()) rep.SetNormal(0,0,1) # Create a vtkImagePlaneWidget and activate it plane_widget = vtk.vtkImplicitPlaneWidget2() plane_widget.SetInteractor(iren) plane_widget.SetRepresentation(rep) plane_widget.On() iren.Initialize() iren.Start() # use orgin as one point and use normla to solve for two others (o1,o2,o3) = rep.GetOrigin() (n1,n2,n3) = rep.GetNormal() # using x = 1 and y =-1 solve for z pt1_z = (-n1+(n1*o1)+n2+(n2*o2)+(n3*o3))/n3 # using x = -1 and y = 1 solve for z pt2_z = (n1+(n1*o1)-n2+(n2*o2)+(n3*o3))/n3 # fix 0 edge case if o1 == 0 and o2 == 0: o1 = -1 o2 = -1 return np.array([[o1, o2, o3], [1, -1, pt1_z], [-1, 1, pt2_z]])