def add_mesh(T, V, **kwargs): pd = numpy_to_vtkPolyData(T, V) pd_normals = vtk.vtkPolyDataNormals() pd_normals.SetInput(pd) pd_normals.ComputeCellNormalsOn() pd_normals.SetFeatureAngle(90.) pd_depth = vtk.vtkDepthSortPolyData() pd_depth.SetInputConnection(pd_normals.GetOutputPort()) pd_depth.SetCamera(ren.GetActiveCamera()) pd_depth.SetDirectionToBackToFront() pd_depth._input = pd_normals mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(pd_depth.GetOutputPort()) mapper._input = pd_depth actor = vtk.vtkActor() actor.SetMapper(mapper) actor_property = actor.GetProperty() for prop, args in kwargs.iteritems(): method = getattr(actor_property, 'Set' + prop) method(*args) ren.AddActor(actor)
def __init__(self, renwin, data, isovalue, color=(0, 0.5, 0.75), rendering_type='surface'): self.renwin = renwin self.data = data self.iren = renwin.GetInteractor() self.renderer = renwin.GetRenderers().GetFirstRenderer() self.camera = self.renderer.GetActiveCamera() self.rendering_type = rendering_type # Among 'surface', 'wireframe', 'points' self.iso = vtk.vtkMarchingContourFilter() self.iso.UseScalarTreeOn() self.iso.ComputeNormalsOn() if vtk.vtkVersion.GetVTKMajorVersion() < 6: self.iso.SetInput(self.data) else: self.iso.SetInputData(self.data) self.iso.SetValue(0, isovalue) depthSort = vtk.vtkDepthSortPolyData() depthSort.SetInputConnection(self.iso.GetOutputPort()) depthSort.SetDirectionToBackToFront() depthSort.SetVector(1, 1, 1) depthSort.SetCamera(self.camera) depthSort.SortScalarsOn() depthSort.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(depthSort.GetOutputPort()) mapper.ScalarVisibilityOff() mapper.Update() self.surf = vtk.vtkActor() self.surf.SetMapper(mapper) self.surf.GetProperty().SetColor(color) self.surf.PickableOff() if self.rendering_type == 'wireframe': self.surf.GetProperty().SetRepresentationToWireframe() elif self.rendering_type == 'surface': self.surf.GetProperty().SetRepresentationToSurface() elif self.rendering_type == 'points': self.surf.GetProperty().SetRepresentationToPoints() self.surf.GetProperty().SetPointSize(5) else: self.surf.GetProperty().SetRepresentationToWireframe() self.surf.GetProperty().SetInterpolationToGouraud() self.surf.GetProperty().SetSpecular(.4) self.surf.GetProperty().SetSpecularPower(10) self.renderer.AddActor(self.surf) self.renwin.Render()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkDepthSortPolyData(), 'Processing.', ('vtkPolyData', ), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def draw_isosurface(self, data, rendtype, opacity, origin, spacing): self.image = self.array_to_3d_imagedata(data, spacing) isovalue = data.mean() mi, ma = data.min(), data.max() self.iso = vtk.vtkMarchingContourFilter() self.iso.UseScalarTreeOn() self.iso.ComputeNormalsOn() if vtk.vtkVersion.GetVTKMajorVersion()<6: self.iso.SetInput(self.image) else: self.iso.SetInputData(self.image) self.iso.SetValue(0,isovalue) self.depthSort = vtk.vtkDepthSortPolyData() self.depthSort.SetInputConnection(self.iso.GetOutputPort()) self.depthSort.SetDirectionToBackToFront() self.depthSort.SetVector(1, 1, 1) self.depthSort.SetCamera(self.camera) self.depthSort.SortScalarsOn() self.depthSort.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self.depthSort.GetOutputPort()) mapper.ScalarVisibilityOff() mapper.Update() self.surface = vtk.vtkActor() self.surface.SetMapper(mapper) self.surface.GetProperty().SetColor((0,0.5,0.75)) self.surface.GetProperty().SetOpacity(opacity) self.surface.PickableOff() if rendtype=='wireframe': self.surface.GetProperty().SetRepresentationToWireframe() elif rendtype=='surface': self.surface.GetProperty().SetRepresentationToSurface() elif rendtype=='points': self.surface.GetProperty().SetRepresentationToPoints() self.surface.GetProperty().SetPointSize(5) else: self.surface.GetProperty().SetRepresentationToWireframe() self.surface.GetProperty().SetInterpolationToGouraud() self.surface.GetProperty().SetSpecular(.4) self.surface.GetProperty().SetSpecularPower(10) self.renderer.AddActor(self.surface) self.surface.SetPosition(origin[0], origin[1], origin[2]) self.iren.Render() return mi, ma
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkDepthSortPolyData(), "Processing.", ("vtkPolyData",), ("vtkPolyData",), replaceDoc=True, inputFunctions=None, outputFunctions=None, )
def __init__(self, vtk_renderer, vtkish_polydata=None): vtkPolyDataPipeline.__init__(self, vtkish_polydata) # The depht sort object is set up to generate scalars representing # the sort depth. A camera is assigned for the sorting. The camera # defines the sort vector (position and focal point). vtk_ds = vtkDepthSortPolyData() vtk_ds.SetCamera(vtk_renderer.GetActiveCamera()) vtk_ds.SetDirectionToBackToFront() #vtk_ds.SetVector(1, 1, 1) #vtk_ds.SortScalarsOn() #vtk_ds.Update() self.append(vtk_ds) vtk_renderer.ResetCamera()
def __init__(self, data, cell, vtk_renderer, contours=1, depthsort=True): #TODO don't require vtk_renderer... implement vtkScene #TODO contour values from list or autocontours if int # Make sure data argument is a valid array if not isinstance(data, np.ndarray): data = np.array(data) vtkVolumeGrid.__init__(self, data.shape, cell) self.vtk_iso = vtkContourFilter() #vtkMarchingContourFilter? self.vtk_iso.SetInput( self.get_structured_points()) #TODO non-orthogonal self.vtk_iso.SetValue(0, 0.25) self.vtk_iso.SetValue(1, -0.25) self.smoothpipe = vtkSurfaceSmootherPipeline(self, vtk_iso) #TODO use vtkDepthSortPipeline - but vtkPolyDataModule isn't a pipeline self.depthsort = depthsort if self.depthsort: # The depht sort object is set up to generate scalars representing # the sort depth. A camera is assigned for the sorting. The camera # defines the sort vector (position and focal point). self.vtk_ds = vtkDepthSortPolyData() self.vtk_ds.SetCamera(vtk_renderer.GetActiveCamera()) self.vtk_ds.SetInputConnection(self.vtk_iso.GetOutputPort()) self.vtk_ds.SetDirectionToBackToFront() #vtk_ds.SetVector(1, 1, 1) #vtk_ds.SortScalarsOn() #vtk_ds.Update() vtk_renderer.ResetCamera() vtkPolyDataModule.__init__(self, self.vtk_ds) else: vtkPolyDataModule.__init__(self, self.vtk_iso) #TODO add color function """
def __init__(self, data, cell, vtk_renderer, contours=1, depthsort=True): #TODO don't require vtk_renderer... implement vtkScene #TODO contour values from list or autocontours if int # Make sure data argument is a valid array if not isinstance(data, np.ndarray): data = np.array(data) vtkVolumeGrid.__init__(self, data.shape, cell) self.vtk_iso = vtkContourFilter() #vtkMarchingContourFilter? self.vtk_iso.SetInput(self.get_structured_points()) #TODO non-orthogonal self.vtk_iso.SetValue(0, 0.25) self.vtk_iso.SetValue(1, -0.25) self.smoothpipe = vtkSurfaceSmootherPipeline(self, vtk_iso) #TODO use vtkDepthSortPipeline - but vtkPolyDataModule isn't a pipeline self.depthsort = depthsort if self.depthsort: # The depht sort object is set up to generate scalars representing # the sort depth. A camera is assigned for the sorting. The camera # defines the sort vector (position and focal point). self.vtk_ds = vtkDepthSortPolyData() self.vtk_ds.SetCamera(vtk_renderer.GetActiveCamera()) self.vtk_ds.SetInputConnection(self.vtk_iso.GetOutputPort()) self.vtk_ds.SetDirectionToBackToFront() #vtk_ds.SetVector(1, 1, 1) #vtk_ds.SortScalarsOn() #vtk_ds.Update() vtk_renderer.ResetCamera() vtkPolyDataModule.__init__(self, self.vtk_ds) else: vtkPolyDataModule.__init__(self, self.vtk_iso) #TODO add color function """
sphere4.SetThetaResolution(80) sphere4.SetPhiResolution(40) sphere4.SetRadius(0.5) sphere4.SetCenter(0,1,0) sphere5 = vtk.vtkSphereSource() sphere5.SetThetaResolution(80) sphere5.SetPhiResolution(40) sphere5.SetRadius(0.5) sphere5.SetCenter(0,-1,0) appendData = vtk.vtkAppendPolyData() appendData.AddInputConnection(sphere.GetOutputPort()) appendData.AddInputConnection(sphere2.GetOutputPort()) appendData.AddInputConnection(sphere3.GetOutputPort()) appendData.AddInputConnection(sphere4.GetOutputPort()) appendData.AddInputConnection(sphere5.GetOutputPort()) depthSort = vtk.vtkDepthSortPolyData() depthSort.SetInputConnection(appendData.GetOutputPort()) depthSort.SetDirectionToBackToFront() depthSort.SetVector(1,1,1) depthSort.SetCamera(camera) depthSort.SortScalarsOn() depthSort.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(depthSort.GetOutputPort()) mapper.SetScalarRange(0,depthSort.GetOutput().GetNumberOfCells()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(0.5) actor.GetProperty().SetColor(1,0,0) actor.RotateX(-72) depthSort.SetProp3D(actor)
sphere4.SetThetaResolution(80) sphere4.SetPhiResolution(40) sphere4.SetRadius(0.5) sphere4.SetCenter(0, 1, 0) sphere5 = vtk.vtkSphereSource() sphere5.SetThetaResolution(80) sphere5.SetPhiResolution(40) sphere5.SetRadius(0.5) sphere5.SetCenter(0, -1, 0) appendData = vtk.vtkAppendPolyData() appendData.AddInputConnection(sphere.GetOutputPort()) appendData.AddInputConnection(sphere2.GetOutputPort()) appendData.AddInputConnection(sphere3.GetOutputPort()) appendData.AddInputConnection(sphere4.GetOutputPort()) appendData.AddInputConnection(sphere5.GetOutputPort()) depthSort = vtk.vtkDepthSortPolyData() depthSort.SetInputConnection(appendData.GetOutputPort()) depthSort.SetDirectionToBackToFront() depthSort.SetVector(1, 1, 1) depthSort.SetCamera(camera) depthSort.SortScalarsOn() depthSort.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(depthSort.GetOutputPort()) mapper.SetScalarRange(0, depthSort.GetOutput().GetNumberOfCells()) mapper.SetScalarVisibility(1) mapper.SelectColorArray("sortedCellIds") mapper.SetUseLookupTableScalarRange(0) mapper.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_FIELD_DATA) actor = vtk.vtkActor() actor.SetMapper(mapper)
def isosurface(self, data, isovalue, rendtype): self.data = data self.settings = wx.Panel(self) self.plot_type = self.type = 'isosurface' self.image = self.array_to_3d_imagedata() self.iso = vtk.vtkMarchingContourFilter() self.iso.UseScalarTreeOn() self.iso.ComputeNormalsOn() if vtk.vtkVersion.GetVTKMajorVersion()<6: self.iso.SetInput(self.image) else: self.iso.SetInputData(self.image) self.iso.SetValue(0,isovalue) depthSort = vtk.vtkDepthSortPolyData() depthSort.SetInputConnection(self.iso.GetOutputPort()) depthSort.SetDirectionToBackToFront() depthSort.SetVector(1, 1, 1) depthSort.SetCamera(self.camera) depthSort.SortScalarsOn() depthSort.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(depthSort.GetOutputPort()) mapper.ScalarVisibilityOff() mapper.Update() self.surf = vtk.vtkActor() self.surf.SetMapper(mapper) self.surf.GetProperty().SetColor((0,0.5,0.75)) self.surf.PickableOff() outline = vtk.vtkOutlineFilter() if vtk.vtkVersion.GetVTKMajorVersion()<6: outline.SetInput(self.image) else: outline.SetInputData(self.image) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) box=vtk.vtkActor() box.SetMapper( outlineMapper ) box.GetProperty().SetColor((0,0,0)) box.PickableOff() self.renderer.AddActor(box) if rendtype=='w': self.surf.GetProperty().SetRepresentationToWireframe() elif rendtype=='s': self.surf.GetProperty().SetRepresentationToSurface() elif rendtype=='p': self.surf.GetProperty().SetRepresentationToPoints() self.surf.GetProperty().SetPointSize(5) else: self.surf.GetProperty().SetRepresentationToWireframe() self.surf.GetProperty().SetInterpolationToGouraud() self.surf.GetProperty().SetSpecular(.4) self.surf.GetProperty().SetSpecularPower(10) self.renderer.AddActor(self.surf) self.build_axes() self.center_on_actor(self.surf, out=True) sb1 = wx.StaticBox(self.settings, wx.ID_ANY, label = "Contour Level") isovSizer = wx.StaticBoxSizer(sb1, wx.HORIZONTAL) self.isov_scale = 100. self.isov_slider = wx.Slider(self.settings, wx.ID_ANY, value = isovalue*self.isov_scale , minValue = int(self.data.min()*self.isov_scale) , maxValue = int(self.data.max()*self.isov_scale), size = (60,27), style = wx.SL_HORIZONTAL) self.isov_slider.Bind(wx.EVT_SCROLL,self.on_change_isov) isovSizer.Add(self.isov_slider, 1, wx.ALIGN_CENTER_VERTICAL, 0) rendSizer = wx.BoxSizer() self.rendlist_label = wx.StaticText(self.settings, label="Rendering mode") self.rendlist = wx.ComboBox(self.settings, id = wx.ID_ANY, choices=["surface","wireframe", "points"], style=wx.CB_READONLY) self.rendlist.SetValue("wireframe") self.rendlist.Bind(wx.EVT_COMBOBOX, self.on_change_surf_rend_mode) self.opacity_label = wx.StaticText(self.settings, label="Opacity level [0-1]") self.opacity = wx.TextCtrl(self.settings, wx.ID_ANY, style= wx.SL_HORIZONTAL|wx.TE_PROCESS_ENTER) self.opacity.SetValue(str(1.0)) self.opacity.Bind(wx.EVT_TEXT_ENTER, self.on_set_opacity) rendSizer.Add(self.rendlist_label, 0, wx.ALIGN_CENTER_VERTICAL, 0) rendSizer.Add(self.rendlist, 0, wx.ALIGN_CENTER_VERTICAL, 0) rendSizer.Add(self.opacity_label, 0, wx.ALIGN_CENTER_VERTICAL, 0) rendSizer.Add(self.opacity, 0, wx.ALIGN_CENTER_VERTICAL, 0) sb = wx.StaticBox(self.settings, wx.ID_ANY, label = "Slice orientation") sliceSizer = wx.StaticBoxSizer(sb, wx.HORIZONTAL) self.sagittal = wx.RadioButton(self.settings, wx.ID_ANY, label = "sagittal (// to Y,Z)") self.axial = wx.RadioButton(self.settings, wx.ID_ANY, label = "axial (// to X,Y)") self.coronal = wx.RadioButton(self.settings, wx.ID_ANY, label = "coronal (// to X,Z)") self.oblique = wx.RadioButton(self.settings, wx.ID_ANY, label = "oblique (// to X,Y+Z)") self.Bind(wx.EVT_RADIOBUTTON, self.on_slice_selection, self.sagittal) self.Bind(wx.EVT_RADIOBUTTON, self.on_slice_selection, self.axial) self.Bind(wx.EVT_RADIOBUTTON, self.on_slice_selection, self.coronal) self.Bind(wx.EVT_RADIOBUTTON, self.on_slice_selection, self.oblique) sliceSizer.Add(self.sagittal, 1, wx.ALIGN_CENTER_VERTICAL, 0) sliceSizer.Add(self.axial, 1, wx.ALIGN_CENTER_VERTICAL, 0) sliceSizer.Add(self.coronal, 1, wx.ALIGN_CENTER_VERTICAL, 0) sliceSizer.Add(self.oblique, 1, wx.ALIGN_CENTER_VERTICAL, 0) self.iren.AddObserver("CharEvent", self.on_keyboard_input) self.reslice = None key_doc = wx.StaticText(self.settings, wx.ID_ANY, label = "Press '+' and '-' keys to translate the slice") self.save_fig = wx.Button(self.settings, wx.ID_ANY, label="Save current view") self.save_fig.Bind(wx.EVT_BUTTON, self.Screen_shot) Sizer = wx.BoxSizer(wx.VERTICAL) Sizer.Add(rendSizer, 0, wx.EXPAND, 0) Sizer.Add(isovSizer, 0, wx.EXPAND, 0) Sizer.Add(sliceSizer, 0, wx.EXPAND, 0) Sizer.Add(key_doc, 0, wx.EXPAND, 0) Sizer.Add(self.save_fig, 0, wx.EXPAND, 0) self.iren.Render() self.settings.SetSizer(Sizer) Sizer.Fit(self.settings) self.settings.Layout() self._mgr.AddPane(self.settings, wxaui.AuiPaneInfo().Center().Dock().Bottom().CloseButton(False).CaptionVisible(False)) self._mgr.Update()
def surface(T, P, use_normals=True, camera=None, face_colours=None, face_label_function_and_lut=None): poly_data = vtk.vtkPolyData() poly_data.SetPoints(make_vtkPoints(P)) poly_data.SetPolys(make_vtkCellArray(T)) mapper = vtk.vtkPolyDataMapper() # `colour_faces_filter` is empty by default. colour_faces_filter = None if face_colours is not None: assert len(face_colours) == poly_data.GetNumberOfPolys() # Build `lut`. npy_face_colours = np.require(np.atleast_2d(face_colours), np.float64) face_colours = map(tuple, face_colours) unique_colours = sorted(set(face_colours)) num_unique_colours = len(unique_colours) lut = make_vtkLookupTable(unique_colours) mapper.SetLookupTable(lut) # Set `lookup_indices`. B = npy_face_colours[:, np.newaxis, :] == unique_colours i, j = np.nonzero(np.all(B, axis=2)) lookup_indices = np.empty(len(face_colours), dtype=j.dtype) lookup_indices[i] = j # Set `lookup`. vtk_lookup = vtk.vtkFloatArray() vtk_lookup.SetNumberOfValues(len(face_colours)) lookup = vtk_to_numpy(vtk_lookup) lookup[:] = lookup_indices.astype(np.float64) / num_unique_colours poly_data.GetCellData().SetScalars(vtk_lookup) elif face_label_function_and_lut is not None: label_function, lut = face_label_function_and_lut # Set `lut` for the mapper. lut = make_vtkLookupTable(lut) mapper.SetLookupTable(lut) # Initialise `colour_faces_filter`. colour_faces_filter = make_colour_faces_filter(label_function) pipeline = [poly_data] def add_to_pipeline(to): from_ = pipeline[-1] if hasattr(from_, 'GetOutputPort'): to.SetInputConnection(from_.GetOutputPort()) else: _SetInput_or_SetInputData(to, from_) pipeline.append(to) if colour_faces_filter is not None: add_to_pipeline(colour_faces_filter) if camera is not None: poly_data_depth = vtk.vtkDepthSortPolyData() poly_data_depth.SetCamera(camera) poly_data_depth.SetDirectionToBackToFront() poly_data_depth.SetDepthSortModeToBoundsCenter() add_to_pipeline(poly_data_depth) if use_normals: normals = vtk.vtkPolyDataNormals() add_to_pipeline(normals) add_to_pipeline(mapper) actor = vtk.vtkActor() actor.SetMapper(mapper) actor._locals = locals() return actor
def main(argc, argv): if (argc != 7): print("Usage: " + argv[0] + " Theta Phi MaximumPeels " + "OcclusionRatio ForceDepthSortingFlag " + "DoNotUseAnyDepthRelatedAlgorithmFlag" + "\n") print("100 100 50 0.1 0 0") return -1 colors = vtk.vtkNamedColors() theta = int(argv[1]) phi = int(argv[2]) maxPeels = int(argv[3]) occulusionRatio = float(argv[4]) forceDepthSort = int(argv[5]) == 1 withoutAnyDepthThings = (argv[6]) == 1 # Generate a translucent sphere poly data set that partially overlaps: translucentGeometry = GenerateOverlappingBunchOfSpheres(theta, phi) # generate a basic Mapper and Actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(translucentGeometry.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(0.5) # translucent !!! actor.GetProperty().SetColor(colors.GetColor3d("Crimson")) actor.RotateX(-72) # put the objects in a position where it is easy to see # different overlapping regions # Create the RenderWindow, Renderer and RenderWindowInteractor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(600, 400) renderWindow.AddRenderer(renderer) renderWindow.SetWindowName("CorrectlyRenderTranslucentGeometry") renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the renderer, set the background and size renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d("SlateGray")) # Setup view geometry renderer.ResetCamera() renderer.GetActiveCamera().Zoom(2.2) # so the object is larger renderWindow.Render() # Answer the key question: Does this box support GPU Depth Peeling? useDepthPeeling = IsDepthPeelingSupported(renderWindow, renderer, True) print("DEPTH PEELING SUPPORT: " + {1: "YES", 0: "NO"}[useDepthPeeling]) success = 0 # Use depth peeling if available and not explicitly prohibited, otherwise we # use manual depth sorting print("\n" + "CHOSEN MODE: ") if (useDepthPeeling and ~forceDepthSort and ~withoutAnyDepthThings): # GPU print("*** DEPTH PEELING ***") # Setup GPU depth peeling with configured parameters success = ~SetupEnvironmentForDepthPeeling(renderWindow, renderer, maxPeels, occulusionRatio) elif (~withoutAnyDepthThings): print("*** DEPTH SORTING ***") # Setup CPU depth sorting filter depthSort = vtk.vtkDepthSortPolyData() depthSort.SetInputConnection(translucentGeometry.GetOutputPort()) depthSort.SetDirectionToBackToFront() depthSort.SetVector(1, 1, 1) depthSort.SetCamera(renderer.GetActiveCamera()) depthSort.SortScalarsOff() # do not really need this here # Bring it to the mapper's input mapper.SetInputConnection(depthSort.GetOutputPort()) depthSort.Update() else: print("*** NEITHER DEPTH PEELING NOR DEPTH SORTING ***") # Initialize interaction renderWindowInteractor.Initialize() # Check the average frame rate when rotating the actor endCount = 100 clock = vtk.vtkTimerLog() # Set a user transform for successively rotating the camera position transform = vtk.vtkTransform() transform.Identity() transform.RotateY(2.0) # rotate 2 degrees around Y-axis at each iteration camera = renderer.GetActiveCamera() # Start test clock.StartTimer() for i in range(endCount): camPos = camera.GetPosition() camPos = transform.TransformPoint(camPos) camera.SetPosition(camPos) renderWindow.Render() clock.StopTimer() frameRate = endCount / clock.GetElapsedTime() print("AVERAGE FRAME RATE: " + str(frameRate) + " fps") # Start interaction renderWindowInteractor.Start() return success