def ExtractGeometryZ(pd, nx, ny, nz, z0): """ cut the mesh using z > z0 could try vtkClipPolyData too """ filter = vtk.vtkExtractPolyDataGeometry() function = vtk.vtkPlane() function.SetNormal(nx, ny, nz) function.SetOrigin(0, 0, z0) triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(pd) triangleFilter.Update() filter.SetImplicitFunction(function) filter.SetInputData(triangleFilter.GetOutput()) filter.Update() #geometryFilter = vtk.vtkGeometryFilter() #geometryFilter.SetInputData(filter.GetOutput()) #geometryFilter.Update() connectFilter = vtk.vtkPolyDataConnectivityFilter() connectFilter.SetExtractionModeToLargestRegion() connectFilter.SetInputData(filter.GetOutput()) connectFilter.Update() return connectFilter.GetOutput()
def extractDataSetByBounds(fullvtkDataSet, boundvtkDataSet): """ Function to extract from a vtkDataSet within bounds of another vtkDataSet. Returns a extrct filter """ # Define a bounding box implicit if boundvtkDataSet.IsA('vtkDataSet'): impFunc = vtk.vtkBox() impFunc.SetBounds(boundvtkDataSet.GetBounds()) elif boundvtkDataSet.IsA('vtkImplicitFunction'): impFunc = boundvtkDataSet # Extract all inside and boundaries if fullvtkDataSet.IsA('vtkPolyData'): extractFilt = vtk.vtkExtractPolyDataGeometry() else: extractFilt = vtk.vtkExtractGeometry() extractFilt.SetExtractInside(1) extractFilt.SetExtractBoundaryCells(1) extractFilt.SetInputData(fullvtkDataSet) extractFilt.SetImplicitFunction(impFunc) extractFilt.Update() return extractFilt
def _ClipModel(self, plane, surface): """Clips surface and returns full cells on the plane i.e. does not produce flat output""" clipper = vtk.vtkExtractPolyDataGeometry() clipper.SetInputData(surface) clipper.SetImplicitFunction(plane) clipper.Update() return clipper
def extractDataSetWithPolygon(vtkDataSet, vtkPoly, returnImpDist=False, extInside=True, extBoundaryCells=True, extractBounds=False): """ Function to extract cells from a vtkDataSet, given polygon/s in a vtkPolyData. Returns a full cells that fall fully inside/outside and/or on the polygon boundary. """ # Make a implicit function impDist = convertToImplicitPolyDataDistance(vtkPoly) # Reduce the data to the bounds # Reduce the data to the bounds if extractBounds: extBoundsFilt = extractDataSetByBounds(vtkDataSet, vtkPoly) else: extBoundsFilt = extractDataSetByBounds(vtkDataSet, vtkDataSet) # If input is a vtkPolyData if vtkDataSet.IsA('vtkPolyData'): extractFilt = vtk.vtkExtractPolyDataGeometry() else: extractFilt = vtk.vtkExtractGeometry() extractFilt.SetExtractInside(extInside + 0) extractFilt.SetExtractBoundaryCells(extBoundaryCells + 0) extractFilt.SetInputConnection(extBoundsFilt.GetOutputPort()) extractFilt.SetImplicitFunction(impDist) extractFilt.Update() if returnImpDist: return extractFilt.GetOutput(), impDist else: return extractFilt.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkExtractPolyDataGeometry(), 'Processing.', ('vtkPolyData',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkExtractPolyDataGeometry(), 'Processing.', ('vtkPolyData', ), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self, size=4, color=(0.9, 0.9, 0.9), **kwargs): kwargs["color"] = color kwargs["size"] = size self.poly_data = vtk.vtkPolyData() self.extractor = vtk.vtkExtractPolyDataGeometry() self.extractor.SetInput(self.poly_data) self.constant_function = vtk.vtkQuadric() self.constant_function.SetCoefficients(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0) # Filter disabled by default self.extractor.SetImplicitFunction(self.constant_function) self.frustum = None self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(self.extractor.GetOutputPort()) self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self._process_kwargs(**kwargs)
def __init__(self, param_farplane_threshold=1.0, param_convolution_threshold=0.01): """ Algorithm setup and define parameters. :param param_farplane_threshold: default=1.0 Values on the depth image range from 0.0-1.0. Points with depth values greater than param_farplane_threshold will be thrown away. :param param_convolution_threshold: default=0.01 Convolution is used to determine pixel neighbors with a large difference. If there is one, the point will be thrown away. This threshold controls sensitivity. """ VTKPythonAlgorithmBase.__init__(self, nInputPorts=1, inputType='vtkImageData', nOutputPorts=1, outputType='vtkPolyData') self._param_farplane_threshold = param_farplane_threshold self.param_convolution_theshold = param_convolution_threshold self._sizex = [] self._sizey = [] self._viewport = [] self._display_pts = [] self._viewport_pts = [] self._world_pts = [] self._points = vtk.vtkPoints() self._polys = vtk.vtkCellArray() self._polydata = vtk.vtkPolyData() self._polydata.SetPoints(self._points) self._polydata.SetPolys(self._polys) self._extract = vtk.vtkExtractPolyDataGeometry() DebugTimeVTKFilter(self._extract) self._extract.SetInputData(self._polydata) planefunc = vtk.vtkPlane() planefunc.SetNormal(0.0, -1.0, 0.0) planefunc.SetOrigin(0.0, -1.0, 0.0) self._extract.SetImplicitFunction(planefunc)
def runGeoJSONCropExample(input_filename, bbox_filename): inputDataset = loadGeoJSONData(input_filename) bboxDataset = loadGeoJSONData(bbox_filename) # Use the bounds from the bounding box to create an implicit function queryBounds = list(bboxDataset.GetBounds()) bbox = vtk.vtkPlanes() bbox.SetBounds(queryBounds) # This filter uses the implicit function to extract the data bboxFilter = vtk.vtkExtractPolyDataGeometry() bboxFilter.SetInputData(inputDataset) bboxFilter.SetImplicitFunction(bbox) # Exclude (set to 0) or include (set to 1) districts on the boundary bboxFilter.SetExtractBoundaryCells(0) # Get the cropped region and write it to disk bboxFilter.Update() croppedDataset = bboxFilter.GetOutput() outputWriter = vtk.vtkGeoJSONWriter() outputWriter.SetFileName('cropped_output.geojson') outputWriter.SetInputData(croppedDataset) outputWriter.Write() renderer = init() inputActor = renderPolyData(renderer, inputDataset) bboxActor = renderPolyData(renderer, bboxDataset) cropActor = renderPolyData(renderer, croppedDataset) # Set rendering type and color on the actors inputActor.GetProperty().SetRepresentationToWireframe() inputActor.GetProperty().SetColor(0.0, 1.0, 0.0) bboxActor.GetProperty().SetRepresentationToWireframe() bboxActor.GetProperty().SetColor(1.0, 0.0, 0.0) cropActor.GetProperty().SetRepresentationToWireframe() cropActor.GetProperty().SetColor(1.0, 0.0, 1.0) run()
# Demonstrate how to extract polygonal cells with an implicit function # get the interactor ui # create a sphere source and actor # sphere = vtk.vtkSphereSource() sphere.SetThetaResolution(8) sphere.SetPhiResolution(16) sphere.SetRadius(1.5) # Extraction stuff t = vtk.vtkTransform() t.RotateX(90) cylfunc = vtk.vtkCylinder() cylfunc.SetRadius(0.5) cylfunc.SetTransform(t) extract = vtk.vtkExtractPolyDataGeometry() extract.SetInputConnection(sphere.GetOutputPort()) extract.SetImplicitFunction(cylfunc) extract.ExtractBoundaryCellsOn() extract.PassPointsOn() sphereMapper = vtk.vtkPolyDataMapper() sphereMapper.SetInputConnection(extract.GetOutputPort()) sphereMapper.GlobalImmediateModeRenderingOn() sphereActor = vtk.vtkActor() sphereActor.SetMapper(sphereMapper) # Extraction stuff - now cull points extract2 = vtk.vtkExtractPolyDataGeometry() extract2.SetInputConnection(sphere.GetOutputPort()) extract2.SetImplicitFunction(cylfunc) extract2.ExtractBoundaryCellsOn()
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 doWrap(Act,wc,wrap=[0.,360], fastClip=True): if wrap is None: return Act Mapper = Act.GetMapper() data = Mapper.GetInput() xmn=min(wc[0],wc[1]) xmx=max(wc[0],wc[1]) if numpy.allclose(xmn,1.e20) or numpy.allclose(xmx,1.e20): xmx = abs(wrap[1]) xmn = -wrap[1] ymn=min(wc[2],wc[3]) ymx=max(wc[2],wc[3]) if numpy.allclose(ymn,1.e20) or numpy.allclose(ymx,1.e20): ymx = abs(wrap[0]) ymn = -wrap[0] ## Prepare MultiBlock and puts in oriinal data appendFilter =vtk.vtkAppendPolyData() appendFilter.AddInputData(data) appendFilter.Update() ## X axis wrappping Amn,Amx = Act.GetXRange() if wrap[1]!=0.: i=0 while Amn>xmn: i+=1 Amn-=wrap[1] Tpf = vtk.vtkTransformPolyDataFilter() Tpf.SetInputData(data) T=vtk.vtkTransform() T.Translate(-i*wrap[1],0,0) Tpf.SetTransform(T) Tpf.Update() appendFilter.AddInputData(Tpf.GetOutput()) appendFilter.Update() i=0 while Amx<xmx: i+=1 Amx+=wrap[1] Tpf = vtk.vtkTransformPolyDataFilter() Tpf.SetInputData(data) T = vtk.vtkTransform() T.Translate(i*wrap[1],0,0) Tpf.SetTransform(T) Tpf.Update() appendFilter.AddInputData(Tpf.GetOutput()) appendFilter.Update() # Y axis wrapping Amn,Amx = Act.GetYRange() if wrap[0]!=0.: i=0 while Amn>ymn: i+=1 Amn-=wrap[0] Tpf = vtk.vtkTransformPolyDataFilter() Tpf.SetInputData(data) T = vtk.vtkTransform() T.Translate(0,i*wrap[0],0) Tpf.SetTransform(T) Tpf.Update() appendFilter.AddInputData(Tpf.GetOutput()) appendFilter.Update() i=0 while Amx<ymx: i+=1 Amx+=wrap[0] Tpf = vtk.vtkTransformPolyDataFilter() Tpf.SetInputData(data) T = vtk.vtkTransform() T.Translate(0,-i*wrap[0],0) Tpf.SetTransform(T) Tpf.Update() appendFilter.AddInputData(Tpf.GetOutput()) appendFilter.Update() # Clip the data to the final window: clipBox = vtk.vtkBox() clipBox.SetXMin(xmn, ymn, -1.0) clipBox.SetXMax(xmx, ymx, 1.0) if fastClip: clipper = vtk.vtkExtractPolyDataGeometry() clipper.ExtractInsideOn() clipper.SetImplicitFunction(clipBox) clipper.ExtractBoundaryCellsOn() clipper.PassPointsOff() else: clipper = vtk.vtkClipPolyData() clipper.InsideOutOn() clipper.SetClipFunction(clipBox) clipper.SetInputConnection(appendFilter.GetOutputPort()) clipper.Update() Mapper.SetInputData(clipper.GetOutput()) return Act
def _extract_polygon(self, PolyData, is_clean): self._contour_widget.EnabledOff() print "Init Extracting" self.setCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() polydata_rep = self._contour_representation.GetContourRepresentationAsPolyData() planes = self.get_frustrum() normal = planes.GetNormals() nor = np.array([0,0,0]) normal.GetTuple(5, nor) #progressBar.setValue(10) #QApplication.processEvents() selection = vtkImplicitSelectionLoop() selection.SetLoop(polydata_rep.GetPoints()) selection.SetNormal(nor[0], nor[1], nor[2]) #progressBar.setValue(20) #QApplication.processEvents() tip = vtkImplicitBoolean() tip.AddFunction(selection) tip.AddFunction(planes) tip.SetOperationTypeToIntersection() tip.Modified() #progressBar.setValue(40) #QApplication.processEvents() if is_clean: extractGeometry = vtkExtractPolyDataGeometry() else: extractGeometry = vtkExtractGeometry() extractGeometry.SetInput(PolyData) extractGeometry.SetImplicitFunction(tip) if is_clean: extractGeometry.ExtractInsideOff() extractGeometry.Update() if is_clean: clean = vtkCleanPolyData() clean.SetInputConnection(extractGeometry.GetOutputPort()) clean.Update() #progressBar.setValue(80) #QApplication.processEvents() filter = vtkDataSetSurfaceFilter() if is_clean: filter.SetInputConnection(clean.GetOutputPort()) else: filter.SetInputConnection(extractGeometry.GetOutputPort()) filter.Update() #progressBar.setValue(90) #QApplication.processEvents() self.setCursor(QCursor(Qt.ArrowCursor)) QApplication.processEvents() self.extract_action.setEnabled(False) self.clean_action.setEnabled(False) print "End Extracting" return filter.GetOutput()