def _data_changed(self, old, new): """When the vtk dataset changes, adjust the pipeline accordingly so that we sync against the new dataset""" if has_attributes(self.data): aa = self._assign_attribute self.configure_input_data(aa, new) self._update_vtk_dataset_content() aa.update() self.outputs = [aa.output] else: self.outputs = [self.data] # Notify the pipeline to refresh against the new data. self.data_changed = True self.output_info.datasets = \ [get_tvtk_dataset_name(self.outputs[0])] # Add an observer to the VTK dataset after removing the one # for the old dataset. We use the messenger to avoid an # uncollectable reference cycle. See the # tvtk.messenger module documentation for details. if old is not None: old.remove_observer(self._observer_id) self._observer_id = new.add_observer('ModifiedEvent', messenger.send) new_vtk = tvtk.to_vtk(new) messenger.connect(new_vtk, 'ModifiedEvent', self._fire_data_changed)
def __init__(self, input): self.dataset = dsa.WrapDataObject( tvtk.to_vtk(get_new_output(input, update=True)) ) self._composite = isinstance(self.dataset, dsa.CompositeDataSet) self._scalars = None self._vectors = None
def _data_changed(self, old, new): if has_attributes(self.data): aa = self._assign_attribute self.configure_input_data(aa, new) self._update_data() aa.update() self.outputs = [aa.output] else: self.outputs = [self.data] self.data_changed = True self.output_info.datasets = \ [get_tvtk_dataset_name(self.outputs[0])] # Add an observer to the VTK dataset after removing the one # for the old dataset. We use the messenger to avoid an # uncollectable reference cycle. See the # tvtk.messenger module documentation for details. if old is not None: old.remove_observer(self._observer_id) self._observer_id = new.add_observer('ModifiedEvent', messenger.send) new_vtk = tvtk.to_vtk(new) messenger.connect(new_vtk, 'ModifiedEvent', self._fire_data_changed) # Change our name so that our label on the tree is updated. self.name = self._get_name()
def get_vtk(data, time): # temporary function generating vtk data structure for experiment from tvtk.api import tvtk tt = to_unixtime(time) ds = data.sel(time=tt, method='nearest') fv = ds.dist.values[0, ...] vr = ds.vr.values[0, ...] vt = ds.vt.values[0, ...] vp = ds.vp.values[0, ...] f, r, t, p = _extend_mesh_interp(fv, vr, vt, vp) fmax = f.max() fmin = fmax * 1.0e-15 f = np.clip(f[:-1, ...], fmin, fmax) # eliminate zeros p = p[:-1, ...] rr = r[None, None, :] tt = t[None, :, None] pp = p[:, None, None] dims = f.shape mesh = np.zeros((np.prod(dims), 3), dtype=np.float64) mesh[:, 0] = (rr * np.sin(tt) * np.cos(pp)).ravel() mesh[:, 1] = (rr * np.sin(tt) * np.sin(pp)).ravel() mesh[:, 2] = (rr * np.cos(tt) * np.ones_like(pp)).ravel() sgrid = tvtk.StructuredGrid(dimensions=dims[::-1]) sgrid.points = np.zeros((np.prod(dims), 3), dtype=np.float64) sgrid.points = mesh sgrid.point_data.scalars = np.log10(f.ravel()) sgrid.point_data.scalars.name = 'VDF' return tvtk.to_vtk(sgrid)
def OnPaint(self, event): """This method is overridden temporarily in order to create the light manager. This is necessary because it makes sense to create the light manager only when the widget is realized. Only when the widget is realized is the VTK render window created and only then are the default lights all setup correctly. This handler is removed on the first Paint event and the default paint handler of the wxVTKRenderWindowInteractor is used instead.""" # Call the original handler (this will Show the widget) self._vtk_control.OnPaint(event) if len(self.renderer.lights) == 0: # The renderer is not ready yet, we do not do anything, and # we do not remove this callback, so that it will be called # later. return # Now create the light manager. self.light_manager = light_manager.LightManager(self) renwin = self._renwin renwin.update_traits() vtk_rw = tvtk.to_vtk(renwin) renwin.add_observer('StartEvent', messenger.send) messenger.connect(vtk_rw, 'StartEvent', self._start_event_callback) renwin.add_observer('EndEvent', messenger.send) messenger.connect(vtk_rw, 'EndEvent', self._end_event_callback) # Reset the event handler to the default since our job is done. wx.EVT_PAINT(self._vtk_control, None) # Remove the default handler. wx.EVT_PAINT(self._vtk_control, self._vtk_control.OnPaint)
def save_u3d(self, event=None): """Save last renderd scene as u3d.""" from tvtk.api import tvtk try: import vtku3dexporter except ImportError: wx.MessageBox( 'u3d export needs the vtku3dexporter module, which is not installed by default with PYME\n A conda-installable package is available for OSX.' ) fdialog = wx.FileDialog(None, 'Save 3D scene as ...', wildcard='*.u3d', style=wx.FD_SAVE) # | wx.HIDE_READONLY) succ = fdialog.ShowModal() if (succ == wx.ID_OK): fname = fdialog.GetPath() #tvtk.STLWriter(input=self.lastSurf.actor.mapper.input, file_name=fname).write() render_window = tvtk.to_vtk(self.dsviewer.f3d.scene.render_window) u3d_exporter = vtku3dexporter.vtkU3DExporter() u3d_exporter.SetFileName(fname) u3d_exporter.SetInput(render_window) u3d_exporter.Write() fdialog.Destroy()
def _set_origin(self, value): # Ugly, but needed. w = tvtk.to_vtk(self.widget) old = w.GetOrigin() w.SetOrigin(list(value)) self.trait_property_changed('origin', old, value) self.update_plane()
def _add_particles(self, iterable): data_set = self.data_set points = data_set.points particle2index = self.particle2index item_uids = [] for particle in iterable: with self._add_item(particle, particle2index) as item: if self.initialized: # We remove the dummy point self.data_set.points = tvtk.Points() points = data_set.points self.initialized = False index = points.insert_next_point(item.coordinates) particle2index[item.uid] = index self.index2particle[index] = item.uid self.point_data.append(item.data) item_uids.append(item.uid) # adding new points causes the cached array under # tvtk.array_handler to be inconsistent with the # points FloatArray, therefore we need to remove # the reference in the tvtk.array_handler._array_cache # for points.to_array() to work properly _array_cache = None for name in ['array_handler', 'tvtk.array_handler']: if name in sys.modules: mod = sys.modules[name] if hasattr(mod, '_array_cache'): _array_cache = mod._array_cache break if _array_cache: _array_cache._remove_array(tvtk.to_vtk(points.data).__this__) return item_uids
def _recorder_changed(self, r): """When the recorder is set we add an event handler so we can record the change to the camera position after the interaction. """ iren = self._interactor if r is not None: self._script_id = r.get_script_id(self) id = iren.add_observer("EndInteractionEvent", messenger.send) self._camera_observer_id = id i_vtk = tvtk.to_vtk(iren) messenger.connect(i_vtk, "EndInteractionEvent", self._record_camera_position) else: self._script_id = "" iren.remove_observer(self._camera_observer_id) i_vtk = tvtk.to_vtk(iren) messenger.disconnect(i_vtk, "EndInteractionEvent", self._record_camera_position)
def test_to_vtk_returns_vtk_object(self): # Given x = tvtk.ContourFilter() # When v = tvtk.to_vtk(x) # Then self.assertEqual(v.GetClassName(), 'vtkContourFilter') self.assertTrue(v is x._vtk_obj)
def __len__(self): """ The number of contained cells. """ # Need to use the vtk implementation due to issue # https://github.com/enthought/mayavi/issues/178 vtk_object = tvtk.to_vtk(self._cell_array) return vtk_object.GetNumberOfCells()
def get_children(self, obj): """Returns the child objects of a particular tvtk object in a dictionary, the keys are the trait names. This is used to generate the tree in the browser.""" vtk_obj = tvtk.to_vtk(obj) methods = self._get_methods(vtk_obj) kids = {} def _add_kid(key, x): if x is None: kids[key] = None else: if type(x) in (type([]), type(())): x1 = [i for i in x if isinstance(i, TVTKBase)] if x1: kids[key] = x1 elif isinstance(x, TVTKBase): if hasattr(x, '__iter__'): # Don't add iterable objects that contain non # acceptable nodes if len(list(x)) and isinstance(list(x)[0], TVTKBase): kids[key] = x else: kids[key] = x for method in methods: attr = camel2enthought(method[0]) if hasattr(obj, attr): _add_kid(attr, getattr(obj, attr)) # Check for sources and inputs. if hasattr(obj, 'number_of_sources'): srcs = [obj.get_source(i) for i in range(obj.number_of_sources)] _add_kid('source', srcs) elif hasattr(obj, 'source'): _add_kid('source', obj.source) if hasattr(obj, 'get_input_algorithm'): inputs = [] if hasattr(obj, 'number_of_input_ports'): inputs = [ obj.get_input_algorithm(i, j) for i in range(obj.number_of_input_ports) for j in range(obj.get_number_of_input_connections(i)) ] _add_kid('input', inputs) elif hasattr(obj, 'get_input'): inputs = [obj.get_input(i) for i in range(obj.number_of_inputs)] _add_kid('input', inputs) elif hasattr(obj, 'input'): _add_kid('input', obj.input) if hasattr(obj, 'producer_port'): _add_kid('producer_port', obj.producer_port) return kids
def get_children(self, obj): """Returns the child objects of a particular tvtk object in a dictionary, the keys are the trait names. This is used to generate the tree in the browser.""" vtk_obj = tvtk.to_vtk(obj) methods = self._get_methods(vtk_obj) kids = {} def _add_kid(key, x): if x is None: kids[key] = None else: if type(x) in (type([]), type(())): x1 = [i for i in x if isinstance(i, TVTKBase)] if x1: kids[key] = x1 elif isinstance(x, TVTKBase): if hasattr(x, '__iter__'): # Don't add iterable objects that contain non # acceptable nodes if len(list(x)) and isinstance(list(x)[0], TVTKBase): kids[key] = x else: kids[key] = x for method in methods: attr = camel2enthought(method[0]) if hasattr(obj, attr): _add_kid(attr, getattr(obj, attr)) # Check for sources and inputs. if hasattr(obj, 'number_of_sources'): srcs = [obj.get_source(i) for i in range(obj.number_of_sources)] _add_kid('source', srcs) elif hasattr(obj, 'source'): _add_kid('source', obj.source) if hasattr(obj, 'get_input_algorithm'): inputs = [] if hasattr(obj, 'number_of_input_ports'): inputs = [obj.get_input_algorithm(i, j) for i in range(obj.number_of_input_ports) for j in range( obj.get_number_of_input_connections(i))] _add_kid('input', inputs) elif hasattr(obj, 'get_input'): inputs = [obj.get_input(i) for i in range(obj.number_of_inputs)] _add_kid('input', inputs) elif hasattr(obj, 'input'): _add_kid('input', obj.input) if hasattr(obj, 'producer_port'): _add_kid('producer_port', obj.producer_port) return kids
def _recorder_changed(self, r): """When the recorder is set we add an event handler so we can record the change to the camera position after the interaction. """ iren = self._interactor if r is not None: self._script_id = r.get_script_id(self) id = iren.add_observer('EndInteractionEvent', messenger.send) self._camera_observer_id = id i_vtk = tvtk.to_vtk(iren) messenger.connect(i_vtk, 'EndInteractionEvent', self._record_camera_position) else: self._script_id = '' iren.remove_observer(self._camera_observer_id) i_vtk = tvtk.to_vtk(iren) messenger.disconnect(i_vtk, 'EndInteractionEvent', self._record_camera_position)
def _remove_listners(self): object = self.object kids = self.children_cache for key, val in kids.items(): if isinstance(val, tvtk.Collection): vtk_obj = tvtk.to_vtk(val) messenger.disconnect(vtk_obj, 'ModifiedEvent', self._notify_children) else: object.on_trait_change(self._notify_children, key, remove=True)
def intersect_line(self, lineP0, lineP1): ''' 计算与线段相交的交点,这里调用了tvtk的方法 lineP0: 线段的第一个点,长度3的数组 lineP1: 线段的第二个点 return points: 所有的交点坐标 cell_ids: 每个交点所属的面片ID ''' intersectPoints = tvtk.to_vtk(tvtk.Points()) intersectCells = tvtk.to_vtk(tvtk.IdList()) self._obb_tree.intersect_with_line(lineP0, lineP1, intersectPoints, intersectCells) intersectPoints = tvtk.to_tvtk(intersectPoints) intersectCells = tvtk.to_tvtk(intersectCells) points = intersectPoints.to_array() cell_ids = [ intersectCells.get_id(i) for i in range(intersectCells.number_of_ids) ] return points, cell_ids
def test_add_dataset_works_with_vtk_datasets(self): # Given pd = vtk.vtkPolyData() # When mlab.pipeline.add_dataset(pd) # Then e = mlab.get_engine() src = e.scenes[0].children[0] from mayavi.sources.vtk_data_source import VTKDataSource self.assertTrue(isinstance(src, VTKDataSource)) self.assertEqual(tvtk.to_vtk(src.data), pd)
def __init__(self, figure=None, **traits): super(RemoteScene, self).__init__(**traits) if figure is None: figure = gcf() self.figure = figure self.scene = figure.scene self.trw = self.scene.render_window self.trwi = self.scene.interactor self.rwi = tvtk.to_vtk(self.trwi) self.rw = tvtk.to_vtk(self.trw) self.ren = tvtk.to_vtk(self.scene.renderer) self.id = id(self) self._last_image = '' self._last_render = 0 self._time_to_render = 0 self._time_for_image = 0 self._render_size = 200*200 self._pending_render = False self._doing_render = False self._timer_enabled = True self._setup_scene()
def _number_of_labels_changed(self, value): if self.input is None: return f = self.mask.filter inp = self.input.get_output_dataset() data_obj = dsa.WrapDataObject(tvtk.to_vtk(inp)) npts = data_obj.GetNumberOfPoints() typ = type(f.on_ratio) f.on_ratio = typ(max(npts/value, 1)) if self.mask.running: f.update() self.mask.data_changed = True
def __init__(self, figure=None, **traits): super(RemoteScene, self).__init__(**traits) if figure is None: figure = gcf() self.figure = figure self.scene = figure.scene self.trw = self.scene.render_window self.trwi = self.scene.interactor self.rwi = tvtk.to_vtk(self.trwi) self.rw = tvtk.to_vtk(self.trw) self.ren = tvtk.to_vtk(self.scene.renderer) self.id = id(self) self._last_image = '' self._last_render = 0 self._time_to_render = 0 self._time_for_image = 0 self._render_size = 200 * 200 self._pending_render = False self._doing_render = False self._timer_enabled = True self._setup_scene()
def get_tvtk_dataset_name(obj): v = tvtk.to_vtk(obj) obj = v.GetOutputInformation(0).Get(vtk.vtkDataObject.DATA_OBJECT()) if obj is not None: name = obj.GetClassName() else: name = v.GetOutputPortInformation(0).Get( vtk.vtkDataObject.DATA_TYPE_NAME()) if name is None: # Try again after calling update v.Update() return get_tvtk_dataset_name(v) return [tvtk_dataset_name(name)]
def has_attributes(dataset): """Returns `True` when the given TVTK `dataset` has any attribute arrays in point and cell data and `False` otherwise. """ if dataset is None: return False obj = dsa.WrapDataObject(tvtk.to_vtk(get_new_output(dataset))) if obj.PointData and len(obj.PointData.keys()) > 0: return True if obj.CellData and len(obj.CellData.keys()) > 0: return True return False
def _object_changed(self, old, new): self.outputs = [new] self.browser.root_object = [new] self.output_info.datasets = get_tvtk_dataset_name(new) if old is not None: old.remove_observer(self._observer_id) self._observer_id = new.add_observer('ModifiedEvent', messenger.send) new_vtk = tvtk.to_vtk(new) messenger.connect(new_vtk, 'ModifiedEvent', self._fire_data_changed) self.name = self._get_name()
def tvtk_show(renderer, width=400, height=300): """ Takes vtkRenderer instance and returns an IPython Image with the rendering. """ renderWindow = tvtk.RenderWindow(off_screen_rendering=True,size=[width,height]) renderWindow.add_renderer(renderer) renderWindow.render() windowToImageFilter = tvtk.WindowToImageFilter(input=renderWindow) windowToImageFilter.update() writer = tvtk.PNGWriter(write_to_memory=True,input=windowToImageFilter.output) writer.write() data = str(buffer(tvtk.to_vtk(writer).GetResult())) return Image(data)
def get_children(self, obj): """Returns the child objects of a particular tvtk object in a dictionary, the keys are the trait names. This is used to generate the tree in the browser.""" vtk_obj = tvtk.to_vtk(obj) methods = self._get_methods(vtk_obj) kids = {} def _add_kid(key, x): if x is None: kids[key] = None else: if type(x) in (type([]), type(())): x1 = [i for i in x if isinstance(i, TVTKBase)] if x1: kids[key] = x1 elif isinstance(x, TVTKBase): if hasattr(x, '__iter__'): # Don't add iterable objects that contain non # acceptable nodes if len(list(x)) and isinstance(list(x)[0], TVTKBase): kids[key] = x else: kids[key] = x for method in methods: attr = camel2enthought(method[0]) if hasattr(obj, attr): _add_kid(attr, getattr(obj, attr)) if hasattr(obj, 'number_of_input_ports'): count = obj.number_of_input_ports inputs = [] for i in range(count): for j in range(obj.get_number_of_input_connections(i)): producer = obj.get_input_connection(i, j).producer if isinstance(producer, tvtk.TrivialProducer): producer = obj.get_input_data_object(i, j) inputs.append(producer) _add_kid('input', inputs) return kids
def paintEvent(self, e): """ Reimplemented to create the light manager only when needed. This is necessary because it makes sense to create the light manager only when the widget is realized. Only when the widget is realized is the VTK render window created and only then are the default lights all setup correctly. """ QVTKRenderWindowInteractor.paintEvent(self, e) scene = self._scene if scene.light_manager is None: scene.light_manager = light_manager.LightManager(scene) renwin = scene._renwin renwin.update_traits() vtk_rw = tvtk.to_vtk(renwin) renwin.add_observer('StartEvent', messenger.send) messenger.connect(vtk_rw, 'StartEvent', self._start_event_callback) renwin.add_observer('EndEvent', messenger.send) messenger.connect(vtk_rw, 'EndEvent', self._end_event_callback)
def test_suppress_vtk_warnings(self): obj = tvtk.to_vtk(tvtk.Object()) self.assertEqual(obj.GetGlobalWarningDisplay(), 1) with suppress_vtk_warnings(): self.assertEqual(obj.GetGlobalWarningDisplay(), 0) self.assertEqual(obj.GetGlobalWarningDisplay(), 1)
def _get_actors(x): return [tvtk.to_vtk(i) for i in x]
def get_children(self, obj): """Returns the child objects of a particular tvtk object in a dictionary, the keys are the trait names. This is used to generate the tree in the browser.""" vtk_obj = tvtk.to_vtk(obj) methods = self._get_methods(vtk_obj) kids = {} def _add_kid(key, x): if x is None: kids[key] = None else: if type(x) in (type([]), type(())): x1 = [i for i in x if isinstance(i, TVTKBase)] if x1: kids[key] = x1 elif isinstance(x, TVTKBase): if hasattr(x, '__iter__'): # Don't add iterable objects that contain non # acceptable nodes if len(list(x)) and isinstance(list(x)[0], TVTKBase): kids[key] = x else: kids[key] = x for method in methods: attr = camel2enthought(method[0]) if hasattr(obj, attr): _add_kid(attr, getattr(obj, attr)) # Check for sources and inputs. if hasattr(obj, 'number_of_sources'): srcs = [obj.get_source(i) \ for i in range(obj.number_of_sources)] _add_kid('source', srcs) elif hasattr(obj, 'source'): _add_kid('source', obj.source) if hasattr(obj, 'get_input'): inputs = [] if hasattr(obj, 'number_of_input_ports'): if obj.number_of_input_ports: # Sometimes not all the inputs can be retrieved using # 'get_input', as they may be sources (for instance # the ProbeFilter). inputs = list() for i in range(obj.number_of_input_ports): try: inputs.append(obj.get_input(i)) except TypeError: pass if not inputs: inputs = [obj.get_input()] else: inputs = [obj.get_input(i) \ for i in range(obj.number_of_inputs)] _add_kid('input', inputs) elif hasattr(obj, 'input'): _add_kid('input', obj.input) if hasattr(obj, 'producer_port'): _add_kid('producer_port', obj.producer_port) return kids
out_dir = sys.argv[1] fromi = int(sys.argv[2]) toi = int(sys.argv[3]) print "out_dir = ",out_dir," averaging from i = ",fromi," to ",toi particles_sum = Particles() particles = Particles() for i in range(fromi,toi): filename = '%s/vtkAveraged%04d.vtu'%(out_dir,i) print 'reading from file ',filename r = tvtk.XMLUnstructuredGridReader(file_name=filename) r.update() grid = tvtk.to_vtk(r.output) particles.copy_from_vtk_grid(grid) if i == fromi: particles_sum.copy_from_vtk_grid(tvtk.to_vtk(r.output)) else: for p_sum,p in zip(particles_sum,particles): delta = p_sum.averaged_orientation - p.averaged_orientation total_n = p_sum.number_of_moves + p.number_of_moves p_sum.averaged_orientation = p.averaged_orientation + delta*float(p_sum.number_of_moves)/total_n #p_sum.variance_orientation = p_sum.variance_orientation + p.variance_orientation + delta**2*p_sum.number_of_moves*p.number_of_moves/total_n p_sum.variance_orientation = p.variance_orientation p_sum.number_of_moves = total_n w = tvtk.XMLUnstructuredGridWriter(input=particles_sum.get_grid(), file_name='%s/vtkAveragedAverage%04d_%04d.vtu'%(out_dir,fromi,toi))
# lut = tvtk.LookupTable(hue_range=[0.66667,0.0],range=[0,1]); lut.build() lut2 = tvtk.LookupTable(hue_range=[0.66667,0.0],range=[0,0.1]); lut2.build() domain_source = tvtk.CubeSource(x_length=L,y_length=L,z_length=0,center=[L/2.0,L/2.0,0]) aDomainSource = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=domain_source.output),property=tvtk.Property(representation='w')) aScalarBar = tvtk.ScalarBarActor(lookup_table=lut,title="s",position=[0.87,0.1],label_format='%-#2.1g',maximum_width_in_pixels=100) aScalarBar2 = tvtk.ScalarBarActor(lookup_table=lut2,title="Q Var",position=[0.87,0.1],label_format='%-#2.1g',maximum_width_in_pixels=100) transform = tvtk.Transform() tvtk.to_vtk(transform).RotateZ(90) cylinder_source = tvtk.TransformPolyDataFilter(input=tvtk.CylinderSource(height=reduce*sigma_s*2,radius=reduce*sigma_s/5).output,transform=transform) # # Averaged Visualisation # if len(averaged_files)>0: r = tvtk.XMLUnstructuredGridReader(file_name=averaged_files[0]) calc1 = tvtk.ArrayCalculator(input=r.output,result_array_name="s",function="mag(averaged_orientation)",replacement_value=0, replace_invalid_values=True) calc1.add_vector_variable('averaged_orientation','averaged_orientation') calc2 = tvtk.ArrayCalculator(input=calc1.output,result_array_name="n1",function="sqrt(ao_X/(2*s) + 0.5)",replacement_value=0,replace_invalid_values=True) calc2.add_scalar_variable('ao_X','averaged_orientation',0) calc2.add_scalar_variable('s','s') calc3 = tvtk.ArrayCalculator(input=calc2.output,result_array_name="n2",function="ao_Y/(2*s*n1)",replacement_value=1,replace_invalid_values=True)
def _find_number_of_points_in_input(self): inp = self.inputs[0].get_output_dataset() o = dsa.WrapDataObject(tvtk.to_vtk(inp)) return o.GetNumberOfPoints()
import nibabel as nib import numpy as np from tvtk.api import tvtk,write_data import vtk from vtk.util import numpy_support nii=nib.load('Annotation2014.nii.gz') reader=tvtk.NIFTIImageReader() reader.file_name='Annotation2014.nii.gz' reader.update() image=reader.get_output() image.origin=nii.affine[0:3,3] vImage=tvtk.to_vtk(image) vPD=vImage.GetPointData() vSC=vPD.GetScalars() data=numpy_support.vtk_to_numpy(vSC) indxs=np.unique(data) for ind in indxs[1:]: print ind tmp=data.copy() tmp[tmp!=ind]=0 tmp[tmp==ind]=1 vPD.SetScalars(numpy_support.numpy_to_vtk(tmp)) image=tvtk.to_tvtk(vImage) iso=tvtk.MarchingCubes()
def __hash__(self): return hash(tvtk.to_vtk(self.object))
def view(image=None, # noqa: C901 label_image=None, # noqa: C901 label_image_names=None, # noqa: C901 label_image_weights=None, # noqa: C901 label_image_blend=0.5, cmap=None, lut='glasbey', select_roi=False, interpolation=True, gradient_opacity=0.22, opacity_gaussians=None, channels=None, slicing_planes=False, shadow=True, blend_mode='composite', point_sets=[], point_set_colors=[], point_set_opacities=[], point_set_representations=[], point_set_sizes=[], geometries=[], geometry_colors=[], geometry_opacities=[], ui_collapsed=False, rotate=False, annotations=True, mode='v', **kwargs): """View the image and/or point sets and/or geometries. Creates and returns an ipywidget to visualize an image, and/or point sets and/or geometries . The image can be 2D or 3D. A label map that corresponds to the image can also be provided. The image and label map must have the same size. The type of the image can be an numpy.array, itk.Image, vtk.vtkImageData, pyvista.UniformGrid, imglyb.ReferenceGuardingRandomAccessibleInterval, or a NumPy array-like, e.g. a Dask array. A point set or a sequence of points sets can be visualized. The type of the point set can be an numpy.array (Nx3 array of point positions). A geometry or a sequence of geometries can be visualized. The type of the geometry can be an itk.Mesh. Parameters ---------- General Interface ^^^^^^^^^^^^^^^^^ ui_collapsed : bool, default: False Collapse the native widget user interface. rotate : bool, default: False Continuously rotate the camera around the scene in volume rendering mode. annotations : bool, default: True Display annotations describing orientation and the value of a mouse-position-based data probe. mode: 'x', 'y', 'z', or 'v', default: 'v' Only relevant for 3D scenes. Viewing mode: 'x': x-plane 'y': y-plane 'z': z-plane 'v': volume rendering camera: 3x3 numpy float32 array Camera parameters: [[position_x, position_y, position_z], [focal_point_x, focal_point_y, focal_point_z], [view_up_x, view_up_y, view_up_z]] background: (red, green, blue) tuple, components from 0.0 to 1.0 Background color. Default is based on the current Jupyter theme. Images ^^^^^^ image : array_like, itk.Image, or vtk.vtkImageData The 2D or 3D image to visualize. label_image : array_like, itk.Image, or vtk.vtkImageData The 2D or 3D label map to visualize. If an image is also provided, the label map must have the same size. label_image_names : OrderedDict of (label_value, label_name) String names associated with the integer label values. label_image_weights : 1D numpy float32 array, default: None Rendering weights, from 0.0 to 1.0, associated labels in the label map. label_image_blend : float, default: 0.5 Label map blend with intensity image, from 0.0 to 1.0. vmin: list of floats, default: Minimum of the image pixel buffer Value that maps to the minimum of image colormap. A single value can be provided or a list for multi-component images. vmax: list of floats, default: Maximum of the image pixel buffer Value that maps to the minimum of image colormap. A single value can be provided or a list for multi-component images. cmap: list of colormaps default: - single component: 'viridis', 'grayscale' with a label map, - two components: 'BkCy', 'BkMa' - three components: 'BkRd', 'BkGn', 'BkBu' Colormap for each image component. Some valid values available at itkwidgets.cm.* Colormaps can also be Nx3 float NumPy arrays from 0.0 to 1.0 for the red, green, blue points on the map or a matplotlib.colors.LinearSegmentedColormap. lut: lookup table, default: 'glasbey' Lookup table for the label map. Some valid values available at itkwidgets.lut.* select_roi: bool, default: False Enable an interactive region of interest widget for the image. slicing_planes: bool, default: False Enable slicing planes on the volume rendering. x_slice: float, default: None World-space position of the X slicing plane. y_slice: float, default: None World-space position of the Y slicing plane. z_slice: float, default: None World-space position of the Z slicing plane. interpolation: bool, default: True Linear as opposed to nearest neighbor interpolation for image slices. Note: Interpolation is not currently supported with label maps. gradient_opacity: float, default: 0.22 Gradient opacity for composite volume rendering, in the range (0.0, 1.0]. opacity_gaussians: list of list of dict Volume rendering opacity transfer function Gaussian parameters. For each image component, multiple Gaussians can be specified. Default Gaussian parameters: {'position': 0.5, 'height': 1, 'width': 0.5, 'xBias': 0.51, 'yBias': 0.4} channels: list of booleans For multi-component images, the components or channels that are enabled. shadow: bool, default: True Use shadowing with composite volume rendering. blend_mode: 'composite', 'max', 'min', or 'average', default: 'composite' Volume rendering blend mode. Point Sets ^^^^^^^^^^ point_sets: point set, or sequence of point sets The point sets to visualize. point_set_colors: list of (r, g, b) colors Colors for the N points. See help(matplotlib.colors) for specification. Defaults to the Glasbey series of categorical colors. point_set_opacities: array of floats, default: [1.0,]*n Opacity for the point sets, in the range (0.0, 1.0]. point_set_sizes: array of unsigned integers, default: [3,]*n Sizes for the point sets, in pixel size units. point_set_representations: list of strings, default: ['points',]*n How to represent the point set. One of 'hidden', 'points', or 'spheres'. Geometries ^^^^^^^^^^ geometries: geometries, or sequence of geometries The geometries to visualize. geometry_colors: list of RGB colors Colors for the N geometries. See help(matplotlib.colors) for specification. Defaults to the Glasbey series of categorical colors. geometry_opacities: list of floats, default: [1.0,]*n Opacity for the point sets, in the range (0.0, 1.0]. Other Parameters ---------------- units: string, default: '' Units to display in the scale bar. actors: vtkActor, vtkAssembly, vtkVolume, default: None List of standard vtk objects, colors are extracted from their properties size_limit_2d: 2x1 numpy int64 array, default: [1024, 1024] Size limit for 2D image visualization. If the roi is larger than this size, it will be downsampled for visualization size_limit_3d: 3x1 numpy int64 array, default: [192, 192, 192] Size limit for 3D image visualization. If the roi is larger than this size, it will be downsampled for visualization. sample_distance: float, default: 0.25 Sampling distance for volume rendering, normalized from 0.0 to 1.0. Lower values result in a higher quality rendering. High values improve the framerate. Returns ------- viewer : ipywidget Display by placing at the end of a Jupyter cell or calling IPython.display.display. Query or set properties on the object to change the visualization or retrieve values created by interacting with the widget. """ # this block allows the user to pass already formed vtkActor vtkVolume # objects actors = kwargs.pop("actors", None) if have_vtk and actors is not None: if not isinstance(actors, (list, tuple) ): # passing the object directly, so make it a list actors = [actors] images = [] for a in actors: if have_mayavi: from mayavi.modules import surface from mayavi.modules import iso_surface from tvtk.api import tvtk if isinstance(a, surface.Surface): a = tvtk.to_vtk(a.actor.actor) elif isinstance(a, iso_surface.IsoSurface): a = tvtk.to_vtk(a.actor.actor) if isinstance(a, vtk.vtkAssembly): # unpack assemblies cl = vtk.vtkPropCollection() a.GetActors(cl) cl.InitTraversal() for i in range(a.GetNumberOfPaths()): ac = vtk.vtkActor.SafeDownCast(cl.GetNextProp()) apoly = ac.GetMapper().GetInput() prop = ac.GetProperty() transform = vtk.vtkTransform() transform.SetMatrix(ac.GetMatrix()) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) tp.SetInputData(apoly) tp.Update() poly = tp.GetOutput() if poly.GetNumberOfPolys(): geometries.insert(0, poly) geometry_colors.insert(0, prop.GetColor()) geometry_opacities.insert(0, prop.GetOpacity()) else: point_sets.insert(0, poly) point_set_colors.insert(0, prop.GetColor()) point_set_opacities.insert(0, prop.GetOpacity()) elif isinstance(a, vtk.vtkActor): apoly = a.GetMapper().GetInput() transform = vtk.vtkTransform() transform.SetMatrix(a.GetMatrix()) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) tp.SetInputData(apoly) tp.Update() poly = tp.GetOutput() prop = a.GetProperty() if poly.GetNumberOfPolys() or poly.GetNumberOfStrips() or poly.GetNumberOfLines(): geometries.insert(0, poly) geometry_colors.insert(0, prop.GetColor()) geometry_opacities.insert(0, prop.GetOpacity()) else: point_sets.insert(0, poly) point_set_colors.insert(0, prop.GetColor()) point_set_opacities.insert(0, prop.GetOpacity()) elif isinstance(a, vtk.vtkVolume): images.append(a.GetMapper().GetInput()) if image is None and len(images): # only one image is rendered image = images[0] viewer = Viewer(image=image, label_image=label_image, label_image_names=label_image_names, label_image_blend=label_image_blend, label_image_weights=label_image_weights, cmap=cmap, lut=lut, select_roi=select_roi, interpolation=interpolation, gradient_opacity=gradient_opacity, opacity_gaussians=opacity_gaussians, slicing_planes=slicing_planes, shadow=shadow, blend_mode=blend_mode, point_sets=point_sets, point_set_colors=point_set_colors, point_set_opacities=point_set_opacities, point_set_representations=point_set_representations, point_set_sizes=point_set_sizes, geometries=geometries, geometry_colors=geometry_colors, geometry_opacities=geometry_opacities, rotate=rotate, ui_collapsed=ui_collapsed, annotations=annotations, mode=mode, **kwargs) return viewer
def _add_observer(self, obj, event, cb): """ Adds a vtk observer using messenger to avoid generating uncollectable objects. """ obj.add_observer(event, messenger.send) messenger.connect(tvtk.to_vtk(obj), event, cb)
def view(image=None, # noqa: C901 cmap=cm.viridis, select_roi=False, interpolation=True, gradient_opacity=0.22, slicing_planes=False, shadow=True, blend='composite', point_sets=[], point_set_colors=[], point_set_opacities=[], point_set_representations=[], # point_set_sizes=[], geometries=[], geometry_colors=[], geometry_opacities=[], ui_collapsed=False, rotate=False, annotations=True, mode='v', **kwargs): """View the image and/or point sets and/or geometries. Creates and returns an ipywidget to visualize an image, and/or point sets and/or geometries . The image can be 2D or 3D. The type of the image can be an numpy.array, itk.Image, vtk.vtkImageData, pyvista.UniformGrid, imglyb.ReferenceGuardingRandomAccessibleInterval, or a NumPy array-like, e.g. a Dask array. A point set or a sequence of points sets can be visualized. The type of the point set can be an numpy.array (Nx3 array of point positions). A geometry or a sequence of geometries can be visualized. The type of the geometry can be an itk.Mesh. Parameters ---------- General Interface ^^^^^^^^^^^^^^^^^ ui_collapsed : bool, optional, default: False Collapse the native widget user interface. rotate : bool, optional, default: False Continuously rotate the camera around the scene in volume rendering mode. annotations : bool, optional, default: True Display annotations describing orientation and the value of a mouse-position-based data probe. mode: 'x', 'y', 'z', or 'v', optional, default: 'v' Only relevant for 3D scenes. Viewing mode: 'x': x-plane 'y': y-plane 'z': z-plane 'v': volume rendering camera: 3x3 numpy float32 array, optional Camera parameters: [[position_x, position_y, position_z], [focal_point_x, focal_point_y, focal_point_z], [view_up_x, view_up_y, view_up_z]] Images ^^^^^^ image : array_like, itk.Image, or vtk.vtkImageData The 2D or 3D image to visualize. vmin: float, optional, default: None Value that maps to the minimum of image colormap. Defaults to minimum of the image pixel buffer. vmax: float, optional, default: None Value that maps to the minimum of image colormap. Defaults to maximum of the image pixel buffer. cmap: string, optional, default: 'Viridis (matplotlib)' Colormap. Some valid values available at itkwidgets.cm.* select_roi: bool, optional, default: False Enable an interactive region of interest widget for the image. slicing_planes: bool, optional, default: False Enable slicing planes on the volume rendering. x_slice: float, optional, default: None World-space position of the X slicing plane. y_slice: float, optional, default: None World-space position of the Y slicing plane. z_slice: float, optional, default: None World-space position of the Z slicing plane. interpolation: bool, optional, default: True Linear as opposed to nearest neighbor interpolation for image slices. gradient_opacity: float, optional, default: 0.22 Gradient opacity for composite volume rendering, in the range (0.0, 1.0]. shadow: bool, optional, default: True Use shadowing with composite volume rendering. blend: 'composite', 'max', 'min', or 'average', optional, default: 'composite' Volume rendering blend mode. Point Sets ^^^^^^^^^^ point_sets: point set, or sequence of point sets, optional The point sets to visualize. point_set_colors: list of RGB colors, optional Colors for the N geometries. See help(matplotlib.colors) for specification. Defaults to the Glasbey series of categorical colors. point_set_opacities: list of floats, optional, default: [0.5,]*n Opacity for the point sets, in the range (0.0, 1.0]. point_set_representations: list of strings, optional, default: ['points',]*n How to represent the point set. One of 'hidden', 'points', or 'spheres'. Geometries ^^^^^^^^^^ geometries: geometries, or sequence of geometries, optional The geometries to visualize. geometry_colors: list of RGB colors, optional Colors for the N geometries. See help(matplotlib.colors) for specification. Defaults to the Glasbey series of categorical colors. geometry_opacities: list of floats, optional, default: [1.0,]*n Opacity for the point sets, in the range (0.0, 1.0]. Other Parameters ---------------- units: string, optional, default: '' Units to display in the scale bar. actors: vtkActor, vtkAssembly, vtkVolume, optional, default: None List of standard vtk objects, colors are extracted from their properties size_limit_2d: 2x1 numpy int64 array, optional, default: [1024, 1024] Size limit for 2D image visualization. If the roi is larger than this size, it will be downsampled for visualization size_limit_3d: 3x1 numpy int64 array, optional, default: [192, 192, 192] Size limit for 3D image visualization. If the roi is larger than this size, it will be downsampled for visualization. Returns ------- viewer : ipywidget Display by placing at the end of a Jupyter cell or calling IPython.display.display. Query or set properties on the object to change the visualization or retrieve values created by interacting with the widget. """ # this block allows the user to pass already formed vtkActor vtkVolume # objects actors = kwargs.pop("actors", None) if have_vtk and actors is not None: if not isinstance(actors, (list, tuple) ): # passing the object directly, so make it a list actors = [actors] images = [] for a in actors: if have_mayavi: from mayavi.modules import surface from mayavi.modules import iso_surface from tvtk.api import tvtk if isinstance(a, surface.Surface): a = tvtk.to_vtk(a.actor.actor) elif isinstance(a, iso_surface.IsoSurface): a = tvtk.to_vtk(a.actor.actor) if isinstance(a, vtk.vtkAssembly): # unpack assemblies cl = vtk.vtkPropCollection() a.GetActors(cl) cl.InitTraversal() for i in range(a.GetNumberOfPaths()): ac = vtk.vtkActor.SafeDownCast(cl.GetNextProp()) apoly = ac.GetMapper().GetInput() prop = ac.GetProperty() transform = vtk.vtkTransform() transform.SetMatrix(ac.GetMatrix()) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) tp.SetInputData(apoly) tp.Update() poly = tp.GetOutput() if poly.GetNumberOfPolys(): geometries.insert(0, poly) geometry_colors.insert(0, prop.GetColor()) geometry_opacities.insert(0, prop.GetOpacity()) else: point_sets.insert(0, poly) point_set_colors.insert(0, prop.GetColor()) point_set_opacities.insert(0, prop.GetOpacity()) elif isinstance(a, vtk.vtkActor): apoly = a.GetMapper().GetInput() transform = vtk.vtkTransform() transform.SetMatrix(a.GetMatrix()) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) tp.SetInputData(apoly) tp.Update() poly = tp.GetOutput() prop = a.GetProperty() if poly.GetNumberOfPolys() or poly.GetNumberOfStrips() or poly.GetNumberOfLines(): geometries.insert(0, poly) geometry_colors.insert(0, prop.GetColor()) geometry_opacities.insert(0, prop.GetOpacity()) else: point_sets.insert(0, poly) point_set_colors.insert(0, prop.GetColor()) point_set_opacities.insert(0, prop.GetOpacity()) elif isinstance(a, vtk.vtkVolume): images.append(a.GetMapper().GetInput()) if image is None and len(images): # only one image is rendered image = images[0] viewer = Viewer(image=image, cmap=cmap, select_roi=select_roi, interpolation=interpolation, gradient_opacity=gradient_opacity, slicing_planes=slicing_planes, shadow=shadow, blend=blend, point_sets=point_sets, point_set_colors=point_set_colors, point_set_opacities=point_set_opacities, point_set_representations=point_set_representations, geometries=geometries, geometry_colors=geometry_colors, geometry_opacities=geometry_opacities, rotate=rotate, ui_collapsed=ui_collapsed, annotations=annotations, mode=mode, **kwargs) return viewer