[docs]classRenderer(vtk.vtkRenderer):""" Your scene class This is an important object that is responsible for preparing objects e.g. actors and volumes for rendering. This is a more pythonic version of ``vtkRenderer`` proving simple methods for adding and removing actors but also it provides access to all the functionality available in ``vtkRenderer`` if necessary. """
[docs]defbackground(self,color):""" Set a background color """self.SetBackground(color)
[docs]defadd(self,*actors):""" Add an actor to the renderer """foractorinactors:ifisinstance(actor,vtk.vtkVolume):self.AddVolume(actor)elifisinstance(actor,vtk.vtkActor2D):self.AddActor2D(actor)elifhasattr(actor,'add_to_renderer'):actor.add_to_renderer(self)else:self.AddActor(actor)
[docs]defrm(self,actor):""" Remove a specific actor """self.RemoveActor(actor)
[docs]defclear(self):""" Remove all actors from the renderer """self.RemoveAllViewProps()
[docs]defrm_all(self):""" Remove all actors from the renderer """self.RemoveAllViewProps()
[docs]defprojection(self,proj_type='perspective'):""" Deside between parallel or perspective projection Parameters ---------- proj_type : str Can be 'parallel' or 'perspective' (default). """ifproj_type=='parallel':self.GetActiveCamera().ParallelProjectionOn()else:self.GetActiveCamera().ParallelProjectionOff()
[docs]defreset_camera(self):""" Reset the camera to an automatic position given by the engine. """self.ResetCamera()
[docs]defcamera_info(self):cam=self.camera()print('# Active Camera')print(' Position (%.2f, %.2f, %.2f)'%cam.GetPosition())print(' Focal Point (%.2f, %.2f, %.2f)'%cam.GetFocalPoint())print(' View Up (%.2f, %.2f, %.2f)'%cam.GetViewUp())
[docs]defzoom(self,value):""" In perspective mode, decrease the view angle by the specified factor. In parallel mode, decrease the parallel scale by the specified factor. A value greater than 1 is a zoom-in, a value less than 1 is a zoom-out. """self.GetActiveCamera().Zoom(value)
[docs]defazimuth(self,angle):""" Rotate the camera about the view up vector centered at the focal point. Note that the view up vector is whatever was set via SetViewUp, and is not necessarily perpendicular to the direction of projection. The result is a horizontal rotation of the camera. """self.GetActiveCamera().Azimuth(angle)
[docs]defyaw(self,angle):""" Rotate the focal point about the view up vector, using the camera's position as the center of rotation. Note that the view up vector is whatever was set via SetViewUp, and is not necessarily perpendicular to the direction of projection. The result is a horizontal rotation of the scene. """self.GetActiveCamera().Yaw(angle)
[docs]defelevation(self,angle):""" Rotate the camera about the cross product of the negative of the direction of projection and the view up vector, using the focal point as the center of rotation. The result is a vertical rotation of the scene. """self.GetActiveCamera().Elevation(angle)
[docs]defpitch(self,angle):""" Rotate the focal point about the cross product of the view up vector and the direction of projection, using the camera's position as the center of rotation. The result is a vertical rotation of the camera. """self.GetActiveCamera().Pitch(angle)
[docs]defroll(self,angle):""" Rotate the camera about the direction of projection. This will spin the camera about its axis. """self.GetActiveCamera().Roll(angle)
[docs]defdolly(self,value):""" Divide the camera's distance from the focal point by the given dolly value. Use a value greater than one to dolly-in toward the focal point, and use a value less than one to dolly-out away from the focal point. """self.GetActiveCamera().Dolly(value)
[docs]defcamera_direction(self):""" Get the vector in the direction from the camera position to the focal point. This is usually the opposite of the ViewPlaneNormal, the vector perpendicular to the screen, unless the view is oblique. """returnself.GetActiveCamera().GetDirectionOfProjection()
[docs]defrenderer(background=None):""" Create a renderer. Parameters ---------- background : tuple Initial background color of renderer Returns ------- v : Renderer Examples -------- >>> from fury import window, actor >>> import numpy as np >>> r = window.Renderer() >>> lines=[np.random.rand(10,3)] >>> c=actor.line(lines, window.colors.red) >>> r.add(c) >>> #window.show(r) """deprecation_msg=("Method 'fury.window.renderer' is deprecated, instead"" use class 'fury.window.Renderer'.")warn(DeprecationWarning(deprecation_msg))ren=Renderer()ifbackgroundisnotNone:ren.SetBackground(background)returnren
# Todo: Deprecatedren=renderer
[docs]defadd(ren,a):""" Add a specific actor """ren.add(a)
[docs]defrm(ren,a):""" Remove a specific actor """ren.rm(a)
[docs]defclear(ren):""" Remove all actors from the renderer """ren.clear()
[docs]defrm_all(ren):""" Remove all actors from the renderer """ren.rm_all()
[docs]classShowManager(object):""" This class is the interface between the renderer, the window and the interactor. """
[docs]def__init__(self,ren=None,title='FURY',size=(300,300),png_magnify=1,reset_camera=True,order_transparent=False,interactor_style='custom'):""" Manages the visualization pipeline Parameters ---------- ren : Renderer() or vtkRenderer() The scene that holds all the actors. title : string A string for the window title bar. size : (int, int) ``(width, height)`` of the window. Default is (300, 300). png_magnify : int Number of times to magnify the screenshot. This can be used to save high resolution screenshots when pressing 's' inside the window. reset_camera : bool Default is True. You can change this option to False if you want to keep the camera as set before calling this function. order_transparent : bool True is useful when you want to order transparent actors according to their relative position to the camera. The default option which is False will order the actors according to the order of their addition to the Renderer(). interactor_style : str or vtkInteractorStyle If str then if 'trackball' then vtkInteractorStyleTrackballCamera() is used, if 'image' then vtkInteractorStyleImage() is used (no rotation) or if 'custom' then CustomInteractorStyle is used. Otherwise you can input your own interactor style. Attributes ---------- ren : vtkRenderer() iren : vtkRenderWindowInteractor() style : vtkInteractorStyle() window : vtkRenderWindow() Methods ------- initialize() render() start() add_window_callback() Notes ----- Default interaction keys for * 3d navigation are with left, middle and right mouse dragging * resetting the camera press 'r' * saving a screenshot press 's' * for quiting press 'q' Examples -------- >>> from fury import actor, window >>> renderer = window.Renderer() >>> renderer.add(actor.axes()) >>> showm = window.ShowManager(renderer) >>> # showm.initialize() >>> # showm.render() >>> # showm.start() """ifrenisNone:ren=Renderer()self.ren=renself.title=titleself.size=sizeself.png_magnify=png_magnifyself.reset_camera=reset_cameraself.order_transparent=order_transparentself.interactor_style=interactor_styleself.timers=[]ifself.reset_camera:self.ren.ResetCamera()self.window=vtk.vtkRenderWindow()self.window.AddRenderer(ren)ifself.title=='FURY':self.window.SetWindowName(title+' '+fury_version)else:self.window.SetWindowName(title)self.window.SetSize(size[0],size[1])ifself.order_transparent:# Use a render window with alpha bits# as default is 0 (false))self.window.SetAlphaBitPlanes(True)# Force to not pick a framebuffer with a multisample buffer# (default is 8)self.window.SetMultiSamples(0)# Choose to use depth peeling (if supported)# (default is 0 (false)):self.ren.UseDepthPeelingOn()# Set depth peeling parameters# Set the maximum number of rendering passes (default is 4)ren.SetMaximumNumberOfPeels(4)# Set the occlusion ratio (initial value is 0.0, exact image):ren.SetOcclusionRatio(0.0)ifself.interactor_style=='image':self.style=vtk.vtkInteractorStyleImage()elifself.interactor_style=='trackball':self.style=vtk.vtkInteractorStyleTrackballCamera()elifself.interactor_style=='custom':self.style=CustomInteractorStyle()else:self.style=interactor_styleself.iren=vtk.vtkRenderWindowInteractor()self.style.SetCurrentRenderer(self.ren)# Hack: below, we explicitly call the Python version of SetInteractor.self.style.SetInteractor(self.iren)self.iren.SetInteractorStyle(self.style)self.iren.SetRenderWindow(self.window)
[docs]defrecord_events(self):""" Records events during the interaction. The recording is represented as a list of VTK events that happened during the interaction. The recorded events are then returned. Returns ------- events : str Recorded events (one per line). Notes ----- Since VTK only allows recording events to a file, we use a temporary file from which we then read the events. """withInTemporaryDirectory():filename="recorded_events.log"recorder=vtk.vtkInteractorEventRecorder()recorder.SetInteractor(self.iren)recorder.SetFileName(filename)def_stop_recording_and_close(obj,evt):ifrecorder:recorder.Stop()self.iren.TerminateApp()self.iren.AddObserver("ExitEvent",_stop_recording_and_close)recorder.EnabledOn()recorder.Record()self.initialize()self.render()self.iren.Start()# Deleting this object is the unique way# to close the file.recorder=None# Retrieved recorded events.withopen(filename,'r')asf:events=f.read()returnevents
[docs]defrecord_events_to_file(self,filename="record.log"):""" Records events during the interaction. The recording is represented as a list of VTK events that happened during the interaction. The recording is going to be saved into `filename`. Parameters ---------- filename : str Name of the file that will contain the recording (.log|.log.gz). """events=self.record_events()# Compress file if needediffilename.endswith(".gz"):withgzip.open(filename,'wb')asfgz:fgz.write(asbytes(events))else:withopen(filename,'w')asf:f.write(events)
[docs]defplay_events(self,events):""" Plays recorded events of a past interaction. The VTK events that happened during the recorded interaction will be played back. Parameters ---------- events : str Recorded events (one per line). """recorder=vtk.vtkInteractorEventRecorder()recorder.SetInteractor(self.iren)recorder.SetInputString(events)recorder.ReadFromInputStringOn()self.initialize()self.render()recorder.Play()
[docs]defplay_events_from_file(self,filename):""" Plays recorded events of a past interaction. The VTK events that happened during the recorded interaction will be played back from `filename`. Parameters ---------- filename : str Name of the file containing the recorded events (.log|.log.gz). """# Uncompress file if needed.iffilename.endswith(".gz"):withgzip.open(filename,'r')asf:events=f.read()else:withopen(filename)asf:events=f.read()self.play_events(events)
[docs]defexit(self):""" Close window and terminate interactor """self.iren.GetRenderWindow().Finalize()self.iren.TerminateApp()
[docs]defshow(ren,title='FURY',size=(300,300),png_magnify=1,reset_camera=True,order_transparent=False):""" Show window with current renderer Parameters ------------ ren : Renderer() or vtkRenderer() The scene that holds all the actors. title : string A string for the window title bar. Default is FURY and current version. size : (int, int) ``(width, height)`` of the window. Default is (300, 300). png_magnify : int Number of times to magnify the screenshot. Default is 1. This can be used to save high resolution screenshots when pressing 's' inside the window. reset_camera : bool Default is True. You can change this option to False if you want to keep the camera as set before calling this function. order_transparent : bool True is useful when you want to order transparent actors according to their relative position to the camera. The default option which is False will order the actors according to the order of their addition to the Renderer(). Notes ----- Default interaction keys for * 3d navigation are with left, middle and right mouse dragging * resetting the camera press 'r' * saving a screenshot press 's' * for quiting press 'q' Examples ---------- >>> import numpy as np >>> from fury import window, actor >>> r = window.Renderer() >>> lines=[np.random.rand(10,3),np.random.rand(20,3)] >>> colors=np.array([[0.2,0.2,0.2],[0.8,0.8,0.8]]) >>> c=actor.line(lines,colors) >>> r.add(c) >>> l=actor.label(text="Hello") >>> r.add(l) >>> #window.show(r) See also --------- fury.window.record fury.window.snapshot """show_manager=ShowManager(ren,title,size,png_magnify,reset_camera,order_transparent)show_manager.initialize()show_manager.render()show_manager.start()
[docs]defrecord(ren=None,cam_pos=None,cam_focal=None,cam_view=None,out_path=None,path_numbering=False,n_frames=1,az_ang=10,magnification=1,size=(300,300),reset_camera=True,verbose=False):""" This will record a video of your scene Records a video as a series of ``.png`` files of your scene by rotating the azimuth angle az_angle in every frame. Parameters ----------- ren : vtkRenderer() object as returned from function renderer() cam_pos : None or sequence (3,), optional Camera's position. If None then default camera's position is used. cam_focal : None or sequence (3,), optional Camera's focal point. If None then default camera's focal point is used. cam_view : None or sequence (3,), optional Camera's view up direction. If None then default camera's view up vector is used. out_path : str, optional Output path for the frames. If None a default fury.png is created. path_numbering : bool When recording it changes out_path to out_path + str(frame number) n_frames : int, optional Number of frames to save, default 1 az_ang : float, optional Azimuthal angle of camera rotation. magnification : int, optional How much to magnify the saved frame. Default is 1. size : (int, int) ``(width, height)`` of the window. Default is (300, 300). reset_camera : bool If True Call ``ren.reset_camera()``. Otherwise you need to set the camera before calling this function. verbose : bool print information about the camera. Default is False. Examples --------- >>> from fury import window, actor >>> ren = window.Renderer() >>> a = actor.axes() >>> ren.add(a) >>> # uncomment below to record >>> # window.record(ren) >>> #check for new images in current directory """ifrenisNone:ren=vtk.vtkRenderer()renWin=vtk.vtkRenderWindow()renWin.AddRenderer(ren)renWin.SetSize(size[0],size[1])iren=vtk.vtkRenderWindowInteractor()iren.SetRenderWindow(renWin)# ren.GetActiveCamera().Azimuth(180)ifreset_camera:ren.ResetCamera()renderLarge=vtk.vtkRenderLargeImage()renderLarge.SetInput(ren)renderLarge.SetMagnification(magnification)renderLarge.Update()writer=vtk.vtkPNGWriter()ang=0ifcam_posisnotNone:cx,cy,cz=cam_posren.GetActiveCamera().SetPosition(cx,cy,cz)ifcam_focalisnotNone:fx,fy,fz=cam_focalren.GetActiveCamera().SetFocalPoint(fx,fy,fz)ifcam_viewisnotNone:ux,uy,uz=cam_viewren.GetActiveCamera().SetViewUp(ux,uy,uz)cam=ren.GetActiveCamera()ifverbose:print('Camera Position (%.2f, %.2f, %.2f)'%cam.GetPosition())print('Camera Focal Point (%.2f, %.2f, %.2f)'%cam.GetFocalPoint())print('Camera View Up (%.2f, %.2f, %.2f)'%cam.GetViewUp())foriinrange(n_frames):ren.GetActiveCamera().Azimuth(ang)renderLarge=vtk.vtkRenderLargeImage()renderLarge.SetInput(ren)renderLarge.SetMagnification(magnification)renderLarge.Update()writer.SetInputConnection(renderLarge.GetOutputPort())ifpath_numbering:ifout_pathisNone:filename=str(i).zfill(6)+'.png'else:filename=out_path+str(i).zfill(6)+'.png'else:ifout_pathisNone:filename='fury.png'else:filename=out_pathwriter.SetFileName(filename)writer.Write()ang=+az_ang
[docs]defsnapshot(ren,fname=None,size=(300,300),offscreen=True,order_transparent=False):""" Saves a snapshot of the renderer in a file or in memory Parameters ----------- ren : vtkRenderer as returned from function renderer() fname : str or None Save PNG file. If None return only an array without saving PNG. size : (int, int) ``(width, height)`` of the window. Default is (300, 300). offscreen : bool Default True. Go stealthmode no window should appear. order_transparent : bool Default False. Use depth peeling to sort transparent objects. Returns ------- arr : ndarray Color array of size (width, height, 3) where the last dimension holds the RGB values. """width,height=sizeifoffscreen:graphics_factory=vtk.vtkGraphicsFactory()graphics_factory.SetOffScreenOnlyMode(1)# TODO check if the line below helps in something# graphics_factory.SetUseMesaClasses(1)render_window=vtk.vtkRenderWindow()ifoffscreen:render_window.SetOffScreenRendering(1)render_window.AddRenderer(ren)render_window.SetSize(width,height)iforder_transparent:# Use a render window with alpha bits# as default is 0 (false))render_window.SetAlphaBitPlanes(True)# Force to not pick a framebuffer with a multisample buffer# (default is 8)render_window.SetMultiSamples(0)# Choose to use depth peeling (if supported)# (default is 0 (false)):ren.UseDepthPeelingOn()# Set depth peeling parameters# Set the maximum number of rendering passes (default is 4)ren.SetMaximumNumberOfPeels(4)# Set the occlusion ratio (initial value is 0.0, exact image):ren.SetOcclusionRatio(0.0)render_window.Render()window_to_image_filter=vtk.vtkWindowToImageFilter()window_to_image_filter.SetInput(render_window)window_to_image_filter.Update()vtk_image=window_to_image_filter.GetOutput()h,w,_=vtk_image.GetDimensions()vtk_array=vtk_image.GetPointData().GetScalars()components=vtk_array.GetNumberOfComponents()arr=numpy_support.vtk_to_numpy(vtk_array).reshape(h,w,components)iffnameisNone:returnarrwriter=vtk.vtkPNGWriter()writer.SetFileName(fname)writer.SetInputConnection(window_to_image_filter.GetOutputPort())writer.Write()returnarr
[docs]defanalyze_snapshot(im,bg_color=(0,0,0),colors=None,find_objects=True,strel=None):""" Analyze snapshot from memory or file Parameters ---------- im: str or array If string then the image is read from a file otherwise the image is read from a numpy array. The array is expected to be of shape (X, Y, 3) or (X, Y, 4) where the last dimensions are the RGB or RGBA values. colors: tuple (3,) or list of tuples (3,) List of colors to search in the image find_objects: bool If True it will calculate the number of objects that are different from the background and return their position in a new image. strel: 2d array Structure element to use for finding the objects. Returns ------- report : ReportSnapshot This is an object with attibutes like ``colors_found`` that give information about what was found in the current snapshot array ``im``. """ifisinstance(im,basestring):reader=vtk.vtkPNGReader()reader.SetFileName(im)reader.Update()vtk_im=reader.GetOutput()vtk_ext=vtk_im.GetExtent()vtk_pd=vtk_im.GetPointData()vtk_comp=vtk_pd.GetNumberOfComponents()shape=(vtk_ext[1]-vtk_ext[0]+1,vtk_ext[3]-vtk_ext[2]+1,vtk_comp)im=numpy_support.vtk_to_numpy(vtk_pd.GetArray(0))im=im.reshape(shape)classReportSnapshot(object):objects=Nonelabels=Nonecolors_found=Falsereport=ReportSnapshot()ifcolorsisnotNone:ifisinstance(colors,tuple):colors=[colors]flags=[False]*len(colors)for(i,col)inenumerate(colors):# find if the current color exist in the arrayflags[i]=np.any(np.all(im==col,axis=-1))report.colors_found=flagsiffind_objectsisTrue:weights=[0.299,0.587,0.144]gray=np.dot(im[...,:3],weights)bg_color=im[0,0]background=np.dot(bg_color,weights)ifstrelisNone:strel=np.array([[1,1,1],[1,1,1],[1,1,1]])labels,objects=ndimage.label(gray!=background,strel)report.labels=labelsreport.objects=objectsreturnreport