def createSliderWidget( self, index ): sliderRep = vtk.vtkSliderRepresentation2D() sliderRep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() sliderRep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() prop = sliderRep.GetSliderProperty() prop.SetColor( 1.0, 0.0, 0.0 ) prop.SetOpacity( 0.5 ) sprop = sliderRep.GetSelectedProperty() sprop.SetOpacity( 0.8 ) tprop = sliderRep.GetTubeProperty() tprop.SetColor( 0.5, 0.5, 0.5 ) tprop.SetOpacity( 0.5 ) cprop = sliderRep.GetCapProperty() cprop.SetColor( 0.0, 0.0, 1.0 ) cprop.SetOpacity( 0.5 ) # sliderRep.PlaceWidget( bounds ) sliderRep.SetSliderLength(0.05) sliderRep.SetSliderWidth(0.02) sliderRep.SetTubeWidth(0.01) sliderRep.SetEndCapLength(0.02) sliderRep.SetEndCapWidth(0.02) sliderRep.SetTitleHeight( 0.02 ) sliderWidget = vtk.vtkSliderWidget() sliderWidget.SetInteractor(self.interactor) sliderWidget.SetRepresentation( sliderRep ) sliderWidget.SetAnimationModeToAnimate() sliderWidget.EnabledOn() sliderWidget.AddObserver("StartInteractionEvent", self.processStartInteractionEvent ) sliderWidget.AddObserver("EndInteractionEvent", self.processEndInteractionEvent ) sliderWidget.AddObserver("InteractionEvent", self.processInteractionEvent ) sliderWidget.KeyPressActivationOff() return sliderWidget
def Execute(self): if self.Image == None: self.PrintError("Error: no Image.") if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) if self.Type == "freehand": self.ImageTracerWidget = vtk.vtkImageTracerWidget() elif self.Type == "contour": self.ImageTracerWidget = vtk.vtkContourWidget() self.ImageTracerWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.SliderWidget = vtk.vtkSliderWidget() self.SliderWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.ImageActor = vtk.vtkImageActor() self.vmtkRenderer.AddKeyBinding("n", "Next.", self.NextCallback) self.vmtkRenderer.AddKeyBinding("p", "Previous.", self.PreviousCallback) self.vmtkRenderer.AddKeyBinding("i", "Interact.", self.InteractCallback) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def CreateSlider(renWinInteractor,plane,y): #build a slide bar slideBar = vtk.vtkSliderRepresentation2D() slideBar.SetMinimumValue(3.0) slideBar.SetMaximumValue(20.0) slideBar.SetTitleText("sphere") slideBar.GetSliderProperty().SetColor(1,0,0) slideBar.GetTitleProperty().SetColor(1,0,0) slideBar.GetLabelProperty().SetColor(1,0,0) slideBar.GetSelectedProperty().SetColor(1,0,0) slideBar.GetTubeProperty().SetColor(0,1,0) slideBar.GetCapProperty().SetColor(1,1,0) slideBar.GetPoint1Coordinate().SetCoordinateSystemToDisplay() slideBar.GetPoint1Coordinate().SetValue(40 ,40+y) slideBar.GetPoint2Coordinate().SetCoordinateSystemToDisplay() slideBar.GetPoint2Coordinate().SetValue(200,40+y) sliderWidget = vtk.vtkSliderWidget() sliderWidget.SetInteractor(renWinInteractor) sliderWidget.SetRepresentation(slideBar) sliderWidget.EnabledOn() def myCallback(obj,event): print obj.__class__.__name__," called" value = int (obj.GetRepresentation().GetValue()) plane.SetSliceIndex(value) sliderWidget.AddObserver("InteractionEvent",myCallback)
def Execute(self): if self.Image == None: self.PrintError('Error: no Image.') if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 if self.Type == 'freehand': self.ImageTracerWidget = vtk.vtkImageTracerWidget() elif self.Type == 'contour': self.ImageTracerWidget = vtk.vtkContourWidget() self.ImageTracerWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.SliderWidget = vtk.vtkSliderWidget() self.SliderWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.ImageActor = vtk.vtkImageActor() self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.Keypress) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def Execute(self): if self.Image == None: self.PrintError('Error: no Image.') if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) if self.Type == 'freehand': self.ImageTracerWidget = vtk.vtkImageTracerWidget() elif self.Type == 'contour': self.ImageTracerWidget = vtk.vtkContourWidget() self.ImageTracerWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.SliderWidget = vtk.vtkSliderWidget() self.SliderWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.ImageActor = vtk.vtkImageActor() self.vmtkRenderer.AddKeyBinding('n','Next.',self.NextCallback) self.vmtkRenderer.AddKeyBinding('p','Previous.',self.PreviousCallback) self.vmtkRenderer.AddKeyBinding('i','Interact.', self.InteractCallback) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def make_slider(title, observer, interactor, startvalue, minvalue, maxvalue, cx1, cy1, cx2, cy2): slider_repres = vtk.vtkSliderRepresentation2D() slider_repres.SetMinimumValue(minvalue - (maxvalue - minvalue) / 100) slider_repres.SetMaximumValue(maxvalue + (maxvalue - minvalue) / 100) slider_repres.SetValue(startvalue) slider_repres.SetTitleText(title) slider_repres.GetPoint1Coordinate().\ SetCoordinateSystemToNormalizedDisplay() slider_repres.GetPoint1Coordinate().SetValue(cx1, cy1) slider_repres.GetPoint2Coordinate().\ SetCoordinateSystemToNormalizedDisplay() slider_repres.GetPoint2Coordinate().SetValue(cx2, cy2) slider_repres.SetSliderLength(0.02) slider_repres.SetSliderWidth(0.03) slider_repres.SetEndCapLength(0.01) slider_repres.SetEndCapWidth(0.03) slider_repres.SetTubeWidth(0.005) slider_repres.SetLabelFormat('%f') slider_repres.SetTitleHeight(0.02) slider_repres.SetLabelHeight(0.02) slider_widget = vtk.vtkSliderWidget() slider_widget.SetInteractor(interactor) slider_widget.SetRepresentation(slider_repres) slider_widget.KeyPressActivationOff() slider_widget.SetAnimationModeToAnimate() slider_widget.SetEnabled(True) slider_widget.AddObserver('InteractionEvent', observer) return slider_widget, slider_repres
def __init__(self, interactor, value=0, min_val=0, max_val=1, point1=( 0, .1), point2=(1, .1), end=None, update=None, title=""): sliderWidget = vtk.vtkSliderWidget() sliderWidget.SetRepresentation(vtk.vtkSliderRepresentation2D()) super(Slider, self).__init__(interactor, sliderWidget) self.end_callback = end self.update_callback = update self.x1, self.y1 = point1 self.x2, self.y2 = point2 self.repr.GetPoint1Coordinate( ).SetCoordinateSystemToNormalizedDisplay() self.repr.GetPoint2Coordinate( ).SetCoordinateSystemToNormalizedDisplay() prop = self.repr.GetSliderProperty() prop.SetColor(1.0, 0.0, 0.0) prop.SetOpacity(0.5) sprop = self.repr.GetSelectedProperty() sprop.SetOpacity(0.8) tprop = self.repr.GetTubeProperty() tprop.SetColor(0.5, 0.5, 0.5) tprop.SetOpacity(0.5) cprop = self.repr.GetCapProperty() cprop.SetColor(0.0, 0.0, 1.0) cprop.SetOpacity(0.5) self.repr.SetMinimumValue(float(min_val)) self.repr.SetMaximumValue(float(max_val)) if callable(value): self.set_value(value()) self.value_func = value else: self.repr.SetValue(float(value)) self.value_func = None self.repr.SetSliderLength(0.05) self.repr.SetSliderWidth(0.02) self.repr.SetTubeWidth(0.01) self.repr.SetEndCapLength(0.02) self.repr.SetEndCapWidth(0.02) self.repr.SetTitleHeight(0.02) self.repr.SetTitleText(title) sliderWidget.SetAnimationModeToJump() sliderWidget.AddObserver("EndInteractionEvent", self.end_slide) sliderWidget.AddObserver("InteractionEvent", self.slide_value) sliderWidget.KeyPressActivationOff() self.place()
def main(argv): if os.name == 'nt': VTK_DATA_ROOT = "c:/VTK82/build_Release/ExternalData/Testing/" else: VTK_DATA_ROOT = "/home/jmh/" if 1: v16 = vtk.vtkMetaImageReader() v16.SetFileName("/home/jmh/github/fis/data/Abdomen/CT-Abdomen.mhd") v16.Update() elif 0: fname = os.path.join(VTK_DATA_ROOT, "Data/headsq/quarter") v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(64, 64) v16.SetDataByteOrderToLittleEndian() v16.SetImageRange(1, 93) v16.SetDataSpacing(3.2, 3.2, 1.5) v16.SetFilePrefix(fname) v16.ReleaseDataFlagOn() v16.SetDataMask(0x7fff) v16.Update() else: v16 = vtk.vtkMetaImageReader() v16.SetFileName("c:/github/fis/data/Abdomen/CT-Abdomen.mhd") v16.Update() rng = v16.GetOutput().GetScalarRange() shifter = vtk.vtkImageShiftScale() shifter.SetShift(-1.0 * rng[0]) shifter.SetScale(255.0 / (rng[1] - rng[0])) shifter.SetOutputScalarTypeToUnsignedChar() shifter.SetInputConnection(v16.GetOutputPort()) shifter.ReleaseDataFlagOff() shifter.Update() ImageViewer = vtk.vtkImageViewer2() ImageViewer.SetInputData(shifter.GetOutput()) ImageViewer.SetColorLevel(127) ImageViewer.SetColorWindow(255) iren = vtk.vtkRenderWindowInteractor() ImageViewer.SetupInteractor(iren) ImageViewer.Render() ImageViewer.GetRenderer().ResetCamera() ImageViewer.Render() dims = v16.GetOutput().GetDimensions() global minArea spacing = v16.GetOutput().GetSpacing() minArea = (spacing[0] * spacing[1]) / 0.1 # Slider screen representation SliderRepres = vtk.vtkSliderRepresentation2D() _min = ImageViewer.GetSliceMin() _max = ImageViewer.GetSliceMax() SliderRepres.SetMinimumValue(_min) SliderRepres.SetMaximumValue(_max) SliderRepres.SetValue(int((_min + _max) / 2)) SliderRepres.SetTitleText("Slice") SliderRepres.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint1Coordinate().SetValue(0.3, 0.05) SliderRepres.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint2Coordinate().SetValue(0.7, 0.05) SliderRepres.SetSliderLength(0.02) SliderRepres.SetSliderWidth(0.03) SliderRepres.SetEndCapLength(0.01) SliderRepres.SetEndCapWidth(0.03) SliderRepres.SetTubeWidth(0.005) SliderRepres.SetLabelFormat("%3.0lf") SliderRepres.SetTitleHeight(0.02) SliderRepres.SetLabelHeight(0.02) # Slider widget SliderWidget = vtk.vtkSliderWidget() SliderWidget.SetInteractor(iren) SliderWidget.SetRepresentation(SliderRepres) SliderWidget.KeyPressActivationOff() SliderWidget.SetAnimationModeToAnimate() SliderWidget.SetEnabled(True) SliderCb = vtkSliderCallback() SliderCb.SetImageViewer(ImageViewer) SliderWidget.AddObserver(vtk.vtkCommand.InteractionEvent, SliderCb.Execute) ImageViewer.SetSlice(int(SliderRepres.GetValue())) # Contour representation - responsible for placement of points, calculation of lines and contour manipulation global rep rep = vtk.vtkOrientedGlyphContourRepresentation() # vtkContourRepresentation has GetActiveNodeWorldPostion/Orientation rep.GetProperty().SetOpacity(0) #1 prop = rep.GetLinesProperty() from vtkUtils import renderLinesAsTubes from vtk.util.colors import red, green, pink, yellow renderLinesAsTubes(prop) prop.SetColor(yellow) propActive = rep.GetActiveProperty() #propActive.SetOpacity(0) # 2 renderLinesAsTubes(propActive) propActive.SetColor(green) shapeActive = rep.GetActiveCursorShape() warp = vtk.vtkWarpVector() warp.SetInputData(shapeActive) warp.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) scale = 0.4 warp.SetScaleFactor(scale) warp.Update() rep.SetActiveCursorShape(warp.GetOutput()) # Use vtkContourTriangulator to fill contours # Point placer imageActorPointPlacer = vtk.vtkImageActorPointPlacer() imageActorPointPlacer.SetImageActor(ImageViewer.GetImageActor()) rep.SetPointPlacer(imageActorPointPlacer) global ContourWidget # Contour widget - has a vtkWidgetEventTranslator which translate events to vtkContourWidget events ContourWidget = vtk.vtkContourWidget() ContourWidget.SetRepresentation(rep) ContourWidget.SetInteractor(iren) ContourWidget.SetEnabled(True) ContourWidget.ProcessEventsOn() ContourWidget.ContinuousDrawOn() # Can be Initialize() using polydata # Override methods that returns display position to get an overlay # (display postions) instead of computing it from world position and # the method BuildLines to interpolate using display positions # instead of world positions # Thinning of contour control points # AddFinalPointAction ContourWidget.AddObserver(vtk.vtkCommand.EndInteractionEvent, callback) if 0: # TODO: Make interior transparent contour = ContourWidget.GetContourRepresentation( ).GetContourRepresentationAsPolyData() tc = vtk.vtkContourTriangulator() tc.SetInputData(contour) tc.Update() # Extrusion towards camera extruder = vtk.vtkLinearExtrusionFilter() extruder.CappingOn() extruder.SetScalaFactor(1.0) extruder.SetInputData(tc.GetOutput()) extruder.SetVector(0, 0, 1.0) extruder.SetExtrusionTypeToNormalExtrusion() polyMapper = vtk.vtkPolyMapper() polyMapper.SetInputConnection(extruder.GetOutputPort()) polyMapper.ScalarVisibilityOn() polyMapper.Update() polyActor = vtk.vtkActor() polyActor.SetMapper(polyMapper) prop = polyActor.GetProperty() prop.SetColor(0, 1, 0) #prop.SetRepresentationToWireframe() renderer.AddActor(polyActor) renderer.GetRenderWindow().Render() iren.Start()
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 interactive_viewer(streamlines, outlierness): import vtk from dipy.viz import fvtk, actor, window, widget from dipy.data.fetcher import read_viz_icons colormap_name = "jet" stream_actor = actor.line(streamlines, colors=fvtk.create_colormap(outlierness, name=colormap_name)) stream_actor.SetPosition(-np.array(stream_actor.GetCenter())) global threshold threshold = 0.8 streamlines_color = np.zeros(len(streamlines), dtype="float32") streamlines_color[outlierness < threshold] = 1 streamlines_color[outlierness >= threshold] = 0 lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(2) lut.Build() lut.SetTableValue(0, tuple(fvtk.colors.orange_red) + (1,)) lut.SetTableValue(1, tuple(fvtk.colors.green) + (1,)) lut.SetTableRange(0, 1) stream_split_actor = actor.line(streamlines, colors=streamlines_color, lookup_colormap=lut) stream_split_actor.SetPosition(-np.array(stream_split_actor.GetCenter())) hist_actor, hist_fig = create_hist_actor(outlierness, colormap_name=colormap_name) # Main renderder bg = (0, 0, 0) global screen_size screen_size = (0, 0) ren_main = window.Renderer() ren_main.background(bg) show_m = window.ShowManager(ren_main, size=(1066, 600), interactor_style="trackball") show_m.window.SetNumberOfLayers(2) ren_main.SetLayer(1) ren_main.InteractiveOff() # Outlierness renderer ren_outlierness = window.Renderer() show_m.window.AddRenderer(ren_outlierness) ren_outlierness.background(bg) ren_outlierness.SetViewport(0, 0.3, 0.5, 1) ren_outlierness.add(stream_actor) ren_outlierness.reset_camera_tight() ren_split = window.Renderer() show_m.window.AddRenderer(ren_split) ren_split.background(bg) ren_split.SetViewport(0.5, 0.3, 1, 1) ren_split.add(stream_split_actor) ren_split.SetActiveCamera(ren_outlierness.GetActiveCamera()) # Histogram renderer ren_hist = window.Renderer() show_m.window.AddRenderer(ren_hist) ren_hist.projection("parallel") ren_hist.background(bg) ren_hist.SetViewport(0, 0, 1, 0.3) ren_hist.add(hist_actor) ren_hist.SetInteractive(False) def apply_threshold(obj, evt): global threshold new_threshold = np.round(obj.GetSliderRepresentation().GetValue(), decimals=2) obj.GetSliderRepresentation().SetValue(new_threshold) if threshold != new_threshold: threshold = new_threshold streamlines_color = np.zeros(len(streamlines), dtype=np.float32) streamlines_color[outlierness < threshold] = 1 streamlines_color[outlierness >= threshold] = 0 colors = [] for color, streamline in zip(streamlines_color, streamlines): colors += [color] * len(streamline) scalars = stream_split_actor.GetMapper().GetInput().GetPointData().GetScalars() for i, c in enumerate(colors): scalars.SetValue(i, c) scalars.Modified() threshold_slider_rep = vtk.vtkSliderRepresentation3D() threshold_slider_rep.SetMinimumValue(0.) threshold_slider_rep.SetMaximumValue(1.) threshold_slider_rep.SetValue(threshold) threshold_slider_rep.SetLabelFormat("%0.2lf") threshold_slider_rep.SetLabelHeight(0.02) threshold_slider_rep.GetPoint1Coordinate().SetCoordinateSystemToWorld() x1, x2, y1, y2, z1, z2 = hist_actor.GetBounds() threshold_slider_rep.GetPoint1Coordinate().SetValue(x1*1., y1-5, 0) threshold_slider_rep.GetPoint2Coordinate().SetCoordinateSystemToWorld() threshold_slider_rep.GetPoint2Coordinate().SetValue(x2*1., y1-5, 0) threshold_slider_rep.SetEndCapLength(0.) threshold_slider_rep.SetEndCapWidth(0.) threshold_slider = vtk.vtkSliderWidget() threshold_slider.SetInteractor(show_m.iren) threshold_slider.SetRepresentation(threshold_slider_rep) threshold_slider.SetCurrentRenderer(ren_hist) threshold_slider.SetAnimationModeToJump() threshold_slider.EnabledOn() threshold_slider.AddObserver("InteractionEvent", apply_threshold) #ren_main def _place_buttons(): sz = 30.0 width, _ = ren_main.GetSize() # bds = np.zeros(6) # bds[0] = width - sz - 5 # bds[1] = bds[0] + sz # bds[2] = 5 # bds[3] = bds[2] + sz # bds[4] = bds[5] = 0.0 # save_button.GetRepresentation().PlaceWidget(bds) def _window_callback(obj, event): ren_hist.reset_camera_tight(margin_factor=1.2) _place_buttons() show_m.add_window_callback(_window_callback) show_m.initialize() show_m.render() show_m.start() inliers = [s for s, keep in zip(streamlines, outlierness < threshold) if keep] outliers = [s for s, keep in zip(streamlines, outlierness >= threshold) if keep] return inliers, outliers
SliderRepres = vtk.vtkSliderRepresentation2D() min = 0 #ImageViewer.GetSliceMin() max = 100 #ImageViewer.GetSliceMax() SliderRepres.SetMinimumValue(min) SliderRepres.SetMaximumValue(max) SliderRepres.SetValue(min) SliderRepres.SetTitleText("scale factor") SliderRepres.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint1Coordinate().SetValue(0.1, 0.1) SliderRepres.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint2Coordinate().SetValue(0.4, 0.1) SliderRepres.SetSliderLength(0.02) SliderRepres.SetSliderWidth(0.03) SliderRepres.SetEndCapLength(0.01) SliderRepres.SetEndCapWidth(0.03) SliderRepres.SetTubeWidth(0.005) SliderRepres.SetLabelFormat("%3.0lf / 1000") SliderRepres.SetTitleHeight(0.02) SliderRepres.SetLabelHeight(0.02) SliderWidget = vtk.vtkSliderWidget() SliderWidget.SetInteractor(iren) SliderWidget.SetRepresentation(SliderRepres) SliderWidget.KeyPressActivationOff() SliderWidget.SetAnimationModeToAnimate() SliderWidget.SetEnabled(True) SliderWidget.AddObserver("InteractionEvent", vtkSliderCallback) iren.Initialize() renWin.Render() iren.Start()
def display_and_query(self): # Convert images to VTK data structures fixedVTKImage = self.fixedCL.toVTKImage() movingVTKImage = self.movingCL.toVTKImage() # Viewing parameters fixedFrame = self.get_frame(self.fixedCL.clarray.get()) movingFrame = self.get_frame(self.movingCL.clarray.get()) N = self.panelSize fixedShape = self.fixedCL.shape XC = [0, 0, 0] for d in range(3): XC[d] = fixedShape[d] / 2.0 # # Create panel of views for fixed and moving image, with likely optimal # orientations # fixedArray = np.zeros((N*3, N*3), np.single) movingArray = np.zeros((N*3, N*3), np.single) for r in range(3): for c in range(3): V = self.get_slicing_matrix(fixedFrame[:,r], movingFrame[:,c]) A = np.zeros((4,4)) A[0:3,0] = V[:,0] A[0:3,1] = V[:,1] A[0:3,2] = V[:,2] A[0,3] = XC[0] A[1,3] = XC[1] A[2,3] = XC[2] A[3,3] = 1.0 resliceAxes = vtk.vtkMatrix4x4() resliceAxes.DeepCopy(A.ravel().tolist()) reslicef = vtk.vtkImageReslice() reslicef.SetInput(fixedVTKImage) reslicef.SetInformationInput(fixedVTKImage) reslicef.SetOutputExtent(0, N-1, 0, N-1, 0, 0) reslicef.SetOutputDimensionality(2) reslicef.SetResliceAxes(resliceAxes) reslicef.SetInterpolationModeToLinear() reslicef.Update() fixedSlice = vtk.util.numpy_support.vtk_to_numpy( reslicef.GetOutput().GetPointData().GetScalars() ).reshape(N, N) fixedSlice = np.transpose(fixedSlice) fixedArray[r*N:(r+1)*N, c*N:(c+1)*N] = fixedSlice resliceAxes = vtk.vtkMatrix4x4() resliceAxes.DeepCopy(A.ravel().tolist()) reslicef = vtk.vtkImageReslice() reslicef.SetInput(movingVTKImage) reslicef.SetInformationInput(movingVTKImage) reslicef.SetOutputExtent(0, N-1, 0, N-1, 0, 0) reslicef.SetOutputDimensionality(2) reslicef.SetResliceAxes(resliceAxes) reslicef.SetInterpolationModeToLinear() reslicef.Update() movingSlice = vtk.util.numpy_support.vtk_to_numpy( reslicef.GetOutput().GetPointData().GetScalars() ).reshape(N, N) movingSlice = np.transpose(movingSlice) movingArray[r*N:(r+1)*N, c*N:(c+1)*N] = movingSlice # # Display panel of views with blending slider # def normalize(arr): minv = arr.min() maxv = arr.max() rangev = maxv - minv if rangev <= 0.0: return arr return (arr - minv) / rangev fixedArray = normalize(fixedArray) movingArray = normalize(movingArray) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetWindowName("Image Alignment Query") renWin.SetSize(800, 800) renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) dataImporter = vtk.vtkImageImport() fixedArray_vtkorder = np.asfortranarray(fixedArray) fixedArray_vtkorder = fixedArray.transpose() ##dataImporter.CopyImportVoidPointer(fixedArray_vtkorder, fixedArray_vtkorder.nbytes) #dataImporter.CopyImportVoidPointer(fixedArray, fixedArray.nbytes) displayArray = np.uint8(fixedArray * 255) dataImporter.CopyImportVoidPointer(displayArray, displayArray.nbytes) #dataImporter.SetDataScalarTypeToFloat() dataImporter.SetDataScalarTypeToUnsignedChar() dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0, N*3-1, 0, N*3-1, 0, 0) dataImporter.SetWholeExtent(0, N*3-1, 0, N*3-1, 0, 0) dataImporter.Update() imageActor = vtk.vtkImageActor() imageActor.SetInput(dataImporter.GetOutput()) imageActor.SetPosition(100.0, 100.0, 0.0) imageActor.SetZSlice(0) imageActor.PickableOn() imageStyle = vtk.vtkInteractorStyleImage() iren.SetInteractorStyle(imageStyle) ren.AddActor(imageActor) def slider_callback(obj, event): # Get slider value alpha = obj.GetRepresentation().GetValue() displayArray = fixedArray * alpha + movingArray * (1.0 - alpha) #minI = displayArray.min() #maxI = displayArray.max() #displayArray = (displayArray - minI) / (maxI - minI) * 255 #displayArray = np.uint8(displayArray) #displayArray = np.uint8(normalize(displayArray) * 255) displayArray = np.uint8(displayArray * 255) dataImporter.CopyImportVoidPointer(displayArray, displayArray.nbytes) sliderRep = vtk.vtkSliderRepresentation2D() sliderRep.SetMinimumValue(0.0) sliderRep.SetMaximumValue(1.0) sliderRep.SetValue(1.0) #sliderRep.SetTitleText("Fixed vs moving") sliderRep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() sliderRep.GetPoint1Coordinate().SetValue(0.2, 0.1) sliderRep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() sliderRep.GetPoint2Coordinate().SetValue(0.8, 0.1) sliderWidget = vtk.vtkSliderWidget() sliderWidget.SetInteractor(iren) sliderWidget.SetRepresentation(sliderRep) sliderWidget.AddObserver("InteractionEvent", slider_callback) sliderWidget.EnabledOn() #ren.InteractiveOff() renWin.AddRenderer(ren) picker = vtk.vtkPropPicker() #picker = vtk.vtkWorldPointPicker() picker.PickFromListOn() picker.AddPickList(imageActor) self.queryRowColumn = (0, 0) def pick_callback(obj, event): mousePos = obj.GetEventPosition() picker.PickProp(mousePos[0], mousePos[1], ren) p = picker.GetPickPosition() c = round( (p[0]-100) / (3*N) * 2 ) r = round( (p[1]-100) / (3*N) * 2 ) if r < 0 or r >= 3 or c < 0 or c >= 3: print "Outside" return print "Image row", r, "col", c self.queryRowColumn = (r, c) iren.GetRenderWindow().Finalize() iren.TerminateApp() iren.SetPicker(picker) iren.AddObserver("LeftButtonPressEvent", pick_callback) renWin.Render() iren.Start() # Return selection of a view in panel r, c = self.queryRowColumn fixedSlice = fixedArray[r*N:(r+1)*N, c*N:(c+1)*N] movingSlice = movingArray[r*N:(r+1)*N, c*N:(c+1)*N] return fixedSlice, movingSlice, fixedFrame[:,r], movingFrame[:,c]
SliderRepres.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint1Coordinate().SetValue(0.3, 0.05) SliderRepres.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint2Coordinate().SetValue(0.7, 0.05) SliderRepres.SetSliderLength(0.02) SliderRepres.SetSliderWidth(0.03) SliderRepres.SetEndCapLength(0.01) SliderRepres.SetEndCapWidth(0.03) SliderRepres.SetTubeWidth(0.005) SliderRepres.SetTitleHeight(0.02) SliderRepres.SetLabelHeight(0.02) SliderRepres.GetSelectedProperty().SetColor(0,1,0) SliderWidget = vtk.vtkSliderWidget() SliderWidget.SetInteractor(iren) SliderWidget.SetRepresentation(SliderRepres) SliderWidget.KeyPressActivationOff() SliderWidget.SetAnimationModeToAnimate() SliderWidget.SetEnabled(True) SliderWidget.AddObserver("EndInteractionEvent", vtkSliderCallback2) # Execute the Pipeline renWin.Render() # initialize and start the interactor iren.Initialize() iren.Start()
def Main(): global continuousSize, continuousType, continuousData, contours, planeSource1s, planeSource2s, planeSource3s, plane1s, plane2s, plane3s, clipper1s, clipper2s, clipper3s, clipX, clipY, clipZ, lut print "data: %s" % sys.argv[1] reader = vtk.vtkStructuredPointsReader() reader.SetFileName(sys.argv[1]) reader.Update() print "gradientmag: %s" % sys.argv[2] gmreader = vtk.vtkStructuredPointsReader() gmreader.SetFileName(sys.argv[2]) gmreader.Update() continuousSize = 0 continuousType = "HSV" continuousData = [] print "params: %s" % sys.argv[3] loadParamsFile(sys.argv[3]) clipX = 0 clipY = 0 clipZ = 0 r = reader.GetOutput().GetScalarRange() datamin = r[0] datamax = r[1] for i in range(4, len(sys.argv)): if sys.argv[i] == "--clip": print "clip (%s,%s,%s)" % (sys.argv[i + 1], sys.argv[i + 2], sys.argv[i + 3]) clipX = float(sys.argv[i + 1]) clipY = float(sys.argv[i + 2]) clipZ = float(sys.argv[i + 3]) clipperActors = [] planeSource1s = [] planeSource2s = [] planeSource3s = [] plane1s = [] plane2s = [] plane3s = [] clipper1s = [] clipper2s = [] clipper3s = [] for i in range(0, len(continuousData)): contours = vtk.vtkContourFilter() contours.SetInputConnection(reader.GetOutputPort()) contours.ComputeNormalsOn() contours.SetValue(0, float(continuousData[i][0])) planeSource1s.append(vtk.vtkPlaneSource()) planeSource1s[i].SetNormal(1, 0, 0) planeSource1s[i].SetOrigin(clipX, 0, 0) plane1s.append(vtk.vtkPlane()) plane1s[i].SetNormal(planeSource1s[i].GetNormal()) plane1s[i].SetOrigin(planeSource1s[i].GetOrigin()) clipper1s.append(vtk.vtkClipPolyData()) clipper1s[i].SetClipFunction(plane1s[i]) clipper1s[i].SetInputConnection(contours.GetOutputPort()) clipper1s[i].Update() planeSource2s.append(vtk.vtkPlaneSource()) planeSource2s[i].SetNormal(0, 1, 0) planeSource2s[i].SetOrigin(0, clipY, 0) plane2s.append(vtk.vtkPlane()) plane2s[i].SetNormal(planeSource2s[i].GetNormal()) plane2s[i].SetOrigin(planeSource2s[i].GetOrigin()) clipper2s.append(vtk.vtkClipPolyData()) clipper2s[i].SetClipFunction(plane2s[i]) clipper2s[i].SetInputConnection(clipper1s[i].GetOutputPort()) clipper2s[i].Update() planeSource3s.append(vtk.vtkPlaneSource()) planeSource3s[i].SetNormal(0, 0, 1) planeSource3s[i].SetOrigin(0, 0, clipZ) plane3s.append(vtk.vtkPlane()) plane3s[i].SetNormal(planeSource3s[i].GetNormal()) plane3s[i].SetOrigin(planeSource3s[i].GetOrigin()) clipper3s.append(vtk.vtkClipPolyData()) clipper3s[i].SetClipFunction(plane3s[i]) clipper3s[i].SetInputConnection(clipper2s[i].GetOutputPort()) clipper3s[i].Update() probeFilter = vtk.vtkProbeFilter() probeFilter.SetInputConnection(0, clipper3s[i].GetOutputPort()) probeFilter.SetInputConnection(1, gmreader.GetOutputPort()) probeFilter.Update() gmrange = probeFilter.GetOutput().GetScalarRange() gmin = gmrange[0] gmax = gmrange[1] gmclipper1 = vtk.vtkClipPolyData() gmclipper1.SetInputConnection(probeFilter.GetOutputPort()) gmclipper1.InsideOutOff() gmclipper1.SetValue(int(continuousData[i][1])) gmclipper1.Update() gmclipper2 = vtk.vtkClipPolyData() gmclipper2.SetInputConnection(gmclipper1.GetOutputPort()) gmclipper2.InsideOutOn() gmclipper2.SetValue(int(continuousData[i][2])) gmclipper2.Update() lut = vtk.vtkColorTransferFunction() if continuousType == "HSV": lut.SetColorSpaceToHSV() p = continuousData[i] print "Color: %s" % p lut.AddHSVPoint(p[0], p[3], p[4], p[5]) elif continuousType == "RGB": lut.SetColorSpaceToRGB() p = continuousData[i] print "Color: %s" % p lut.AddRGBPoint(p[0], p[3], p[4], p[5]) clipperMapper = vtk.vtkPolyDataMapper() clipperMapper.SetLookupTable(lut) clipperMapper.SetInputConnection(gmclipper2.GetOutputPort()) clipperActors.append(vtk.vtkActor()) clipperActors[i].GetProperty().SetRepresentationToWireframe() clipperActors[i].SetMapper(clipperMapper) backFaces = vtk.vtkProperty() backFaces.SetSpecular(0) backFaces.SetDiffuse(0) backFaces.SetAmbient(0) backFaces.SetAmbientColor(1, 0, 0) clipperActors[i].SetBackfaceProperty(backFaces) lut_color = vtk.vtkColorTransferFunction() for d in continuousData: if continuousType == "HSV": lut_color.SetColorSpaceToHSV() lut_color.AddHSVPoint(d[0], d[3], d[4], d[5]) elif continuousType == "RGB": lut_color.SetColorSpaceToRGB() lut_color.AddRGBPoint(d[0], d[3], d[4], d[5]) colorMapper = vtk.vtkPolyDataMapper() colorMapper.SetLookupTable(lut_color) colorBar = vtkScalarBarActor() colorBar.SetLookupTable(colorMapper.GetLookupTable()) colorBar.SetTitle("isovalue") colorBar.SetNumberOfLabels(6) colorBar.SetLabelFormat("%4.0f") colorBar.SetPosition(0.9, 0.1) colorBar.SetWidth(0.1) colorBar.SetHeight(0.7) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) for i in range(0, len(clipperActors)): clipperActors[i].GetProperty().SetOpacity( continuousData[i][6]) # load opacity for actor ren.AddActor(clipperActors[i]) ren.AddActor(colorBar) # for depth peeling ren.SetUseDepthPeeling(1) ren.SetMaximumNumberOfPeels(2) # default 4 ren.SetOcclusionRatio(0.1) # default 0 ren.ResetCamera() ren.SetBackground(0.2, 0.3, 0.4) ren.ResetCameraClippingRange() # for depth peeling renWin.SetAlphaBitPlanes(1) renWin.SetMultiSamples(0) renWin.SetSize(1200, 600) clipXSlider = vtk.vtkSliderRepresentation2D() clipXSlider.SetMinimumValue(0) clipXSlider.SetMaximumValue(300) clipXSlider.SetValue(clipX) clipXSlider.SetTitleText("X") clipXSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() clipXSlider.GetPoint1Coordinate().SetValue(0.0, 0.3) clipXSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() clipXSlider.GetPoint2Coordinate().SetValue(0.2, 0.3) clipXSlider.SetSliderLength(0.02) clipXSlider.SetSliderWidth(0.03) clipXSlider.SetEndCapLength(0.01) clipXSlider.SetEndCapWidth(0.03) clipXSlider.SetTubeWidth(0.005) clipXSlider.SetLabelFormat("%1.2lf") clipXSlider.SetTitleHeight(0.02) clipXSlider.SetLabelHeight(0.02) SliderWidget2 = vtk.vtkSliderWidget() SliderWidget2.SetInteractor(iren) SliderWidget2.SetRepresentation(clipXSlider) SliderWidget2.KeyPressActivationOff() SliderWidget2.SetAnimationModeToAnimate() SliderWidget2.SetEnabled(True) SliderWidget2.AddObserver("InteractionEvent", clipXSliderHandler) clipYSlider = vtk.vtkSliderRepresentation2D() clipYSlider.SetMinimumValue(0) clipYSlider.SetMaximumValue(300) clipYSlider.SetValue(clipY) clipYSlider.SetTitleText("Y") clipYSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() clipYSlider.GetPoint1Coordinate().SetValue(0.0, 0.2) clipYSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() clipYSlider.GetPoint2Coordinate().SetValue(0.2, 0.2) clipYSlider.SetSliderLength(0.02) clipYSlider.SetSliderWidth(0.03) clipYSlider.SetEndCapLength(0.01) clipYSlider.SetEndCapWidth(0.03) clipYSlider.SetTubeWidth(0.005) clipYSlider.SetLabelFormat("%1.2lf") clipYSlider.SetTitleHeight(0.02) clipYSlider.SetLabelHeight(0.02) SliderWidget3 = vtk.vtkSliderWidget() SliderWidget3.SetInteractor(iren) SliderWidget3.SetRepresentation(clipYSlider) SliderWidget3.KeyPressActivationOff() SliderWidget3.SetAnimationModeToAnimate() SliderWidget3.SetEnabled(True) SliderWidget3.AddObserver("InteractionEvent", clipYSliderHandler) clipZSlider = vtk.vtkSliderRepresentation2D() clipZSlider.SetMinimumValue(0) clipZSlider.SetMaximumValue(300) clipZSlider.SetValue(clipZ) clipZSlider.SetTitleText("Z") clipZSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() clipZSlider.GetPoint1Coordinate().SetValue(0.0, 0.1) clipZSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() clipZSlider.GetPoint2Coordinate().SetValue(0.2, 0.1) clipZSlider.SetSliderLength(0.02) clipZSlider.SetSliderWidth(0.03) clipZSlider.SetEndCapLength(0.01) clipZSlider.SetEndCapWidth(0.03) clipZSlider.SetTubeWidth(0.005) clipZSlider.SetLabelFormat("%1.2lf") clipZSlider.SetTitleHeight(0.02) clipZSlider.SetLabelHeight(0.02) SliderWidget4 = vtk.vtkSliderWidget() SliderWidget4.SetInteractor(iren) SliderWidget4.SetRepresentation(clipZSlider) SliderWidget4.KeyPressActivationOff() SliderWidget4.SetAnimationModeToAnimate() SliderWidget4.SetEnabled(True) SliderWidget4.AddObserver("InteractionEvent", clipZSliderHandler) # Render iren.Initialize() renWin.Render() iren.Start()
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 om_display_vtk(f,d = 0,n = 0): """ This function displays a VTK::vtk file generated with OpenMEEG. Such a file defines a polydata, containing points and triangles of a single mesh. Most often a EEG helmet mesh and associated leadfield. """ welcome = """Welcome\n\n Move the slider to see all sources (columns of the input matrix)\n Press 'r': To select points/cells.\n""" # This callback function does updates the mappers for where n is the slider value def CleanPickData(object, event): ren.RemoveActor(selactor) PickData(object, event, selactor, 0, view, text_init) def SelectSource(object, event): # object will be the slider2D slidervalue = int(round(object.GetRepresentation().GetValue())) mapper.GetInput().GetPointData().SetActiveScalars("Potentials-"+str(slidervalue)) renWin.SetWindowName(renWin.GetWindowName()[0:(renWin.GetWindowName().find('-')+1)]+str(slidervalue)) UpdateColorBar(colorBar, mapper) # A window with an interactor renWin = vtk.vtkRenderWindow() renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) # A picker (to pick points/cells) picker = vtk.vtkRenderedAreaPicker() iren.SetPicker(picker) # Read the input file reader = vtk.vtkPolyDataReader() reader.SetFileName(f); reader.Update() poly = reader.GetOutput() renWin.SetWindowName(f+' Potentials-'+str(n)) # determine the number of sources nb_sources = 0 for i in range(poly.GetPointData().GetNumberOfArrays()): if poly.GetPointData().GetGlobalIds('Potentials-'+str(i)): nb_sources += 1 if nb_sources == 0: #the file doesn't provide potentials if not d.__class__ == int: assert(d.shape[0] == poly.GetNumberOfPoints()) nb_sources = d.shape[1] pot = [vtk.vtkDoubleArray() for j in range(d.shape[1])] for j in range(d.shape[1]): pot[j].SetName('Potentials-'+str(j)) for i in range(d.shape[0]): pot[j].InsertNextValue(d[i,j]) poly.GetPointData().AddArray(pot[j]) poly.Update() if not poly.GetPointData().GetGlobalIds('Indices'): ind = vtk.vtkUnsignedIntArray() ind.SetName('Indices') for i in range(poly.GetNumberOfPoints()): ind.InsertNextValue(i) poly.GetPointData().AddArray(ind) poly.GetPointData().SetActiveScalars('Potentials-'+str(n)) mapper = vtk.vtkPolyDataMapper() colorBar = vtk.vtkScalarBarActor() actor = vtk.vtkActor() ren = vtk.vtkRenderer() mapper.SetInput(poly) mapper.SetScalarModeToUsePointData(); mapper.Update() actor.SetMapper(mapper) ren.AddActor(actor) if nb_sources: ren.AddActor2D(colorBar) UpdateColorBar(colorBar, mapper) renWin.AddRenderer(ren) renWin.Render() if nb_sources > 1: # Slider sliderWidget = vtk.vtkSliderWidget() slider = vtk.vtkSliderRepresentation2D(); slider.SetMaximumValue(nb_sources-1) slider.SetValue(n); slider.SetEndCapLength(0.01); slider.SetLabelFormat('%1.0f') slider.SetSliderWidth(0.05); slider.SetSliderLength(1./nb_sources) slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport() slider.GetPoint1Coordinate().SetValue(.0, 0.02) slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport() slider.GetPoint2Coordinate().SetValue(1., 0.02); sliderWidget.SetInteractor(iren); sliderWidget.SetRepresentation(slider); sliderWidget.SetAnimationModeToAnimate(); sliderWidget.EnabledOn(); sliderWidget.AddObserver("InteractionEvent", SelectSource); # Selection selactor = vtk.vtkActor() view = vtk.vtkContextView(); view.GetRenderWindow().SetWindowName('Plot') view.GetRenderWindow().SetPosition(600, 0); view.GetRenderWindow().SetSize(600, 600) # Welcome text text_init = vtk.vtkTextActor() text_init.SetPosition(10, 300) text_init.SetInput(welcome) text_init.GetTextProperty().SetColor(1.0, 0.0, 0.0) view.GetRenderer().AddActor2D(text_init) view.GetInteractor().Initialize() iren.AddObserver(vtk.vtkCommand.EndPickEvent,CleanPickData) iren.Initialize() iren.Start()
def om_display_vtp(f, n = 0): """ This function displays a VTK::vtp file generated with OpenMEEG. Such a file defines a polydata, containing points and triangles of several meshes which are labelled through a vtkAbstractArray (Strings) associated to the cells (mesh names). Results of the forward problem (or a cortical mapping) can be seen thanks to arrays associated to points and cells (respectively potentials and normals currents). """ welcome = """Welcome\n\n Switch the button: To either see Potentials (on points) or Currents (on triangles)\n Move the slider to see all sources (columns of the input matrix)\n Press 'r': To select points/cells.\n""" # This callback function does updates the mappers for where n is the slider value def CleanPickData(object, event): for i in range(4): rens[i].RemoveActor(selactor) if buttonWidget.GetRepresentation().GetState(): PickData(object, event, selactor, 1, view, text_init) else: PickData(object, event, selactor, 0, view, text_init) def SelectSource(object, event): # object will be the slider2D slidervalue = int(round(object.GetRepresentation().GetValue())) for i in range(4): mappers[i].GetInput().GetPointData().SetActiveScalars("Potentials-"+str(slidervalue)) mappers[i].GetInput().GetCellData().SetActiveScalars("Currents-"+str(slidervalue)) renWin.SetWindowName(renWin.GetWindowName()[0:(renWin.GetWindowName().find('-')+1)]+str(slidervalue)) UpdateColorBar(colorBars[i], mappers[i]) # This callback function does updates the Scalar Mode To Use def SelectMode(object, event): # object will be the buttonWidget for i in range(4): if (object.GetRepresentation().GetState()): mappers[i].SetScalarModeToUseCellData() renWin.SetWindowName(renWin.GetWindowName().replace('Potentials','Currents')) else: mappers[i].SetScalarModeToUsePointData() renWin.SetWindowName(renWin.GetWindowName().replace('Currents','Potentials')) UpdateColorBar(colorBars[i], mappers[i]) # A window with an interactor renWin = vtk.vtkRenderWindow() renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) # A picker (to pick points/cells) picker = vtk.vtkRenderedAreaPicker() iren.SetPicker(picker) # Read the input file reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(f); reader.Update() poly = reader.GetOutput() renWin.SetWindowName(f+' Potentials-'+str(n)) # determine the number of sources nb_sources = 0 for i in range(poly.GetPointData().GetNumberOfArrays()): if poly.GetPointData().GetGlobalIds('Potentials-'+str(i)): nb_sources += 1 if n < nb_sources: poly.GetPointData().SetActiveScalars('Potentials-'+str(n)) poly.GetCellData().SetActiveScalars('Currents-'+str(n)) # Get the mesh names cell_labels = poly.GetCellData().GetAbstractArray(0) assert(cell_labels.GetName()=='Names') s = set(); nb_meshes = 0; cell_ids = list() for i in range(cell_labels.GetNumberOfValues()): s.add(cell_labels.GetValue(i)) if len(s)>nb_meshes: # if a label is added, store the ID for the connectivity filter cell_ids.append(i) nb_meshes += 1 # Number of meshes assert(nb_meshes<=4) # Multiple viewports: 4 xmins = [0,.5,0,.5]; xmaxs = [0.5,1,0.5,1]; ymins = [0,0,.5,.5]; ymaxs = [0.5,0.5,1,1] mappers = [vtk.vtkPolyDataMapper() for i in range(4)] colorBars = [vtk.vtkScalarBarActor() for i in range(4)] actors = [vtk.vtkActor() for i in range(4)] rens = [vtk.vtkRenderer() for i in range(4)] for i in range(4): rens[i].SetViewport(xmins[i],ymins[i],xmaxs[i],ymaxs[i]); # Display the meshes if (i < nb_meshes): # Create a connectivity filter based on cell seeded region (to display # only one mesh per viewport) conn = vtk.vtkPolyDataConnectivityFilter() conn.SetInput(poly) conn.SetExtractionModeToCellSeededRegions() conn.AddSeed(cell_ids[i]); conn.Update() actor_meshname = vtk.vtkTextActor(); actor_meshname.SetInput(cell_labels.GetValue(cell_ids[i])); actor_meshname.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport(); actor_meshname.SetPosition(0.5, 0.85); tprop = actor_meshname.GetTextProperty(); tprop.SetFontSize(30) tprop.SetFontFamilyToArial(); tprop.SetColor(1, 1, 1); tprop.SetJustificationToCentered() mappers[i].SetInputConnection(conn.GetOutputPort()) mappers[i].SetScalarModeToUsePointData(); mappers[i].Update() if nb_sources: rens[i].AddActor2D(colorBars[i]) actors[i].SetMapper(mappers[i]) rens[i].AddActor2D(actor_meshname) rens[i].AddActor(actors[i]) if (i == 0): cam = rens[i].GetActiveCamera() rens[i].ResetCamera() else: # Create a plane to cut plane = vtk.vtkPlane(); plane.SetOrigin(0,0,0); plane.SetNormal(1,0,0); # Create cutter extract = vtk.vtkExtractPolyDataGeometry(); extract.SetInput(poly) extract.SetImplicitFunction(plane); extract.ExtractBoundaryCellsOff() mappers[i].SetInputConnection(extract.GetOutputPort()) mappers[i].SetScalarModeToUsePointData(); mappers[i].Update() # Create plane actor actors[i].SetMapper(mappers[i]) rens[i].AddActor(actors[i]) rens[i].SetActiveCamera(cam) if nb_sources: UpdateColorBar(colorBars[i], mappers[i]) renWin.AddRenderer(rens[i]) renWin.Render(); if nb_sources > 1: # Slider sliderWidget = vtk.vtkSliderWidget() slider = vtk.vtkSliderRepresentation2D(); slider.SetMaximumValue(nb_sources-1) slider.SetValue(n); slider.SetEndCapLength(0.01); slider.SetLabelFormat('%1.0f') slider.SetSliderWidth(0.05); slider.SetSliderLength(1./nb_sources) slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport() slider.GetPoint1Coordinate().SetValue(.0 ,0.02) slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport() slider.GetPoint2Coordinate().SetValue(1. ,0.02); sliderWidget.SetInteractor(iren); sliderWidget.SetRepresentation(slider); sliderWidget.SetAnimationModeToAnimate(); sliderWidget.EnabledOn(); sliderWidget.AddObserver("InteractionEvent", SelectSource); if not nb_sources == 0: # The button for choosing Potentials/Currents buttonWidget = vtk.vtkButtonWidget() button = vtk.vtkTexturedButtonRepresentation2D(); button.SetNumberOfStates(2) tex1r = vtk.vtkImageData(); tex2r = vtk.vtkImageData(); prop = vtk.vtkTextProperty(); prop.SetFontSize(24); prop.SetColor(1,0,0); prop.SetBold(2); prop.SetShadow(2); str2im = vtk.vtkFreeTypeStringToImage() str2im.RenderString(prop,'Potentials',tex1r) str2im.RenderString(prop,'Currents',tex2r) button.SetButtonTexture(0, tex1r) button.SetButtonTexture(1, tex2r) buttonWidget.SetInteractor(iren); buttonWidget.SetRepresentation(button); button.SetPlaceFactor(1); button.PlaceWidget([0., 100, 50, 500, 0, 0]); buttonWidget.On() buttonWidget.AddObserver(vtk.vtkCommand.StateChangedEvent,SelectMode); # Selection selactor = vtk.vtkActor() view = vtk.vtkContextView(); view.GetRenderWindow().SetWindowName('Plot') view.GetRenderWindow().SetPosition(600, 0); view.GetRenderWindow().SetSize(600, 600) # Welcome text text_init = vtk.vtkTextActor() text_init.SetPosition(10, 300) text_init.SetInput(welcome) text_init.GetTextProperty().SetColor(1.0, 0.0, 0.0) view.GetRenderer().AddActor2D(text_init) view.GetInteractor().Initialize() iren.AddObserver(vtk.vtkCommand.EndPickEvent,CleanPickData) iren.Initialize() iren.Start()
def add_widgets(self): # axes axes = vtk.vtkAxesActor() self.marker_widget = vtk.vtkOrientationMarkerWidget() self.marker_widget.SetInteractor(self.iren) self.marker_widget.SetOrientationMarker(axes) self.marker_widget.SetViewport(0.0, 0.0, 0.25, 0.25) # scalar bar self.scalarbar_actor = vtk.vtkScalarBarActor() self.scalarbar_actor.SetLookupTable(self.lut) self.scalarbar_widget = vtk.vtkScalarBarWidget() self.scalarbar_widget.SetInteractor(self.iren) self.scalarbar_widget.SetScalarBarActor(self.scalarbar_actor) # contour slider self.slider_rep = vtk.vtkSliderRepresentation2D() self.slider_rep.SetTitleText("contour") self.slider_rep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport() self.slider_rep.GetPoint1Coordinate().SetValue(0.65, 0.1) self.slider_rep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport() self.slider_rep.GetPoint2Coordinate().SetValue(0.95, 0.1) self.slider_widget = vtk.vtkSliderWidget() self.slider_widget.SetInteractor(self.iren) self.slider_widget.SetRepresentation(self.slider_rep) self.slider_widget.SetAnimationModeToAnimate() self.slider_widget.AddObserver(vtk.vtkCommand.InteractionEvent, self.update_contour);