def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkOutlineSource(), 'Processing.', (), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self, atoms): assert isinstance(atoms, Atoms) self.pbc = atoms.get_pbc() cell = atoms.get_cell() """ if not isinstance(cell, np.ndarray): cell = np.array(cell) if cell.shape == (3,): cell = np.diag(cell) assert cell.dtype == float and cell.shape == (3, 3) """ self.vtk_outline = vtkOutlineSource() if (cell - np.diag(cell.diagonal())).any(): corners = np.empty((8, 3), dtype=float) # edges = [map(int,[(i-1)%2==0,i%4>=2,i>=4]) for i in range(8)] for c,a in enumerate([(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), \ (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1)]): corners[c] = np.dot(a, cell) self.bbox = np.array(zip(np.min(corners, axis=0), \ np.max(corners, axis=0))).ravel() self.vtk_outline.SetCorners(corners.ravel()) self.vtk_outline.SetBoxTypeToOriented() else: self.bbox = np.array(zip(np.zeros(3), cell.diagonal())).ravel() self.vtk_outline.SetBounds(self.bbox) vtkPolyDataModule.__init__(self, self.vtk_outline)
def __init__(self, atoms): assert isinstance(atoms, Atoms) self.pbc = atoms.get_pbc() cell = atoms.get_cell() """ if not isinstance(cell, np.ndarray): cell = np.array(cell) if cell.shape == (3,): cell = np.diag(cell) assert cell.dtype == float and cell.shape == (3, 3) """ self.vtk_outline = vtkOutlineSource() if (cell - np.diag(cell.diagonal())).any(): corners = np.empty((8,3), dtype=float) # edges = [map(int,[(i-1)%2==0,i%4>=2,i>=4]) for i in range(8)] for c,a in enumerate([(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), \ (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1)]): corners[c] = np.dot(a, cell) self.bbox = np.array(list(zip(np.min(corners, axis=0), \ np.max(corners, axis=0)))).ravel() self.vtk_outline.SetCorners(corners.ravel()) self.vtk_outline.SetBoxTypeToOriented() else: self.bbox = np.array(list(zip(np.zeros(3),cell.diagonal()))).ravel() self.vtk_outline.SetBounds(self.bbox) vtkPolyDataModule.__init__(self, self.vtk_outline)
def __init__(self, atoms): assert isinstance(atoms, Atoms) cell = atoms.get_cell() """ if not isinstance(cell, np.ndarray): cell = np.array(cell) if cell.shape == (3,): cell = np.diag(cell) assert cell.dtype == float and cell.shape == (3, 3) """ #TODO bounding box with general unit cell diagcell = np.diag(cell.diagonal()) assert (cell == diagcell).all(), 'Unit cell must be orthogonal' self.bbox = np.array(zip(np.zeros(3),cell.diagonal())).ravel() self.pbc = atoms.get_pbc() self.vtk_outline = vtkOutlineSource() self.vtk_outline.SetBounds(self.bbox) vtkPolyDataModule.__init__(self, self.vtk_outline)
def __init__(self, ren): self.ren = ren self.source = vtk.vtkOutlineSource() self.mapper = vtk.vtkPolyDataMapper() self.actor = vtk.vtkActor() self.visible = 0 self.currentColour = (0, 0, 0)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkOutlineSource(), 'Processing.', (), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def renderBounds(self, bounds): ''' Render a box with boundaries from the given input :param bounds: Tuple holding max/min axes values ''' cube = vtk.vtkOutlineSource() cube.SetBounds(bounds) cube.Update() cubeMapper = vtk.vtkPolyDataMapper() cubeMapper.SetInputConnection(cube.GetOutputPort()) cubeActor = vtk.vtkActor() cubeActor.SetMapper(cubeMapper) cubeActor.GetProperty().SetColor(0.6, 0, 0) self.ren.AddActor(cubeActor) return cube
def CreateOutline(bounds, color=None): squareSource = vtkOutlineSource() squareSource.GenerateFacesOff() squareSource.SetBounds(bounds) squareMapper = vtkPolyDataMapper() squareMapper.SetInputConnection(squareSource.GetOutputPort()) square = vtkActor() square.PickableOff() square.SetMapper(squareMapper) square.GetProperty().SetColor(1.0, 1.0, 1.0) ColorActor(square, color) return square
def CreateSquare(width, color=None, zOffset=0): halfWidth = width / 2.0 squareSource = vtkOutlineSource() squareSource.GenerateFacesOff() squareSource.SetBounds(-halfWidth, halfWidth, -halfWidth, halfWidth, zOffset, zOffset) squareMapper = vtkPolyDataMapper() squareMapper.SetInputConnection(squareSource.GetOutputPort()) square = vtkActor() square.PickableOff() square.SetMapper(squareMapper) square.GetProperty().SetColor(1.0, 0.5, 0.5) ColorActor(square, color) return square
def __init__(self): vtkPythonInteractorObserver.__init__(self) # Keep track of current state self.State = self.VTKIS_NONE self.AnimState = self.VTKIS_ANIM_OFF # Should observers be handled here, should we fire timers self.HandleObservers = 1 self.UseTimers = 0 self.TimerId = 1# keep track of the timers that are created/destroyed self.AutoAdjustCameraClippingRange = 1 self.Interactor = None self.EventCallbackCommand = lambda obj, event: self.ProcessEvents(obj, event, self, None) # These widgets are not activated with a key self.KeyPressActivation = 0 # For picking and highlighting props self.Outline = vtk.vtkOutlineSource() self.OutlineMapper = vtk.vtkPolyDataMapper() self.OutlineActor = None self.OutlineMapper.SetInput(self.Outline.GetOutput()) self.PickedRenderer = None self.CurrentProp = None self.PickedActor2D = None # bool: prop picked? self.PropPicked = 0 # support 2D picking self.PickColor = [1.0, 0.0, 0.0] self.MouseWheelMotionFactor = 1.0 # Control the timer duration in milliseconds self.TimerDuration = 10 # Forward evets to the RenderWindowInteractor self.EventForwarder = None
def set_initial_display(self): if self.renwininter is None: self.renwininter = MEQ_QVTKRenderWindowInteractor(self.winsplitter) self.renwininter.setWhatsThis(rendering_control_instructions) self.renwin = self.renwininter.GetRenderWindow() self.inter = self.renwin.GetInteractor() self.winsplitter.insertWidget(0, self.renwininter) self.winsplitter.addWidget(self.v_box_controls) self.winsplitter.setSizes([500, 100]) self.renwininter.show() # Paul Kemper suggested the following: camstyle = vtk.vtkInteractorStyleTrackballCamera() self.renwininter.SetInteractorStyle(camstyle) self.extents = self.image_array.GetDataExtent() self.spacing = self.image_array.GetDataSpacing() self.origin = self.image_array.GetDataOrigin() # An outline is shown for context. if self.warped_surface: self.index_selector.initWarpContextmenu() sx, sy, sz = self.image_array.GetDataSpacing() xMin, xMax, yMin, yMax, zMin, zMax = self.image_array.GetDataExtent( ) xMin = sx * xMin xMax = sx * xMax yMin = sy * yMin yMax = sy * yMax self.scale_factor = 0.5 * ( (xMax - xMin) + (yMax - yMin)) / (self.data_max - self.data_min) zMin = self.data_min * self.scale_factor zMax = self.data_max * self.scale_factor self.outline = vtk.vtkOutlineSource() self.outline.SetBounds(xMin, xMax, yMin, yMax, zMin, zMax) else: self.index_selector.init3DContextmenu() self.outline = vtk.vtkOutlineFilter() self.outline.SetInput(self.image_array.GetOutput()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInput(self.outline.GetOutput()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) # create blue to red color table self.lut = vtk.vtkLookupTable() self.lut.SetHueRange(0.6667, 0.0) self.lut.SetNumberOfColors(256) self.lut.Build() # here is where the 2-D image gets warped if self.warped_surface: geometry = vtk.vtkImageDataGeometryFilter() geometry.SetInput(self.image_array.GetOutput()) self.warp = vtk.vtkWarpScalar() self.warp.SetInput(geometry.GetOutput()) self.warp.SetScaleFactor(self.scale_factor) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInput(self.warp.GetPolyDataOutput()) self.mapper.SetScalarRange(self.data_min, self.data_max) self.mapper.SetLookupTable(self.lut) self.mapper.ImmediateModeRenderingOff() warp_actor = vtk.vtkActor() # warp_actor.SetScale(2,1,1) warp_actor.SetMapper(self.mapper) min_range = 0.5 * self.scale_factor max_range = 2.0 * self.scale_factor self.index_selector.set_emit(False) self.index_selector.setMaxValue(max_range, False) self.index_selector.setMinValue(min_range) self.index_selector.setTickInterval((max_range - min_range) / 10) self.index_selector.setRange(max_range, False) self.index_selector.setValue(self.scale_factor) self.index_selector.setLabel('display gain') self.index_selector.hideNDControllerOption() self.index_selector.reset_scale_toggle() self.index_selector.set_emit(True) else: # set up ImagePlaneWidgets ... # The shared picker enables us to use 3 planes at one time # and gets the picking order right picker = vtk.vtkCellPicker() picker.SetTolerance(0.005) # get locations for initial slices xMin, xMax, yMin, yMax, zMin, zMax = self.extents x_index = (xMax - xMin) / 2 y_index = (yMax - yMin) / 2 z_index = (zMax - zMin) / 2 # The 3 image plane widgets are used to probe the dataset. self.planeWidgetX = vtk.vtkImagePlaneWidget() self.planeWidgetX.DisplayTextOn() self.planeWidgetX.SetInput(self.image_array.GetOutput()) self.planeWidgetX.SetPlaneOrientationToXAxes() self.planeWidgetX.SetSliceIndex(x_index) self.planeWidgetX.SetPicker(picker) self.planeWidgetX.SetKeyPressActivationValue("x") self.planeWidgetX.SetLookupTable(self.lut) self.planeWidgetX.TextureInterpolateOff() self.planeWidgetX.SetResliceInterpolate(0) self.planeWidgetY = vtk.vtkImagePlaneWidget() self.planeWidgetY.DisplayTextOn() self.planeWidgetY.SetInput(self.image_array.GetOutput()) self.planeWidgetY.SetPlaneOrientationToYAxes() self.planeWidgetY.SetSliceIndex(y_index) self.planeWidgetY.SetPicker(picker) self.planeWidgetY.SetKeyPressActivationValue("y") self.planeWidgetY.SetLookupTable( self.planeWidgetX.GetLookupTable()) self.planeWidgetY.TextureInterpolateOff() self.planeWidgetY.SetResliceInterpolate(0) self.planeWidgetZ = vtk.vtkImagePlaneWidget() self.planeWidgetZ.DisplayTextOn() self.planeWidgetZ.SetInput(self.image_array.GetOutput()) self.planeWidgetZ.SetPlaneOrientationToZAxes() self.planeWidgetZ.SetSliceIndex(z_index) self.planeWidgetZ.SetPicker(picker) self.planeWidgetZ.SetKeyPressActivationValue("z") self.planeWidgetZ.SetLookupTable( self.planeWidgetX.GetLookupTable()) self.planeWidgetZ.TextureInterpolateOff() self.planeWidgetZ.SetResliceInterpolate(0) self.current_widget = self.planeWidgetZ self.mode_widget = self.planeWidgetZ self.index_selector.set_emit(False) self.index_selector.setMinValue(zMin) self.index_selector.setMaxValue(zMax, False) self.index_selector.setTickInterval((zMax - zMin) / 10) self.index_selector.setRange(zMax, False) self.index_selector.setValue(z_index) self.index_selector.setLabel('Z axis') self.index_selector.reset_scale_toggle() self.index_selector.set_emit(True) # create scalar bar for display of intensity range self.scalar_bar = vtk.vtkScalarBarActor() self.scalar_bar.SetLookupTable(self.lut) self.scalar_bar.SetOrientationToVertical() self.scalar_bar.SetWidth(0.1) self.scalar_bar.SetHeight(0.8) self.scalar_bar.SetTitle("Intensity") self.scalar_bar.GetPositionCoordinate( ).SetCoordinateSystemToNormalizedViewport() self.scalar_bar.GetPositionCoordinate().SetValue(0.01, 0.1) # Create the RenderWindow and Renderer self.ren = vtk.vtkRenderer() self.renwin.AddRenderer(self.ren) # Add the outline actor to the renderer, set the background color and size if self.warped_surface: self.ren.AddActor(warp_actor) self.ren.AddActor(outlineActor) self.ren.SetBackground(0.1, 0.1, 0.2) self.ren.AddActor2D(self.scalar_bar) # Create a text property for cube axes tprop = vtk.vtkTextProperty() tprop.SetColor(1, 1, 1) tprop.ShadowOn() # Create a vtkCubeAxesActor2D. Use the outer edges of the bounding box to # draw the axes. Add the actor to the renderer. self.axes = vtk.vtkCubeAxesActor2D() if self.warped_surface: if zMin < 0.0 and zMax > 0.0: zLoc = 0.0 else: zLoc = zMin self.axes.SetBounds(xMin, xMax, yMin, yMax, zLoc, zLoc) self.axes.SetZLabel(" ") else: self.axes.SetInput(self.image_array.GetOutput()) self.axes.SetZLabel("Z") self.axes.SetCamera(self.ren.GetActiveCamera()) self.axes.SetLabelFormat("%6.4g") self.axes.SetFlyModeToOuterEdges() self.axes.SetFontFactor(0.8) self.axes.SetAxisTitleTextProperty(tprop) self.axes.SetAxisLabelTextProperty(tprop) self.axes.SetXLabel("X") self.axes.SetYLabel("Y") self.ren.AddProp(self.axes) # Set the interactor for the widgets if not self.warped_surface: self.planeWidgetX.SetInteractor(self.inter) self.planeWidgetX.On() self.planeWidgetY.SetInteractor(self.inter) self.planeWidgetY.On() self.planeWidgetZ.SetInteractor(self.inter) self.planeWidgetZ.On() self.initialize_camera()
def __init__(self, data_source, input_link): """Parallel coordinates view constructor needs a valid DataSource plus and external annotation link (from the icicle view). """ self.ds = data_source self.input_link = input_link # Set up callback to listen for changes in IcicleView selections self.input_link.AddObserver("AnnotationChangedEvent", self.InputSelectionCallback) # Set up an annotation link for other views to monitor selected image # This link will be created here, but used back and forth between this detail view # and the icicle view. It carries the current "scale" selected in both. self.output_link = vtk.vtkAnnotationLink() # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010) # See vtkSelectionNode doc for field and content type enum values self.output_link.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point # Here I'm outputting the "scale" of the selection, so I'm not sure it matters # whether output is index or other content type... self.output_link.GetCurrentSelection().GetNode(0).SetContentType(4) # 2 = PedigreeIds, 4 = Indices # Set up callback which will work either internally or triggered by change from icicle view. self.output_link.AddObserver("AnnotationChangedEvent", self.ScaleSelectionCallback) # Create a set of empty image stacks for use in empty selections # but use the dimensions of a "projected image" so scales match example_image = self.ds.GetProjectedImages([0]) example_image.UpdateInformation() (xMin, xMax, yMin, yMax, zMin, zMax) = example_image.GetWholeExtent() (xSpacing, ySpacing, zSpacing) = example_image.GetSpacing() (x0, y0, z0) = example_image.GetOrigin() blankR = xMax - xMin + 1 blankC = yMax - yMin + 1 numScales = len(self.ds.ScaleMaxDim) # Note: accessing member variable directly self.blank_image_list = [] self.blank_image_weights = [] self.numImagesList = [] nDim = 3 # 3-dim for now... for dd in range(numScales): images_linear = N.zeros( blankR*blankC*nDim, dtype='float') intensity = VN.numpy_to_vtk(images_linear, deep=True) intensity.SetName('PNGImage') imageData = vtk.vtkImageData() imageData.SetOrigin(x0, y0, z0) imageData.SetSpacing(xSpacing, ySpacing, zSpacing) imageData.SetExtent(xMin,xMax,yMin,yMax,0,nDim-1) imageData.GetPointData().AddArray(intensity) imageData.GetPointData().SetActiveScalars('PNGImage') self.blank_image_list.append(imageData) self.blank_image_weights.append(0.1*N.ones(nDim, dtype='float')) self.numImagesList.append(nDim) for dd in range(len(self.blank_image_list)): self.blank_image_list[dd].UpdateInformation() # Create a BrBg7 lookup table self.lut = self.ds.GetDivergingLUT('BrBg') self.colorList = [] self.resliceList = [] self.assemblyList = [] self.numScales = len(self.ds.ScaleMaxDim) # Note: accessing member variable self.expSpread = 0.5 self.renderer = vtk.vtkRenderer() self.cam = self.renderer.GetActiveCamera() # renderer.SetBackground(0.15, 0.12, 0.1) # cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [40,40,40]] cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [60, 60, 60]] self.renderer.SetBackground(cc0,cc1,cc2) self.highlightRect = vtk.vtkOutlineSource() self.highlightMapper = vtk.vtkPolyDataMapper() self.highlightMapper.SetInputConnection(self.highlightRect.GetOutputPort(0)) self.highlightActor = vtk.vtkActor() self.highlightActor.SetMapper(self.highlightMapper) self.highlightActor.GetProperty().SetColor(1,0.8,0.2) self.highlightActor.GetProperty().SetLineWidth(3.0) self.highlightActor.GetProperty().SetOpacity(0.6) # Setting as if nothing picked even though initialized position & orientation to actor0 self.highlightIndex = -1 self.highlightActor.SetPickable(False) self.highlightActor.SetVisibility(False) self.renderer.AddActor(self.highlightActor) # Create the slider which will control the image positions self.sliderRep = vtk.vtkSliderRepresentation2D() self.sliderRep.SetMinimumValue(0) self.sliderRep.SetMaximumValue(self.numScales-1) self.sliderRep.SetValue(0) # For remembering the previous slider setting when switching data sets self.prevSliderValue = int(self.numScales/2.0) # And need to keep track of whether to reset view self.needToResetCamera = True self.window = vtk.vtkRenderWindow() self.window.SetSize(600,300) self.window.AddRenderer(self.renderer) # Set up the interaction self.interactorStyle = vtk.vtkInteractorStyleImage() self.interactor = vtk.vtkRenderWindowInteractor() self.interactor.SetInteractorStyle(self.interactorStyle) self.window.SetInteractor(self.interactor) self.sliderWidget = vtk.vtkSliderWidget() self.sliderWidget.SetInteractor(self.interactor) self.sliderWidget.SetRepresentation(self.sliderRep) self.sliderWidget.SetAnimationModeToAnimate() self.sliderWidget.EnabledOn() self.sliderWidget.AddObserver("InteractionEvent", self.sliderCallback) self.sliderWidget.AddObserver("EndInteractionEvent", self.endSliderCallback) # Default flow direction Horizontal # Setting self.maxAngle in SetFlowDirection() self.FlowDirection = Direction.Vertical self.SetFlowDirection(self.FlowDirection) # Set up callback to toggle between inspect modes (manip axes & select data) # self.interactorStyle.AddObserver("SelectionChangedEvent", self.selectImage) # Create callbacks for mouse events self.mouseActions = {} self.mouseActions["LeftButtonDown"] = 0 self.mouseActions["Picking"] = 0 self.interactorStyle.AddObserver("MouseMoveEvent", self.MouseMoveCallback) self.interactorStyle.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback) self.interactorStyle.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback) # Done setting up all of the image stuff, so call selection callback # to set up view with blank images # self.input_link.InvokeEvent('AnnotationChangedEvent') self.InputSelectionCallback(self.input_link,None) self.cam.ParallelProjectionOn()
def __init__(self, data_source, input_link): """Parallel coordinates view constructor needs a valid DataSource plus and external annotation link (from the icicle view). """ self.ds = data_source self.input_link = input_link # Set up callback to listen for changes in IcicleView selections self.input_link.AddObserver("AnnotationChangedEvent", self.InputSelectionCallback) # Set up an annotation link for other views to monitor selected image self.output_link = vtk.vtkAnnotationLink() # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010) # See vtkSelectionNode doc for field and content type enum values self.output_link.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point # The chart seems to force INDEX selection, so I'm using vtkConvertSelection below to get # out PedigreeIds... self.output_link.GetCurrentSelection().GetNode(0).SetContentType(2) # 2 = PedigreeIds, 4 = Indices # Going to manually create output_link selection list, so not setting up callback for it... if os.path.isfile(os.path.abspath('BlankImage.png')): blank_file = 'BlankImage.png' else: # For use in app bundles blank_file = os.path.join(sys.path[0],'BlankImage.png') self.blankImageReader = vtk.vtkPNGReader() self.blankImageReader.SetFileName(blank_file) self.blankImageReader.Update() tmp = self.blankImageReader.GetOutput().GetBounds() self.flowSpacing = float(tmp[1]-tmp[0])*1.1 self.nupSpacing = float(tmp[3]-tmp[2])*1.1 # Create a blue-white-red lookup table self.lut = vtk.vtkLookupTable() lutNum = 256 self.lut.SetNumberOfTableValues(lutNum) ctf = vtk.vtkColorTransferFunction() ctf.SetColorSpaceToDiverging() c_blue = N.array([59,76,192],dtype='float')/255.0 # c_gray = [0.8, 0.8, 0.8] c_red = N.array([180,4,38],dtype='float')/255.0 ctf.AddRGBPoint(0.0, c_blue[0], c_blue[1], c_blue[2]) # blue # ctf.AddRGBPoint(0.5, c_gray[0], c_gray[1], c_gray[2]) # blue ctf.AddRGBPoint(1.0, c_red[0], c_red[1], c_red[2]) # red for ii,ss in enumerate([float(xx)/float(lutNum) for xx in range(lutNum)]): cc = ctf.GetColor(ss) self.lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0) self.lut.SetRange(-10,10) # Map the image through the lookup table self.color = vtk.vtkImageMapToColors() self.color.SetLookupTable(self.lut) self.color.SetInput(self.blankImageReader.GetOutput()) self.resliceList = [] self.actorList = [] self.numImages = 1 # Map between indices of images and their Pedigree ID self.pedigree_id_dict = {} blankImageActor = vtk.vtkImageActor() blankImageActor.SetInput(self.color.GetOutput()) blankImageActor.SetPickable(False) blankImageActor.SetOpacity(0.1) self.actorList.append(blankImageActor) self.expSpread = 0.5 self.maxAngle = 80.0 self.renderer = vtk.vtkRenderer() self.cam = self.renderer.GetActiveCamera() # renderer.SetBackground(0.15, 0.12, 0.1) cc = [68,57,53] cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in cc] self.renderer.SetBackground(cc0,cc1,cc2) self.renderer.AddActor(self.actorList[0]) self.highlightRect = vtk.vtkOutlineSource() self.highlightRect.SetBounds(self.actorList[0].GetBounds()) self.highlightMapper = vtk.vtkPolyDataMapper() self.highlightMapper.SetInputConnection(self.highlightRect.GetOutputPort(0)) self.highlightActor = vtk.vtkActor() self.highlightActor.SetMapper(self.highlightMapper) self.highlightActor.GetProperty().SetColor(1,0.8,0.2) self.highlightActor.GetProperty().SetLineWidth(3.0) self.highlightActor.SetOrientation(self.actorList[0].GetOrientation()) tmpPos = self.actorList[0].GetPosition() usePos = (tmpPos[0],tmpPos[1],tmpPos[2]+0.01) self.highlightActor.SetPosition(usePos) # Setting as if nothing picked even though initialized position & orientation to actor0 self.highlightIndex = -1 self.highlightActor.SetPickable(False) self.highlightActor.SetVisibility(False) self.renderer.AddActor(self.highlightActor) # Create the slider which will control the image positions self.sliderRep = vtk.vtkSliderRepresentation2D() self.sliderRep.SetMinimumValue(0) self.sliderRep.SetMaximumValue(self.numImages) self.sliderRep.SetValue(0) self.window = vtk.vtkRenderWindow() self.window.SetSize(600,300) self.window.AddRenderer(self.renderer) # Set up the interaction self.interactorStyle = vtk.vtkInteractorStyleRubberBand3D() self.interactor = vtk.vtkRenderWindowInteractor() self.interactor.SetInteractorStyle(self.interactorStyle) self.window.SetInteractor(self.interactor) self.sliderWidget = vtk.vtkSliderWidget() self.sliderWidget.SetInteractor(self.interactor) self.sliderWidget.SetRepresentation(self.sliderRep) self.sliderWidget.SetAnimationModeToAnimate() self.sliderWidget.EnabledOn() self.sliderWidget.AddObserver("InteractionEvent", self.sliderCallback) self.sliderWidget.AddObserver("EndInteractionEvent", self.endSliderCallback) # Default flow direction Horizontal self.FlowDirection = Direction.Horizontal self.SetFlowDirection(self.FlowDirection) # Set up callback to toggle between inspect modes (manip axes & select data) self.interactorStyle.AddObserver("SelectionChangedEvent", self.selectImage) # Set up callback to toggle between inspect modes (manip axes & select data) self.interactor.AddObserver("UserEvent", self.PrintCameraPosition) self.cam.ParallelProjectionOn() self.renderer.ResetCamera(self.actorList[0].GetBounds()) self.cam.Elevation(10) self.renderer.ResetCameraClippingRange() self.window.Render()
def __init__(self, data_source, input_link): """Parallel coordinates view constructor needs a valid DataSource plus and external annotation link (from the icicle view). """ self.ds = data_source self.input_link = input_link # Set up callback to listen for changes in IcicleView selections self.input_link.AddObserver("AnnotationChangedEvent", self.InputSelectionCallback) # Set up an annotation link for other views to monitor selected image self.output_link = vtk.vtkAnnotationLink() # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010) # See vtkSelectionNode doc for field and content type enum values self.output_link.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point # The chart seems to force INDEX selection, so I'm using vtkConvertSelection below to get # out PedigreeIds... self.output_link.GetCurrentSelection().GetNode(0).SetContentType(2) # 2 = PedigreeIds, 4 = Indices # Going to manually create output_link selection list, so not setting up callback for it... if os.path.isfile(os.path.abspath('BlankImage.png')): blank_file = 'BlankImage.png' else: # For use in app bundles blank_file = os.path.join(sys.path[0],'BlankImage.png') self.blankImageReader = vtk.vtkPNGReader() self.blankImageReader.SetFileName(blank_file) self.blankImageReader.Update() tmp = self.blankImageReader.GetOutput().GetBounds() self.flowSpacing = float(tmp[1]-tmp[0])*1.1 # Create a greyscale lookup table self.lut = self.ds.GetGrayscaleLUT('gray') self.lut.SetRange(self.blankImageReader.GetOutput().GetPointData().GetArray('PNGImage').GetRange()) # image intensity range # Map the image through the lookup table self.color = vtk.vtkImageMapToColors() self.color.SetLookupTable(self.lut) self.color.SetInput(self.blankImageReader.GetOutput()) self.resliceList = [] self.actorList = [] self.numImages = 1 # Map between indices of images and their Pedigree ID self.pedigree_id_dict = {} blankImageActor = vtk.vtkImageActor() blankImageActor.SetInput(self.color.GetOutput()) blankImageActor.SetPickable(False) blankImageActor.SetOpacity(0.1) self.actorList.append(blankImageActor) self.expSpread = 0.5 self.maxAngle = 80.0 self.renderer = vtk.vtkRenderer() self.cam = self.renderer.GetActiveCamera() # renderer.SetBackground(0.15, 0.12, 0.1) # cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [68,57,53]] # self.renderer.SetBackground(cc0,cc1,cc2) # cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [60,60,60]] cc0,cc1,cc2 = [float(ccVal)/255.0 for ccVal in [160, 160, 160]] self.renderer.SetBackground(cc0,cc1,cc2) self.renderer.AddActor(self.actorList[0]) self.highlightRect = vtk.vtkOutlineSource() self.highlightRect.SetBounds(self.actorList[0].GetBounds()) self.highlightMapper = vtk.vtkPolyDataMapper() self.highlightMapper.SetInputConnection(self.highlightRect.GetOutputPort(0)) self.highlightActor = vtk.vtkActor() self.highlightActor.SetMapper(self.highlightMapper) self.highlightActor.GetProperty().SetColor(0,0.5,1.0) self.highlightActor.GetProperty().SetLineWidth(6.0) self.highlightActor.GetProperty().SetOpacity(0.5) self.highlightActor.SetOrientation(self.actorList[0].GetOrientation()) tmpPos = self.actorList[0].GetPosition() usePos = (tmpPos[0],tmpPos[1],tmpPos[2]+0.01) self.highlightActor.SetPosition(usePos) # Setting as if nothing picked even though initialized position & orientation to actor0 self.highlightIndex = -1 self.highlightActor.SetPickable(False) self.highlightActor.SetVisibility(False) self.renderer.AddActor(self.highlightActor) # Create the slider which will control the image positions self.sliderRep = vtk.vtkSliderRepresentation2D() self.sliderRep.SetMinimumValue(0) self.sliderRep.SetMaximumValue(self.numImages-1) self.sliderRep.SetValue(0) self.window = vtk.vtkRenderWindow() self.window.SetSize(600,300) self.window.AddRenderer(self.renderer) # Set up the interaction self.interactorStyle = vtk.vtkInteractorStyleImage() self.interactor = vtk.vtkRenderWindowInteractor() self.interactor.SetInteractorStyle(self.interactorStyle) self.window.SetInteractor(self.interactor) self.sliderWidget = vtk.vtkSliderWidget() self.sliderWidget.SetInteractor(self.interactor) self.sliderWidget.SetRepresentation(self.sliderRep) self.sliderWidget.SetAnimationModeToAnimate() self.sliderWidget.EnabledOn() self.sliderWidget.AddObserver("InteractionEvent", self.sliderCallback) self.sliderWidget.AddObserver("EndInteractionEvent", self.endSliderCallback) # Default flow direction Horizontal self.FlowDirection = Direction.Horizontal self.SetFlowDirection(self.FlowDirection) # Set up callback to toggle between inspect modes (manip axes & select data) # self.interactorStyle.AddObserver("SelectionChangedEvent", self.selectImage) # Create callbacks for mouse events self.mouseActions = {} self.mouseActions["LeftButtonDown"] = 0 self.mouseActions["Picking"] = 0 self.interactorStyle.AddObserver("MouseMoveEvent", self.MouseMoveCallback) self.interactorStyle.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback) self.interactorStyle.AddObserver("LeftButtonReleaseEvent", self.LeftButtonReleaseCallback) self.cam.ParallelProjectionOn() self.renderer.ResetCamera(self.actorList[0].GetBounds()) self.cam.Elevation(10) self.renderer.ResetCameraClippingRange()
def __init__(self, module_manager): # call base constructor ModuleBase.__init__(self, module_manager) ColourDialogMixin.__init__( self, module_manager.get_module_view_parent_window()) self._numDataInputs = self.NUM_INPUTS # use list comprehension to create list keeping track of inputs self._inputs = [{ 'Connected': None, 'inputData': None, 'vtkActor': None, 'ipw': None } for i in range(self._numDataInputs)] # then the window containing the renderwindows self.threedFrame = None # the renderers corresponding to the render windows self._threedRenderer = None self._outline_source = vtk.vtkOutlineSource() om = vtk.vtkPolyDataMapper() om.SetInputConnection(self._outline_source.GetOutputPort()) self._outline_actor = vtk.vtkActor() self._outline_actor.SetMapper(om) self._cube_axes_actor2d = vtk.vtkCubeAxesActor2D() self._cube_axes_actor2d.SetFlyModeToOuterEdges() #self._cube_axes_actor2d.SetFlyModeToClosestTriad() # use box widget for VOI selection self._voi_widget = vtk.vtkBoxWidget() # we want to keep it aligned with the cubic volume, thanks self._voi_widget.SetRotationEnabled(0) self._voi_widget.AddObserver('InteractionEvent', self.voiWidgetInteractionCallback) self._voi_widget.AddObserver('EndInteractionEvent', self.voiWidgetEndInteractionCallback) self._voi_widget.NeedsPlacement = True # also create the VTK construct for actually extracting VOI from data #self._extractVOI = vtk.vtkExtractVOI() self._currentVOI = 6 * [0] # set the whole UI up! self._create_window() # our interactor styles (we could add joystick or something too) self._cInteractorStyle = vtk.vtkInteractorStyleTrackballCamera() # set the default self.threedFrame.threedRWI.SetInteractorStyle(self._cInteractorStyle) rwi = self.threedFrame.threedRWI rwi.Unbind(wx.EVT_MOUSEWHEEL) rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel) # initialise our sliceDirections, this will also setup the grid and # bind all slice UI events self.sliceDirections = sliceDirections(self, self.controlFrame.sliceGrid) self.selectedPoints = selectedPoints(self, self.controlFrame.pointsGrid) # we now have a wx.ListCtrl, let's abuse it self._tdObjects = tdObjects(self, self.controlFrame.objectsListGrid) self._implicits = implicits(self, self.controlFrame.implicitsGrid) # setup orientation widget stuff # NB NB NB: we switch interaction with this off later # (InteractiveOff()), thus disabling direct translation and # scaling. If we DON'T do this, interaction with software # raycasters are greatly slowed down. self._orientation_widget = vtk.vtkOrientationMarkerWidget() self._annotated_cube_actor = aca = vtk.vtkAnnotatedCubeActor() #aca.TextEdgesOff() aca.GetXMinusFaceProperty().SetColor(1, 0, 0) aca.GetXPlusFaceProperty().SetColor(1, 0, 0) aca.GetYMinusFaceProperty().SetColor(0, 1, 0) aca.GetYPlusFaceProperty().SetColor(0, 1, 0) aca.GetZMinusFaceProperty().SetColor(0, 0, 1) aca.GetZPlusFaceProperty().SetColor(0, 0, 1) self._axes_actor = vtk.vtkAxesActor() self._orientation_widget.SetInteractor(self.threedFrame.threedRWI) self._orientation_widget.SetOrientationMarker(self._axes_actor) self._orientation_widget.On() # make sure interaction is off; when on, interaction with # software raycasters is greatly slowed down! self._orientation_widget.InteractiveOff()
subActor.SetMapper(subMapper) # Create an outline outline = vtk.vtkOutlineFilter() outline.SetInputConnection(points.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) # Create another outline bds = [0, 0, 0, 0, 0, 0] hBin.GetBinBounds(binNum, bds) binOutline = vtk.vtkOutlineSource() binOutline.SetBounds(bds) binOutlineMapper = vtk.vtkPolyDataMapper() binOutlineMapper.SetInputConnection(binOutline.GetOutputPort()) binOutlineActor = vtk.vtkActor() binOutlineActor.SetMapper(binOutlineMapper) # Create the RenderWindow, Renderer and both Actors # ren0 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren0) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin)
def _init_frame(): # call base constructor ModuleBase.__init__(self, module_manager) self._numDataInputs = self.NUM_INPUTS # use list comprehension to create list keeping track of inputs self._inputs = [{'Connected' : None, 'inputData' : None, 'vtkActor' : None, 'ipw' : None} for i in range(self._numDataInputs)] # create the view frame self.frame = module_utils.instantiate_module_view_frame( self, self._module_manager, multiDirectionalSlicedViewSegmentation3dVieWeRFrame.multiDirectionalSlicedViewSegmentation3dVieWeRFrame) #THE FRAME (reference) frame = self.frame # change the title to something more spectacular (or at least something non-default) frame.SetTitle('multiDirectionalSlicedViewSegmentation3dVieWeR') # predefine this self.selectedData = [] self.controlIsCurrentlyDown = 0 # list of objects that want to be contoured by this slice self._contourObjectsDict1 = {} self._contourObjectsDict2 = {} self._contourObjectsDict3 = {} # anything you stuff into self._config will be saved self._config.last_used_dir = '' #color definitions twoD_bg_color = (0.19,0.19,0.19) threeD_bg_color = (0.62,0.62,0.62) contour_color = (0.6,0.6,0.6) # create the necessary VTK objects # setup the Top Renderer (id: 1) self.renderer_top = vtk.vtkRenderer() self.renderer_top.SetBackground(twoD_bg_color) frame.top.GetRenderWindow().AddRenderer(self.renderer_top) self.slice_viewer_top = CMSliceViewer(frame.top, self.renderer_top) self.slice_viewer_top.set_parallel() # setup the Side Renderer (id: 2) self.renderer_side = vtk.vtkRenderer() self.renderer_side.SetBackground(twoD_bg_color) frame.side.GetRenderWindow().AddRenderer(self.renderer_side) self.slice_viewer_side = CMSliceViewer(frame.side, self.renderer_side) self.slice_viewer_side.set_parallel() # setup the Front Renderer (id: 3) self.renderer_front = vtk.vtkRenderer() self.renderer_front.SetBackground(twoD_bg_color) frame.front.GetRenderWindow().AddRenderer(self.renderer_front) self.slice_viewer_front = CMSliceViewer(frame.front, self.renderer_front) self.slice_viewer_front.set_parallel() # setup the 3D Renderer (id: 4) self.contour_actor = vtk.vtkActor() self.contour_mapper = vtk.vtkPolyDataMapper() self.contour_mapper.ScalarVisibilityOff() self.contour_selected_actors = [] self.contour_actor.SetMapper(self.contour_mapper) self.contour_actor.GetProperty().SetColor(contour_color) self._on_slide_transparency() self.renderer_3d = vtk.vtkRenderer() self.renderer_3d.SetBackground(threeD_bg_color) self.renderer_3d.AddActor(self.contour_actor) frame.view3d.GetRenderWindow().AddRenderer(self.renderer_3d) frame.view3d._outline_source = vtk.vtkOutlineSource() om = vtk.vtkPolyDataMapper() om.SetInput(frame.view3d._outline_source.GetOutput()) frame.view3d._outline_actor = vtk.vtkActor() frame.view3d._outline_actor.SetMapper(om) frame.view3d._cInteractorStyle = vtk.vtkInteractorStyleTrackballCamera() frame.view3d.SetInteractorStyle(frame.view3d._cInteractorStyle) frame.view3d._orientation_widget.On() # make our window appear (this is a viewer after all) self.view() # all modules should toggle this once they have shown their views. self.view_initialised = True # apply config information to underlying logic self.sync_module_logic_with_config() # then bring it all the way up again to the view self.sync_module_view_with_logic() self.clearSeedPoints()
def __init__(self, module_manager): # call base constructor ModuleBase.__init__(self, module_manager) ColourDialogMixin.__init__( self, module_manager.get_module_view_parent_window()) self._numDataInputs = self.NUM_INPUTS # use list comprehension to create list keeping track of inputs self._inputs = [{'Connected' : None, 'inputData' : None, 'vtkActor' : None, 'ipw' : None} for i in range(self._numDataInputs)] # then the window containing the renderwindows self.threedFrame = None # the renderers corresponding to the render windows self._threedRenderer = None self._outline_source = vtk.vtkOutlineSource() om = vtk.vtkPolyDataMapper() om.SetInputConnection(self._outline_source.GetOutputPort()) self._outline_actor = vtk.vtkActor() self._outline_actor.SetMapper(om) self._cube_axes_actor2d = vtk.vtkCubeAxesActor2D() self._cube_axes_actor2d.SetFlyModeToOuterEdges() #self._cube_axes_actor2d.SetFlyModeToClosestTriad() # use box widget for VOI selection self._voi_widget = vtk.vtkBoxWidget() # we want to keep it aligned with the cubic volume, thanks self._voi_widget.SetRotationEnabled(0) self._voi_widget.AddObserver('InteractionEvent', self.voiWidgetInteractionCallback) self._voi_widget.AddObserver('EndInteractionEvent', self.voiWidgetEndInteractionCallback) self._voi_widget.NeedsPlacement = True # also create the VTK construct for actually extracting VOI from data #self._extractVOI = vtk.vtkExtractVOI() self._currentVOI = 6 * [0] # set the whole UI up! self._create_window() # our interactor styles (we could add joystick or something too) self._cInteractorStyle = vtk.vtkInteractorStyleTrackballCamera() # set the default self.threedFrame.threedRWI.SetInteractorStyle(self._cInteractorStyle) rwi = self.threedFrame.threedRWI rwi.Unbind(wx.EVT_MOUSEWHEEL) rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel) # initialise our sliceDirections, this will also setup the grid and # bind all slice UI events self.sliceDirections = sliceDirections( self, self.controlFrame.sliceGrid) self.selectedPoints = selectedPoints( self, self.controlFrame.pointsGrid) # we now have a wx.ListCtrl, let's abuse it self._tdObjects = tdObjects(self, self.controlFrame.objectsListGrid) self._implicits = implicits(self, self.controlFrame.implicitsGrid) # setup orientation widget stuff # NB NB NB: we switch interaction with this off later # (InteractiveOff()), thus disabling direct translation and # scaling. If we DON'T do this, interaction with software # raycasters are greatly slowed down. self._orientation_widget = vtk.vtkOrientationMarkerWidget() self._annotated_cube_actor = aca = vtk.vtkAnnotatedCubeActor() #aca.TextEdgesOff() aca.GetXMinusFaceProperty().SetColor(1,0,0) aca.GetXPlusFaceProperty().SetColor(1,0,0) aca.GetYMinusFaceProperty().SetColor(0,1,0) aca.GetYPlusFaceProperty().SetColor(0,1,0) aca.GetZMinusFaceProperty().SetColor(0,0,1) aca.GetZPlusFaceProperty().SetColor(0,0,1) self._axes_actor = vtk.vtkAxesActor() self._orientation_widget.SetInteractor( self.threedFrame.threedRWI) self._orientation_widget.SetOrientationMarker( self._axes_actor) self._orientation_widget.On() # make sure interaction is off; when on, interaction with # software raycasters is greatly slowed down! self._orientation_widget.InteractiveOff()
def setWidgetView(self, widget): super(CenterLineView, self).setWidgetView(widget) point_array = self.parent.getData().pointSet point_data = npy.array(point_array.getData('Centerline')) if point_data is None or not point_data.shape[0]: return #self.spacing = [1, 1, 1] self.spacing = self.parent.getData().getResolution().tolist() self.spacing = [float(x) / self.spacing[-1] for x in self.spacing] point_data[:, :2] *= self.spacing[:2] self.renderer = vtk.vtkRenderer() self.render_window = widget.GetRenderWindow() self.render_window.AddRenderer(self.renderer) self.window_interactor = vtk.vtkRenderWindowInteractor() self.render_window.SetInteractor(self.window_interactor) self.center = [] self.center_mapper = [] self.center_actor = [] self.points = [] self.para_spline = [] self.spline_source = [] for cnt in range(3): self.center.append(vtk.vtkPolyData()) self.center_mapper.append(vtk.vtkPolyDataMapper()) self.center_actor.append(vtk.vtkActor()) self.points.append(vtk.vtkPoints()) self.para_spline.append(vtk.vtkParametricSpline()) self.spline_source.append(vtk.vtkParametricFunctionSource()) point = point_data[npy.where(npy.round(point_data[:, -1]) == cnt)] point = point[point[:, 2].argsort(), :] count = point.shape[0] if not count: continue self.points[cnt].SetNumberOfPoints(count) for i in range(count): self.points[cnt].SetPoint(i, point[i, 0], point[i, 1], point[i, 2]) self.para_spline[cnt].SetPoints(self.points[cnt]) self.spline_source[cnt].SetParametricFunction(self.para_spline[cnt]) numberOfOutputPoints = count * 10 self.spline_source[cnt].SetUResolution(numberOfOutputPoints) self.center_mapper[cnt].SetInput(self.spline_source[cnt].GetOutput()) self.center_mapper[cnt].ScalarVisibilityOff() self.center_actor[cnt].SetMapper(self.center_mapper[cnt]) color = [0, 0, 0] color[cnt] = 1 self.center_actor[cnt].GetProperty().SetColor(color[0], color[1], color[2]) self.renderer.AddViewProp(self.center_actor[cnt]) bound = npy.array(self.parent.getData().getData().shape)[::-1] * self.spacing outline_source = vtk.vtkOutlineSource() outline_source.SetBounds(0, bound[0], 0, bound[1], 0, bound[2]) mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outline_source.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(mapOutline) outlineActor.GetProperty().SetColor(1, 1, 1) self.renderer.AddViewProp(outlineActor) self.renderer.ResetCamera() point = self.renderer.GetActiveCamera().GetFocalPoint() dis = self.renderer.GetActiveCamera().GetDistance() self.renderer.GetActiveCamera().SetViewUp(0, 0, 1) self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2]) self.renderer.ResetCameraClippingRange() self.render_window.Render() # Manually set to trackball style self.window_interactor.SetKeyCode('t') self.window_interactor.CharEvent() self.window_interactor.GetInteractorStyle().AddObserver("KeyPressEvent", self.KeyPressCallback) self.window_interactor.GetInteractorStyle().AddObserver("CharEvent", self.KeyPressCallback)
def set_initial_display(self): if self.renwininter is None: self.renwininter = MEQ_QVTKRenderWindowInteractor(self.winsplitter) self.renwininter.setWhatsThis(rendering_control_instructions) self.renwin = self.renwininter.GetRenderWindow() self.inter = self.renwin.GetInteractor() self.winsplitter.insertWidget(0,self.renwininter) self.winsplitter.addWidget(self.v_box_controls) self.winsplitter.setSizes([500,100]) self.renwininter.show() # Paul Kemper suggested the following: camstyle = vtk.vtkInteractorStyleTrackballCamera() self.renwininter.SetInteractorStyle(camstyle) self.extents = self.image_array.GetDataExtent() self.spacing = self.image_array.GetDataSpacing() self.origin = self.image_array.GetDataOrigin() # An outline is shown for context. if self.warped_surface: self.index_selector.initWarpContextmenu() sx, sy, sz = self.image_array.GetDataSpacing() xMin, xMax, yMin, yMax, zMin, zMax = self.image_array.GetDataExtent() xMin = sx * xMin xMax = sx * xMax yMin = sy * yMin yMax = sy * yMax self.scale_factor = 0.5 * ((xMax-xMin) + (yMax-yMin)) / (self.data_max - self.data_min) zMin = self.data_min * self.scale_factor zMax = self.data_max * self.scale_factor self.outline = vtk.vtkOutlineSource(); self.outline.SetBounds(xMin, xMax, yMin, yMax, zMin, zMax) else: self.index_selector.init3DContextmenu() self.outline = vtk.vtkOutlineFilter() self.outline.SetInput(self.image_array.GetOutput()) outlineMapper = vtk.vtkPolyDataMapper(); outlineMapper.SetInput(self.outline.GetOutput() ); outlineActor = vtk.vtkActor(); outlineActor.SetMapper(outlineMapper); # create blue to red color table self.lut = vtk.vtkLookupTable() self.lut.SetHueRange(0.6667, 0.0) self.lut.SetNumberOfColors(256) self.lut.Build() # here is where the 2-D image gets warped if self.warped_surface: geometry = vtk.vtkImageDataGeometryFilter() geometry.SetInput(self.image_array.GetOutput()) self.warp = vtk.vtkWarpScalar() self.warp.SetInput(geometry.GetOutput()) self.warp.SetScaleFactor(self.scale_factor) self.mapper = vtk.vtkPolyDataMapper(); self.mapper.SetInput(self.warp.GetPolyDataOutput()) self.mapper.SetScalarRange(self.data_min,self.data_max) self.mapper.SetLookupTable(self.lut) self.mapper.ImmediateModeRenderingOff() warp_actor = vtk.vtkActor() # warp_actor.SetScale(2,1,1) warp_actor.SetMapper(self.mapper) min_range = 0.5 * self.scale_factor max_range = 2.0 * self.scale_factor self.index_selector.set_emit(False) self.index_selector.setMaxValue(max_range,False) self.index_selector.setMinValue(min_range) self.index_selector.setTickInterval( (max_range - min_range) / 10 ) self.index_selector.setRange(max_range, False) self.index_selector.setValue(self.scale_factor) self.index_selector.setLabel('display gain') self.index_selector.hideNDControllerOption() self.index_selector.reset_scale_toggle() self.index_selector.set_emit(True) else: # set up ImagePlaneWidgets ... # The shared picker enables us to use 3 planes at one time # and gets the picking order right picker = vtk.vtkCellPicker() picker.SetTolerance(0.005) # get locations for initial slices xMin, xMax, yMin, yMax, zMin, zMax = self.extents x_index = (xMax-xMin) / 2 y_index = (yMax-yMin) / 2 z_index = (zMax-zMin) / 2 # The 3 image plane widgets are used to probe the dataset. self.planeWidgetX = vtk.vtkImagePlaneWidget() self.planeWidgetX.DisplayTextOn() self.planeWidgetX.SetInput(self.image_array.GetOutput()) self.planeWidgetX.SetPlaneOrientationToXAxes() self.planeWidgetX.SetSliceIndex(x_index) self.planeWidgetX.SetPicker(picker) self.planeWidgetX.SetKeyPressActivationValue("x") self.planeWidgetX.SetLookupTable(self.lut) self.planeWidgetX.TextureInterpolateOff() self.planeWidgetX.SetResliceInterpolate(0) self.planeWidgetY = vtk.vtkImagePlaneWidget() self.planeWidgetY.DisplayTextOn() self.planeWidgetY.SetInput(self.image_array.GetOutput()) self.planeWidgetY.SetPlaneOrientationToYAxes() self.planeWidgetY.SetSliceIndex(y_index) self.planeWidgetY.SetPicker(picker) self.planeWidgetY.SetKeyPressActivationValue("y") self.planeWidgetY.SetLookupTable(self.planeWidgetX.GetLookupTable()) self.planeWidgetY.TextureInterpolateOff() self.planeWidgetY.SetResliceInterpolate(0) self.planeWidgetZ = vtk.vtkImagePlaneWidget() self.planeWidgetZ.DisplayTextOn() self.planeWidgetZ.SetInput(self.image_array.GetOutput()) self.planeWidgetZ.SetPlaneOrientationToZAxes() self.planeWidgetZ.SetSliceIndex(z_index) self.planeWidgetZ.SetPicker(picker) self.planeWidgetZ.SetKeyPressActivationValue("z") self.planeWidgetZ.SetLookupTable(self.planeWidgetX.GetLookupTable()) self.planeWidgetZ.TextureInterpolateOff() self.planeWidgetZ.SetResliceInterpolate(0) self.current_widget = self.planeWidgetZ self.mode_widget = self.planeWidgetZ self.index_selector.set_emit(False) self.index_selector.setMinValue(zMin) self.index_selector.setMaxValue(zMax,False) self.index_selector.setTickInterval( (zMax-zMin) / 10 ) self.index_selector.setRange(zMax, False) self.index_selector.setValue(z_index) self.index_selector.setLabel('Z axis') self.index_selector.reset_scale_toggle() self.index_selector.set_emit(True) # create scalar bar for display of intensity range self.scalar_bar = vtk.vtkScalarBarActor() self.scalar_bar.SetLookupTable(self.lut) self.scalar_bar.SetOrientationToVertical() self.scalar_bar.SetWidth(0.1) self.scalar_bar.SetHeight(0.8) self.scalar_bar.SetTitle("Intensity") self.scalar_bar.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport() self.scalar_bar.GetPositionCoordinate().SetValue(0.01, 0.1) # Create the RenderWindow and Renderer self.ren = vtk.vtkRenderer() self.renwin.AddRenderer(self.ren) # Add the outline actor to the renderer, set the background color and size if self.warped_surface: self.ren.AddActor(warp_actor) self.ren.AddActor(outlineActor) self.ren.SetBackground(0.1, 0.1, 0.2) self.ren.AddActor2D(self.scalar_bar) # Create a text property for cube axes tprop = vtk.vtkTextProperty() tprop.SetColor(1, 1, 1) tprop.ShadowOn() # Create a vtkCubeAxesActor2D. Use the outer edges of the bounding box to # draw the axes. Add the actor to the renderer. self.axes = vtk.vtkCubeAxesActor2D() if self.warped_surface: if zMin < 0.0 and zMax > 0.0: zLoc = 0.0 else: zLoc = zMin self.axes.SetBounds(xMin, xMax, yMin, yMax, zLoc, zLoc) self.axes.SetZLabel(" ") else: self.axes.SetInput(self.image_array.GetOutput()) self.axes.SetZLabel("Z") self.axes.SetCamera(self.ren.GetActiveCamera()) self.axes.SetLabelFormat("%6.4g") self.axes.SetFlyModeToOuterEdges() self.axes.SetFontFactor(0.8) self.axes.SetAxisTitleTextProperty(tprop) self.axes.SetAxisLabelTextProperty(tprop) self.axes.SetXLabel("X") self.axes.SetYLabel("Y") self.ren.AddProp(self.axes) # Set the interactor for the widgets if not self.warped_surface: self.planeWidgetX.SetInteractor(self.inter) self.planeWidgetX.On() self.planeWidgetY.SetInteractor(self.inter) self.planeWidgetY.On() self.planeWidgetZ.SetInteractor(self.inter) self.planeWidgetZ.On() self.initialize_camera()
subActor.SetMapper(subMapper) # Create an outline outline = vtk.vtkOutlineFilter() outline.SetInputConnection(points.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) # Create another outline bds = [0,0,0,0,0,0] hBin.GetBinBounds(binNum,bds) binOutline = vtk.vtkOutlineSource() binOutline.SetBounds(bds) binOutlineMapper = vtk.vtkPolyDataMapper() binOutlineMapper.SetInputConnection(binOutline.GetOutputPort()) binOutlineActor = vtk.vtkActor() binOutlineActor.SetMapper(binOutlineMapper) # Create the RenderWindow, Renderer and both Actors # ren0 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren0) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin)
def setWidgetView(self, widget): super(CenterLineView, self).setWidgetView(widget) point_array = self.parent.getData().pointSet point_data = npy.array(point_array.getData('Centerline')) if point_data is None or not point_data.shape[0]: return #self.spacing = [1, 1, 1] self.spacing = self.parent.getData().getResolution().tolist() self.spacing = [float(x) / self.spacing[-1] for x in self.spacing] point_data[:, :2] *= self.spacing[:2] self.renderer = vtk.vtkRenderer() self.render_window = widget.GetRenderWindow() self.render_window.AddRenderer(self.renderer) self.window_interactor = vtk.vtkRenderWindowInteractor() self.render_window.SetInteractor(self.window_interactor) self.center = [] self.center_mapper = [] self.center_actor = [] self.points = [] self.para_spline = [] self.spline_source = [] for cnt in range(3): self.center.append(vtk.vtkPolyData()) self.center_mapper.append(vtk.vtkPolyDataMapper()) self.center_actor.append(vtk.vtkActor()) self.points.append(vtk.vtkPoints()) self.para_spline.append(vtk.vtkParametricSpline()) self.spline_source.append(vtk.vtkParametricFunctionSource()) point = point_data[npy.where(npy.round(point_data[:, -1]) == cnt)] point = point[point[:, 2].argsort(), :] count = point.shape[0] if not count: continue self.points[cnt].SetNumberOfPoints(count) for i in range(count): self.points[cnt].SetPoint(i, point[i, 0], point[i, 1], point[i, 2]) self.para_spline[cnt].SetPoints(self.points[cnt]) self.spline_source[cnt].SetParametricFunction( self.para_spline[cnt]) numberOfOutputPoints = count * 10 self.spline_source[cnt].SetUResolution(numberOfOutputPoints) self.center_mapper[cnt].SetInput( self.spline_source[cnt].GetOutput()) self.center_mapper[cnt].ScalarVisibilityOff() self.center_actor[cnt].SetMapper(self.center_mapper[cnt]) color = [0, 0, 0] color[cnt] = 1 self.center_actor[cnt].GetProperty().SetColor( color[0], color[1], color[2]) self.renderer.AddViewProp(self.center_actor[cnt]) bound = npy.array( self.parent.getData().getData().shape)[::-1] * self.spacing outline_source = vtk.vtkOutlineSource() outline_source.SetBounds(0, bound[0], 0, bound[1], 0, bound[2]) mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outline_source.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(mapOutline) outlineActor.GetProperty().SetColor(1, 1, 1) self.renderer.AddViewProp(outlineActor) self.renderer.ResetCamera() point = self.renderer.GetActiveCamera().GetFocalPoint() dis = self.renderer.GetActiveCamera().GetDistance() self.renderer.GetActiveCamera().SetViewUp(0, 0, 1) self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2]) self.renderer.ResetCameraClippingRange() self.render_window.Render() # Manually set to trackball style self.window_interactor.SetKeyCode('t') self.window_interactor.CharEvent() self.window_interactor.GetInteractorStyle().AddObserver( "KeyPressEvent", self.KeyPressCallback) self.window_interactor.GetInteractorStyle().AddObserver( "CharEvent", self.KeyPressCallback)