def onLeftButtonUp(self, obj, event):
        # Forward events
        self.OnLeftButtonUp()

        frustum = self.GetInteractor().GetPicker().GetFrustum()

        extractGeometry = vtk.vtkExtractGeometry()
        extractGeometry.SetImplicitFunction(frustum)
        extractGeometry.SetInputData(self.Points)
        extractGeometry.Update()

        glyphFilter = vtk.vtkVertexGlyphFilter()
        glyphFilter.SetInputConnection(extractGeometry.GetOutputPort())
        glyphFilter.Update()

        selected = glyphFilter.GetOutput()
        print("Selected " + str(selected.GetNumberOfPoints()) + " points.")
        print("Selected " + str(selected.GetNumberOfCells()) + " cells.")
        self.SelectedMapper.SetInputData(selected)
        self.SelectedMapper.ScalarVisibilityOff()

        ids = selected.GetPointData().GetArray("OriginalIds")

        for i in range(ids.GetNumberOfTuples()):
            print("Id " + str(i) + str(ids.GetValue(i)))

        self.SelectedActor.GetProperty().SetColor(1.0, 0.0, 0.0)  #(R,G,B)
        self.SelectedActor.GetProperty().SetPointSize(3)

        self.GetCurrentRenderer().AddActor(self.SelectedActor)
        self.GetInteractor().GetRenderWindow().Render()
        self.HighlightProp(None)
예제 #2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkExtractGeometry(), 'Processing.',
         ('vtkDataSet',), ('vtkUnstructuredGrid',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
예제 #3
0
    def AdjustColor(self, flag):
        if self.myactor is None:

            self.selection = vtk.vtkExtractGeometry()

            self.selection.SetInputConnection(self.input.GetOutputPort())
            filter = vtk.vtkVertexGlyphFilter()
            filter.SetInputConnection(self.selection.GetOutputPort())
            self.myactor = PolyDataActor(filter.GetOutputPort())
            self.renderer.AddMyActor(self.myactor)

        polydata = vtk.vtkPolyData()
        self.GetPolyData(polydata)
        self.selection.SetImplicitFunction(polydata)
        self.myactor.Update()
        num_points = self.myactor.GetNumberOfPoints()
        print("num of points: ", num_points)
        num_cells = self.myactor.GetNumberOfCells()

        f = self.GetEnabled() if flag else not self.GetEnabled()
        if f:
            color_name = "green"
        else:
            color_name = "red"
        # generate colors
        selected_colors = GenerateColors(num_points, color_name=color_name)

        # set attribution of points
        self.myactor.SetScalars(selected_colors)
예제 #4
0
파일: compare.py 프로젝트: majroy/OpenRS
    def update_volume(self,r,c):
        '''
        Updates inset active volume with an extract filter, assumes sphere with radius r and centre c (tuple)
        '''
        self.sub_ren.RemoveAllViewProps()
        
        
        geo = vtk.vtkSphere()
        geo.SetRadius(r)
        geo.SetCenter(c)

        extract = vtk.vtkExtractGeometry()
        extract.ExtractInsideOn()
        extract.SetInputDataObject(self.active_vtu)
        extract.SetImplicitFunction(geo)
        extract.Update()
        
        # q4 = v2n(extract.GetOutput().GetPointData().GetArray('S11'))
        
        extract_mapper = vtk.vtkDataSetMapper()
        extract_mapper.SetInputData(extract.GetOutput())
        extract_mapper.SetScalarRange(self.active_vtu.GetScalarRange())
        extract_mapper.SetLookupTable(self.mesh_lut)
        

        extract_actor = vtk.vtkActor()
        extract_actor.SetMapper(extract_mapper)
        
        self.sub_ren.AddActor(extract_actor)
        self.sub_ren.ResetCamera()
        self.ui.vtkWidget.update()
예제 #5
0
def getBoundaryNodes(mesh, radius, used_nodes, vprint):
    numPts = mesh.GetNumberOfPoints()
    boundary_nodes = vtk.vtkIdList()
    #First get the points within a sphere on the boundaries using the boundary points as seed points
    for ptID in xrange(0, numPts):
        if (mesh.GetPointData().GetArray('GlobalBoundaryPoints').GetValue(ptID)
                > 0):
            x0, y0, z0 = mesh.GetPoint(ptID)

            neighbrs = vtk.vtkExtractGeometry()
            sphere = vtk.vtkSphere()
            sphere.SetCenter(x0, y0, z0)
            sphere.SetRadius(float(radius))
            neighbrs.SetImplicitFunction(sphere)
            neighbrs.ExtractInsideOn()
            neighbrs.ExtractBoundaryCellsOn()
            neighbrs.SetInputData(mesh)
            neighbrs.Update()

            neighbors = vtk.vtkConnectivityFilter()
            neighbors.SetInputData(neighbrs.GetOutput())
            neighbors.SetExtractionModeToClosestPointRegion()
            neighbors.SetClosestPoint(x0, y0, z0)
            neighbors.Update()
            neighbors = neighbors.GetOutput()
            for neighborID in xrange(0, neighbors.GetNumberOfPoints()):
                meshID = mesh.FindPoint(neighbors.GetPoint(neighborID))
                if (used_nodes.IsId(meshID) < 0):
                    boundary_nodes.InsertNextId(meshID)
                    used_nodes.InsertNextId(meshID)
    writeVTU(neighbors, 'test_extraction.vtu', vprint)
    return [boundary_nodes, used_nodes]
예제 #6
0
    def AddFilter(self, func):
        if not self.GetContinue():
            # reset history
            self.ResetHistory()

        extract_geometry_filter = vtk.vtkExtractGeometry()
        # set filter function
        extract_geometry_filter.SetImplicitFunction(func)

        # connect the last output
        # some bug here, so I use SetInputData() instead.
        # extract_geometry_filter.SetInputConnection(self.last_filters[-1].GetOutputPort())
        extract_geometry_filter.SetInputConnection(
            self.last_filter.GetOutputPort())

        # save last_filter
        self.last_filters.append(self.last_filter)

        # update the last output
        self.last_filter = vtk.vtkVertexGlyphFilter()
        self.last_filter.SetInputConnection(
            extract_geometry_filter.GetOutputPort())

        # append to the list for saving
        self.extract_geometry_filters.append(extract_geometry_filter)

        # set the last filter to the input of mapper
        self.selected_actor.SetInput(self.last_filter.GetOutputPort())
        self.selected_actor.Update()
    def pickCallback(obj, event):
        props = obj.GetProp3Ds()
        if props.GetNumberOfItems() <= 0:
            return

        extract_geometry = vtk.vtkExtractGeometry()
        extract_geometry.SetImplicitFunction(picker.GetFrustum())
        extract_geometry.SetInput(props.GetLastProp3D().GetMapper().GetInput())
        extract_geometry.Update()

        unstructured_grid = extract_geometry.GetOutput()

        if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0:
            return

        visible.Update()
        if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0:
            return

        i = np.intersect1d(
            vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i')),
            vtk_to_numpy(visible.GetOutput().GetPointData().GetArray('i')))

        if i.shape[0] <= 0:
            return

        vtk_points = vtk.vtkPoints()
        vtk_points.SetNumberOfPoints(i.shape[0])
        vtk_points_data = vtk_to_numpy(vtk_points.GetData())
        vtk_points_data.flat = np.require(V[i], np.float32, 'C')

        highlight_poly_data.SetPoints(vtk_points)
        highlight_actor.VisibilityOn()
예제 #8
0
    def LeftButtonReleaseEvent(self, obj, event):
        print("LEFT BUTTON RELEASED")
        self.OnLeftButtonUp()

        self.frustum = self.area_picker.GetFrustum()

        self.extract_geometry = vtk.vtkExtractGeometry()
        self.extract_geometry.SetImplicitFunction(self.frustum)
        self.extract_geometry.SetInputData(self.pointcloud.cm_poly_data)
        self.extract_geometry.Update()

        self.glyph_filter = vtk.vtkVertexGlyphFilter()
        self.glyph_filter.SetInputConnection(
            self.extract_geometry.GetOutputPort())
        self.glyph_filter.Update()

        self.selected = self.glyph_filter.GetOutput()
        self.p1 = self.selected.GetNumberOfPoints()
        self.p2 = self.selected.GetNumberOfCells()
        print("Number of points = %s" % self.p1)
        print("Number of cells = %s" % self.p2)

        '# % COLOR SELECTED POINTS RED'
        self.selected_mapper.SetInputData(self.selected)
        try:
            self.selected_actor.GetProperty().SetPointSize(10)
            self.selected_actor.GetProperty().SetColor(0, 0, 0)  # (R, G, B)
            self.color_picked()
        except AttributeError:
            pass
예제 #9
0
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()
예제 #10
0
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
예제 #11
0
        def callback_picker(obj, event):
            props = obj.GetProp3Ds()
            if props.GetNumberOfItems() <= 0:
                return

            extract_geometry = vtk.vtkExtractGeometry()
            extract_geometry.SetImplicitFunction(picker.GetFrustum())
            extract_geometry.SetInput(visible.GetInput())
            extract_geometry.Update()

            unstructured_grid = extract_geometry.GetOutput()
            if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0:
                return

            i = vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i'))

            if self.select_only_visible:
                visible.Update()

                if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0:
                    return

                i = np.intersect1d(
                    i,
                    vtk_to_numpy(
                        visible.GetOutput().GetPointData().GetArray('i')))

                if i.shape[0] <= 0:
                    return

            self.set_labels(self.current_label, i)
def getBoundaryNodes(mesh, radius):
    numPts = mesh.GetNumberOfPoints()
    boundary_nodes = vtk.vtkIdList()
    #First get the points within a sphere on the boundaries using the boundary points as seed points
    for ptID in xrange(0, numPts):
        if (mesh.GetPointData().GetArray('GlobalBoundaryPoints').GetValue(ptID)
                > 0):
            x0, y0, z0 = mesh.GetPoint(ptID)

            sphere = vtk.vtkSphere()
            sphere.SetCenter(x0, y0, z0)
            sphere.SetRadius(float(radius))
            neighbrs = vtk.vtkExtractGeometry()
            neighbrs.SetImplicitFunction(sphere)
            neighbrs.ExtractInsideOn()
            neighbrs.ExtractBoundaryCellsOn()
            neighbrs.SetInputData(mesh)
            neighbrs.Update()
            neighbors = neighbrs.GetOutput()
            writeVTU(neighbors, 'test_boundary.vtu')

            for neighborID in xrange(0, neighbors.GetNumberOfPoints()):
                meshID = mesh.FindPoint(neighbors.GetPoint(neighborID))
                boundary_nodes.InsertUniqueId(meshID)
    return boundary_nodes

    parser.add_argument('filename',
                        type=str,
                        help='the filename (include file ext) to analyze')
예제 #13
0
 def through_pick_call_back(picker, event_id):
     extract = vtk.vtkExtractGeometry()
     mesh.cell_arrays['orig_extract_id'] = np.arange(mesh.n_cells)
     extract.SetInputData(mesh)
     extract.SetImplicitFunction(picker.GetFrustum())
     extract.Update()
     self.picked_cells = pyvista.wrap(extract.GetOutput())
     return end_pick_helper(picker, event_id)
예제 #14
0
 def ExtractMesh(self):
     meshExtractFilter = vtk.vtkExtractGeometry()
     meshExtractFilter.SetInputData(self.Mesh)
     meshExtractFilter.SetExtractInside(self.InsideOut)
     clipPlane = vtk.vtkPlane()
     self.PlaneWidget.GetPlane(clipPlane)
     meshExtractFilter.SetImplicitFunction(clipPlane)
     meshExtractFilter.Update()
     return meshExtractFilter.GetOutput()
예제 #15
0
 def ExtractMesh(self):
     meshExtractFilter = vtk.vtkExtractGeometry()
     meshExtractFilter.SetInputData(self.Mesh)
     meshExtractFilter.SetExtractInside(self.InsideOut)
     clipPlane = vtk.vtkPlane()
     self.PlaneWidget.GetPlane(clipPlane)
     meshExtractFilter.SetImplicitFunction(clipPlane)
     meshExtractFilter.Update()
     return meshExtractFilter.GetOutput()
예제 #16
0
    def setupExtractionAlgorithm(self):
        """Extraction algorithm method for mesh visualization

        This method implements the extraction algorithm used within the filter
        pipeline. Based on the settings of the box widget, the mesh elements
        within the extraction box bounds are extracted.
        """
        self.extractionAlgorithm = vtk.vtkExtractGeometry()                     # use vtkExtractGeometry filter class of vtk library
        self.extractionAlgorithm.SetInputDataObject(self.mesh)                  # use (potentially updated) mesh to plot as input data object
        self.extractionAlgorithm.SetImplicitFunction(self.extractionBox)        # describe extraction box by implicit function with the information stored in extractionBox
        self.extractionAlgorithm.Update()                                       # update extraction algorithm
예제 #17
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self,
         module_manager,
         vtk.vtkExtractGeometry(),
         "Processing.",
         ("vtkDataSet",),
         ("vtkUnstructuredGrid",),
         replaceDoc=True,
         inputFunctions=None,
         outputFunctions=None,
     )
예제 #18
0
    def cutWithMesh(self,
                    mesh,
                    invert=False,
                    onlyTets=False,
                    onlyBoundary=False):
        """
        Cut a ``TetMesh`` mesh with a ``Mesh``.

        :param bool invert: if True return cut off part of the input TetMesh.
        """
        polymesh = mesh.polydata()
        ug = self._ugrid

        scalname = ug.GetCellData().GetScalars().GetName()

        ippd = vtk.vtkImplicitPolyDataDistance()
        ippd.SetInput(polymesh)

        if onlyTets or onlyBoundary:
            clipper = vtk.vtkExtractGeometry()
            clipper.SetInputData(ug)
            clipper.SetImplicitFunction(ippd)
            clipper.SetExtractInside(not invert)
            clipper.SetExtractBoundaryCells(False)
            if onlyBoundary:
                clipper.SetExtractBoundaryCells(True)
                clipper.SetExtractOnlyBoundaryCells(True)
        else:
            signedDistances = vtk.vtkFloatArray()
            signedDistances.SetNumberOfComponents(1)
            signedDistances.SetName("SignedDistances")
            for pointId in range(ug.GetNumberOfPoints()):
                p = ug.GetPoint(pointId)
                signedDistance = ippd.EvaluateFunction(p)
                signedDistances.InsertNextValue(signedDistance)
            ug.GetPointData().SetScalars(signedDistances)
            clipper = vtk.vtkClipDataSet()
            clipper.SetInputData(ug)
            clipper.SetInsideOut(not invert)
            clipper.SetValue(0.0)

        clipper.Update()
        cug = clipper.GetOutput()

        if scalname:  # not working
            if self.useCells:
                self.selectCellArray(scalname)
            else:
                self.selectPointArray(scalname)
        self._update(cug)
        return self
예제 #19
0
def gocad2simpegMeshIndex(gcFile,mesh,extractBoundaryCells=True,extractInside=True):
    """"
    Function to read gocad polystructure file and output indexes of mesh with in the structure.

    """

    # Make the polydata
    polyData = gocad2vtp(gcFile)

    # Make implicit func
    ImpDistFunc = vtk.vtkImplicitPolyDataDistance()
    ImpDistFunc.SetInput(polyData)

    # Convert the mesh
    vtkMesh = vtk.vtkRectilinearGrid()
    vtkMesh.SetDimensions(mesh.nNx,mesh.nNy,mesh.nNz)
    vtkMesh.SetXCoordinates(npsup.numpy_to_vtk(mesh.vectorNx,deep=1))
    vtkMesh.SetYCoordinates(npsup.numpy_to_vtk(mesh.vectorNy,deep=1))
    vtkMesh.SetZCoordinates(npsup.numpy_to_vtk(mesh.vectorNz,deep=1))
    # Add indexes cell data to the object
    vtkInd = npsup.numpy_to_vtk(np.arange(mesh.nC),deep=1)
    vtkInd.SetName('Index')
    vtkMesh.GetCellData().AddArray(vtkInd)

    # Define the extractGeometry
    extractImpDistRectGridFilt = vtk.vtkExtractGeometry() # Object constructor
    extractImpDistRectGridFilt.SetImplicitFunction(ImpDistFunc) #
    extractImpDistRectGridFilt.SetInputData(vtkMesh)

    # Set extraction type
    if extractBoundaryCells is True:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOn()
    else:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOff()

    if extractInside is True:
        extractImpDistRectGridFilt.ExtractInsideOn()
    else:
        extractImpDistRectGridFilt.ExtractInsideOff()

    print "Extracting indices from grid..."
    # Executing the pipe
    extractImpDistRectGridFilt.Update()

    # Get index inside
    insideGrid = extractImpDistRectGridFilt.GetOutput()
    insideGrid = npsup.vtk_to_numpy(insideGrid.GetCellData().GetArray('Index'))


    # Return the indexes inside
    return insideGrid
예제 #20
0
    def extract(self, volumeNode):
        if not self.isValidInputData(volumeNode):
            logging.error("No input volume!")
            return

        imageData = volumeNode.GetImageData()
        impSphere = self.getImplicitSphere()

        extract = vtk.vtkExtractGeometry()
        extract.SetInputData(imageData)
        extract.SetImplicitFunction(impSphere)

        dataMapper = vtk.vtkDataSetMapper()
        dataMapper.SetInputConnection(extract.GetOutputPort())
예제 #21
0
    def legosurface(self, vmin=None, vmax=None, invert=False, cmap='afmhot_r'):
        """
        Represent a ``Volume`` as lego blocks (voxels).
        By default colors correspond to the volume's scalar.
        Returns an ``Mesh``.

        :param float vmin: the lower threshold, voxels below this value are not shown.
        :param float vmax: the upper threshold, voxels above this value are not shown.
        :param str cmap: color mapping of the scalar associated to the voxels.

        |legosurface| |legosurface.py|_
        """
        dataset = vtk.vtkImplicitDataSet()
        dataset.SetDataSet(self._imagedata)
        window = vtk.vtkImplicitWindowFunction()
        window.SetImplicitFunction(dataset)

        srng = list(self._imagedata.GetScalarRange())
        if vmin is not None:
            srng[0] = vmin
        if vmax is not None:
            srng[1] = vmax
        tol = 0.00001*(srng[1]-srng[0])
        srng[0] -= tol
        srng[1] += tol
        window.SetWindowRange(srng)

        extract = vtk.vtkExtractGeometry()
        extract.SetInputData(self._imagedata)
        extract.SetImplicitFunction(window)
        extract.SetExtractInside(invert)
        extract.ExtractBoundaryCellsOff()
        extract.Update()

        gf = vtk.vtkGeometryFilter()
        gf.SetInputData(extract.GetOutput())
        gf.Update()

        a = Mesh(gf.GetOutput()).lw(0.1).flat()
        scalars = a.getPointArray()
        if scalars is None:
            print("Error in legosurface(): no scalars found!")
            return a
        a.pointColors(scalars, vmin=srng[0], vmax=srng[1], cmap=cmap)
        a.mapPointsToCells()
        return a
    def OnLeftButtonUp(self):
        # Forward events
        vtkInteractorStyleRubberBandPick.OnLeftButtonUp()

        frustum = vtk.vtkAreaPicker(
            self.GetInteractor().GetPicker()).GetFrustum()

        extract_geometry = vtk.vtkExtractGeometry()
        extract_geometry.SetImplicitFunction(frustum)

        if vtk.VTK_MAJOR_VERSION <= 5:
            extract_geometry.SetInput(self.Points)
        else:
            extract_geometry.SetInputData(self.Points)
        extract_geometry.Update()

        glyph_filter = vtk.vtkVertexGlyphFilter()
        glyph_filter.SetInputConnection(extract_geometry.GetOutputPort())
        glyph_filter.Update()

        selected = glyph_filter.GetOutput()
        print("Selected %s points" % selected.GetNumberOfPoints())
        print("Selected %s cells" % selected.GetNumberOfCells())
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.SelectedMapper.SetInput(selected)
        else:
            self.SelectedMapper.SetInputData(selected)

        self.SelectedMapper.ScalarVisibilityOff()

        ids = vtkIdTypeArray.SafeDownCast(
            selected.GetPointData().GetArray("OriginalIds"))
        for i in range(ids.GetNumberOfTuples()):
            print("Id %s : %s" % (i, ids.GetValue(i)))

        self.SelectedActor.GetProperty().SetColor(1.0, 0.0, 0.0)  #(R,G,B)
        self.SelectedActor.GetProperty().SetPointSize(3)

        self.CurrentRenderer.AddActor(selected_actor)
        self.GetInteractor().GetRenderWindow().Render()
예제 #23
0
파일: interactors.py 프로젝트: libAtoms/dap
    def leftButtonReleaseEvent(self,obj,event):
        p0 = self.GetStartPosition()
        p1 = self.GetEndPosition()

        picker = vtk.vtkAreaPicker()
        picker.AreaPick(p0[0], p0[1], p1[0], p1[1], self.GetDefaultRenderer())
        at = self.davtk_state.cur_at()
        actors = picker.GetProp3Ds()
        points = []
        # find selected points
        for actor in actors:
            if not hasattr(actor, "point_to_input_point"):
                points.append([None])
                continue
            frustum = picker.GetFrustum()
            geom = vtk.vtkExtractGeometry()
            geom.SetImplicitFunction(frustum)
            geom.SetInputData(actor.GetMapper().GetInput())
            geom.Update()

            IDs = geom.GetOutputDataObject(0).GetPointData().GetArray("IDs")
            points.append([])
            for ID_i in range(IDs.GetNumberOfTuples()):
                points[-1].append(int(IDs.GetTuple(ID_i)[0]/actor.point_to_input_point))
            points[-1] = set(points[-1])

        pick_actors(self.davtk_state.cur_at(), actors, points)
        self.davtk_state.update()

        self.OnLeftButtonUp()

        if self.prev_style is None:
            raise ValueError("leftButtonReleaseEvent prev_style not set")

        self.GetInteractor().SetInteractorStyle(self.prev_style)
        self.prev_style.GetInteractor().Render()
        self.prev_Style = None

        return
예제 #24
0
    def OnLeftButtonUp(self):
        # Forward events
        vtkInteractorStyleRubberBandPick.OnLeftButtonUp()

        frustum = vtk.vtkAreaPicker(self.GetInteractor().GetPicker()).GetFrustum()

        extract_geometry = vtk.vtkExtractGeometry()
        extract_geometry.SetImplicitFunction(frustum)

        if vtk.VTK_MAJOR_VERSION <= 5:
            extract_geometry.SetInput(self.Points)
        else:
            extract_geometry.SetInputData(self.Points)
        extract_geometry.Update()

        glyph_filter = vtk.vtkVertexGlyphFilter()
        glyph_filter.SetInputConnection(extract_geometry.GetOutputPort())
        glyph_filter.Update()

        selected = glyph_filter.GetOutput()
        print("Selected %s points" % selected.GetNumberOfPoints())
        print("Selected %s cells" % selected.GetNumberOfCells())
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.SelectedMapper.SetInput(selected)
        else:
            self.SelectedMapper.SetInputData(selected)

        self.SelectedMapper.ScalarVisibilityOff()

        ids = vtkIdTypeArray.SafeDownCast(selected.GetPointData().GetArray("OriginalIds"))
        for i in range(ids.GetNumberOfTuples()):
            print("Id %s : %s" % (i, ids.GetValue(i)))

        self.SelectedActor.GetProperty().SetColor(1.0, 0.0, 0.0)  # (R,G,B)
        self.SelectedActor.GetProperty().SetPointSize(3)

        self.CurrentRenderer.AddActor(selected_actor)
        self.GetInteractor().GetRenderWindow().Render()
sample.SetImplicitFunction(sphere)
sample.SetModelBounds(-0.5,0.5, -0.5,0.5, -0.5,0.5)
sample.SetSampleDimensions(res,res,res)
sample.ComputeNormalsOff()
sample.Update()

# Adds random attributes
random = vtk.vtkRandomAttributeGenerator()
random.SetGenerateCellScalars(True)
random.SetInputConnection(sample.GetOutputPort())

# Convert the image data to unstructured grid
extractionSphere = vtk.vtkSphere()
extractionSphere.SetRadius(100)
extractionSphere.SetCenter(0,0,0)
extract = vtk.vtkExtractGeometry()
extract.SetImplicitFunction(extractionSphere)
extract.SetInputConnection(random.GetOutputPort())
extract.Update()

# The cut plane
plane = vtk.vtkPlane()
plane.SetOrigin(0,0,0)
plane.SetNormal(1,1,1)

# Now create the usual extractor
cutter = vtk.vtkExtractGeometry()
cutter.SetInputConnection(extract.GetOutputPort())
cutter.SetImplicitFunction(plane)
cutter.ExtractBoundaryCellsOn()
cutter.ExtractOnlyBoundaryCellsOn()
예제 #26
0
sample = vtk.vtkSampleFunction()
sample.SetImplicitFunction(sphere)
sample.SetModelBounds(-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)
sample.SetSampleDimensions(res, res, res)
sample.Update()

# Adds random attributes
random = vtk.vtkRandomAttributeGenerator()
random.SetGenerateCellScalars(True)
random.SetInputConnection(sample.GetOutputPort())

# Convert the image data to unstructured grid
extractionSphere = vtk.vtkSphere()
extractionSphere.SetRadius(100)
extractionSphere.SetCenter(0, 0, 0)
extract = vtk.vtkExtractGeometry()
extract.SetImplicitFunction(extractionSphere)
extract.SetInputConnection(random.GetOutputPort())
extract.Update()

# The cut plane
plane = vtk.vtkPlane()
plane.SetOrigin(0, 0, 0)
plane.SetNormal(1, 1, 1)

# Now create the usual cutter - without a tree
cutter = vtk.vtkCutter()
cutter.SetInputConnection(extract.GetOutputPort())
cutter.SetCutFunction(plane)

cutterMapper = vtk.vtkCompositePolyDataMapper()
예제 #27
0
Log("Filtering node set by depth.")

visibleBoneVertices.ComputeBounds()
visibleNodesBounds = visibleBoneVertices.GetBounds()
Log("Bounds of visible bone nodes:",
    ("%.4f" + " %.4f" * 5) % visibleNodesBounds)

boxBounds = (visibleNodesBounds[0], visibleNodesBounds[1],
             visibleNodesBounds[3] - trochConstraintMaxDepth,
             visibleNodesBounds[3], visibleNodesBounds[4],
             visibleNodesBounds[5])

Log("Limiting to box bounds:", ("%.4f" + " %.4f" * 5) % boxBounds)
box = vtk.vtkBox()
box.SetBounds(boxBounds)
filter = vtk.vtkExtractGeometry()
filter.SetImplicitFunction(box)
filter.ExtractInsideOn()
filter.ExtractBoundaryCellsOn()
filter.SetInput(0, visibleBoneVertices)
filter.Update()
filteredSurfaceVertices = filter.GetOutput()
Log("Found %d nodes in bounding box." %
    filteredSurfaceVertices.GetNumberOfCells())
filteredSurfaceVertices.ComputeBounds()
filteredSurfaceVerticesBounds = filteredSurfaceVertices.GetBounds()

# Save to file so we can examine in ParaView, etc...
depthFilteredBoneNodesFile = os.path.splitext(
    inputAimFile)[0] + "_nodes_troch.vtu"
writer = vtk.vtkXMLUnstructuredGridWriter()
예제 #28
0
                               vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS,
                               "BoundaryCells")
thresh1.Update()

mapper1 = vtk.vtkDataSetMapper()
mapper1.SetInputConnection(thresh1.GetOutputPort())

actor1 = vtk.vtkActor()
actor1.SetMapper(mapper1)

# unstructured grid
sphere = vtk.vtkSphere()
sphere.SetCenter(0, 0, 0)
sphere.SetRadius(1000000)

toUG = vtk.vtkExtractGeometry()
toUG.SetInputConnection(plane.GetOutputPort())
toUG.SetImplicitFunction(sphere)

mark2 = vtk.vtkMarkBoundaryFilter()
mark2.SetInputConnection(toUG.GetOutputPort())
mark2.Update()

thresh2 = vtk.vtkThreshold()
thresh2.SetInputConnection(mark2.GetOutputPort())
thresh2.ThresholdByUpper(1)
thresh2.SetInputArrayToProcess(0, 0, 0,
                               vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS,
                               "BoundaryCells")

mapper2 = vtk.vtkDataSetMapper()
예제 #29
0
sphere.SetRadius(0.25)
sphere.SetTransform(trans)
trans2 = vtk.vtkTransform()
trans2.Scale(.25, .5, 1.0)
sphere2 = vtk.vtkSphere()
sphere2.SetRadius(0.25)
sphere2.SetTransform(trans2)
union = vtk.vtkImplicitBoolean()
union.AddFunction(sphere)
union.AddFunction(sphere2)
union.SetOperationType(0) #union

# Here is where it gets interesting. The implicit function is used to
# extract those cells completely inside the function. They are then
# shrunk to help show what was extracted.
extract = vtk.vtkExtractGeometry()
extract.SetInputConnection(sample.GetOutputPort())
extract.SetImplicitFunction(union)
shrink = vtk.vtkShrinkFilter()
shrink.SetInputConnection(extract.GetOutputPort())
shrink.SetShrinkFactor(0.5)
dataMapper = vtk.vtkDataSetMapper()
dataMapper.SetInputConnection(shrink.GetOutputPort())
dataActor = vtk.vtkActor()
dataActor.SetMapper(dataMapper)

# The outline gives context to the original data.
outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(sample.GetOutputPort())
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())
예제 #30
0
def main():
    colors = vtk.vtkNamedColors()

    ren1 = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0)

    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(50, 50, 50)
    sample.SetImplicitFunction(quadric)
    sample.ComputeNormalsOff()

    trans = vtk.vtkTransform()
    trans.Scale(1, 0.5, 0.333)

    sphere = vtk.vtkSphere()
    sphere.SetRadius(0.25)
    sphere.SetTransform(trans)

    trans2 = vtk.vtkTransform()
    trans2.Scale(0.25, 0.5, 1.0)

    sphere2 = vtk.vtkSphere()
    sphere2.SetRadius(0.25)
    sphere2.SetTransform(trans2)

    booleanUnion = vtk.vtkImplicitBoolean()
    booleanUnion.AddFunction(sphere)
    booleanUnion.AddFunction(sphere2)
    booleanUnion.SetOperationType(0)  # boolean Union

    extract = vtk.vtkExtractGeometry()
    extract.SetInputConnection(sample.GetOutputPort())
    extract.SetImplicitFunction(booleanUnion)

    shrink = vtk.vtkShrinkFilter()
    shrink.SetInputConnection(extract.GetOutputPort())
    shrink.SetShrinkFactor(0.5)

    dataMapper = vtk.vtkDataSetMapper()
    dataMapper.SetInputConnection(shrink.GetOutputPort())
    dataActor = vtk.vtkActor()
    dataActor.SetMapper(dataMapper)

    # outline
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(0, 0, 0)

    # Add the actors to the renderer, set the background and size
    #
    ren1.AddActor(outlineActor)
    ren1.AddActor(dataActor)
    ren1.SetBackground(colors.GetColor3d("SlateGray"))

    renWin.SetSize(640, 480)
    renWin.SetWindowName('ExtractData')

    renWin.Render()
    ren1.GetActiveCamera().Azimuth(30)
    ren1.GetActiveCamera().Elevation(30)

    renWin.Render()
    iren.Start()
예제 #31
0
파일: io_utils.py 프로젝트: jsc1129/simpeg
def surface2inds(vrtx, trgl, mesh, boundaries=True, internal=True):
    """"
    Function to read gocad polystructure file and output indexes of
    mesh with in the structure.

    """
    import vtk
    import vtk.util.numpy_support as npsup

    # Adjust the index
    trgl = trgl - 1

    # Make vtk pts
    ptsvtk = vtk.vtkPoints()
    ptsvtk.SetData(npsup.numpy_to_vtk(vrtx, deep=1))

    # Make the polygon connection
    polys = vtk.vtkCellArray()
    for face in trgl:
        poly = vtk.vtkPolygon()
        poly.GetPointIds().SetNumberOfIds(len(face))
        for nrv, vert in enumerate(face):
            poly.GetPointIds().SetId(nrv, vert)
        polys.InsertNextCell(poly)

    # Make the polydata, structure of connections and vrtx
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(ptsvtk)
    polyData.SetPolys(polys)

    # Make implicit func
    ImpDistFunc = vtk.vtkImplicitPolyDataDistance()
    ImpDistFunc.SetInput(polyData)

    # Convert the mesh
    vtkMesh = vtk.vtkRectilinearGrid()
    vtkMesh.SetDimensions(mesh.nNx, mesh.nNy, mesh.nNz)
    vtkMesh.SetXCoordinates(npsup.numpy_to_vtk(mesh.vectorNx, deep=1))
    vtkMesh.SetYCoordinates(npsup.numpy_to_vtk(mesh.vectorNy, deep=1))
    vtkMesh.SetZCoordinates(npsup.numpy_to_vtk(mesh.vectorNz, deep=1))
    # Add indexes
    vtkInd = npsup.numpy_to_vtk(np.arange(mesh.nC), deep=1)
    vtkInd.SetName('Index')
    vtkMesh.GetCellData().AddArray(vtkInd)

    extractImpDistRectGridFilt = vtk.vtkExtractGeometry()  # Object constructor
    extractImpDistRectGridFilt.SetImplicitFunction(ImpDistFunc)  #
    extractImpDistRectGridFilt.SetInputData(vtkMesh)

    if boundaries is True:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOn()

    else:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOff()

    if internal is True:
        extractImpDistRectGridFilt.ExtractInsideOn()

    else:
        extractImpDistRectGridFilt.ExtractInsideOff()

    print("Extracting indices from grid...")
    # Executing the pipe
    extractImpDistRectGridFilt.Update()

    # Get index inside
    insideGrid = extractImpDistRectGridFilt.GetOutput()
    insideGrid = npsup.vtk_to_numpy(insideGrid.GetCellData().GetArray('Index'))

    # Return the indexes inside
    return insideGrid
예제 #32
0
    def plot(self, struct):

        # creates self. data1, legend, filename, fieldname, dim, has_field, tracker, revision
        if not self.call_config(struct):
            return

        # creates self.src
        if not self.call_src():
            return

# postponed widget processing
        if self.has_field:
            self.add_scalarbar_1()
            self.add_abs_rel_1()
        self.add_outline_1()
        self.add_plane_1()
        self.add_sw_1()
        self.add_opacity_1(selection=0)  # Opacity: 100%/75%/50%/25%/0%

        # vector
        self.plane = vtk.vtkPlane()
        self.origin = self.src.GetOutput().GetCenter()
        print 'center', self.origin
        #        self.plane.SetOrigin(self.origin) #xml
        #        self.plane.SetNormal(1, 1, 1) #xml

        self.clipper = vtk.vtkExtractGeometry()
        self.clipper.SetInputConnection(self.src.GetOutputPort())
        self.clipper.SetImplicitFunction(self.plane)
        self.clipper.ExtractInsideOn()  # +/-
        #        self.clipper.ExtractBoundaryCellsOn() # inclue as que estan parcialmente dentro
        #        self.clipper.ExtractOnlyBoundaryCellsOn()

        self.pdM = vtk.vtkDataSetMapper()
        self.pdM.SetInputConnection(self.clipper.GetOutputPort())
        if self.has_field:
            self.pdM.ScalarVisibilityOn()
        else:
            self.pdM.ScalarVisibilityOff()

        self.scalarrange.local_set(self.src.GetOutput().GetScalarRange())

        # reverse rainbow [red->blue] -> [blue->red]
        look = self.pdM.GetLookupTable()
        #        self.add_scalarbar_2(look)

        self.add_outline_2(self.src)

        self.cutA = vtk.vtkActor()
        self.cutA.SetMapper(self.pdM)
        self.cutA.GetProperty().SetRepresentationToSurface()
        self.cutA.GetProperty().SetColor(Plot.mesh_color)

        self.rens[0].AddActor(self.cutA)

        # poñendo a scalarbar aquí e non antes, queda ben dibuxada desde o primeiro (non negra)
        if self.has_field:
            self.add_scalarbar_2(look)
            self.add_abs_rel_2(self.src, self.clipper)

        self.add_sw_2(self.cutA)
        self.add_opacity_2([self.cutA])  # Opacity: 100%/75%/50%/25%/0%

        # mover plano interactivamente
        #self.planeI = vtk.vtkPlaneWidget()
        self.planeI = vtk.vtkImplicitPlaneWidget()
        seeds = vtk.vtkPolyData()
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            self.planeI.SetInput(self.src.GetOutput())
        else:
            self.planeI.SetInputConnection(self.src.GetOutputPort())

        self.add_plane_2(self.planeI)

        self.planeI.SetOrigin(self.origin[0], self.origin[1], self.origin[2])
        #self.planeI.SetResolution(20)
        #planeWidget.NormalToXAxisOn()
        #planeWidget.SetRepresentationToOutline()
        #self.planeI.PlaceWidget()
        self.planeI.GetPolyData(seeds)
        self.planeI.SetPlaceFactor(1.0)  # factor * bounds
        self.planeI.OutsideBoundsOn()  # not on PlaneWidget
        self.planeI.OutlineTranslationOff()
        self.planeI.DrawPlaneOff()
        self.planeI.ScaleEnabledOff()
        self.planeI.PlaceWidget()
        #self.planeI.PlaceWidget(self.src.GetOutput().GetBounds())
        self.planeI.AddObserver("EndInteractionEvent", self.event_end)

        self.set_iren()
        self.planeI.SetInteractor(self.iren)
        self.planeI.On()

        #        self.lineI.AddObserver("StartInteractionEvent", self.event_start)
        #        self.lineI.AddObserver("InteractionEvent", self.event)
        #        self.lineI.AddObserver("EndInteractionEvent", self.event_end)
        # /mover plano interactivamente

        if interactive2 and self.has_field:
            #self.set_iren() #necesario ^
            self.clicker = ClickLabel.ClickLabel()
            self.clicker.set_point_cell(self.data1.get('fielddomain'))
            self.clicker.set_objects(self.clipper, self.rens[0], self.iren,
                                     self.widget)
            self.clicker.set_props([self.cutA])
            self.clicker.setup()

        o = self.planeI.GetOrigin()
        n = self.planeI.GetNormal()
        print 'initial: o,n', o, n
        self.set_params(struct, o, n)  # not force first time

        self.copy_params(struct)

        self.done = True
예제 #33
0
    def makeModels(self):
        """
        make vtk model
        """

        # Here we create two ellipsoidal implicit functions and boolean them
        # together to form a "cross" shaped implicit function.
        quadric = vtk.vtkQuadric()
        quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

        sample = vtk.vtkSampleFunction()
        sample.SetSampleDimensions(50, 50, 50)
        sample.SetImplicitFunction(quadric)
        sample.ComputeNormalsOff()

        trans = vtk.vtkTransform()
        trans.Scale(1, .5, .333)
        sphere = vtk.vtkSphere()
        sphere.SetRadius(self.radius)
        sphere.SetTransform(trans)

        trans2 = vtk.vtkTransform()
        trans2.Scale(.25, .5, 1.0)
        sphere2 = vtk.vtkSphere()
        sphere2.SetRadius(self.radius)
        sphere2.SetTransform(trans2)

        self.sphere_geom_1 = sphere
        self.sphere_geom_2 = sphere2

        union = vtk.vtkImplicitBoolean()
        union.AddFunction(sphere)
        union.AddFunction(sphere2)
        union.SetOperationType(0)

        # Here is where it gets interesting. The implicit function is used to
        # extract those cells completely inside the function. They are then
        # shrunk to helpr show what was extracted.
        extract = vtk.vtkExtractGeometry()
        extract.SetInputConnection(sample.GetOutputPort())
        extract.SetImplicitFunction(union)
        shrink = vtk.vtkShrinkFilter()
        shrink.SetInputConnection(extract.GetOutputPort())
        shrink.SetShrinkFactor(self.shrink_factor)
        dataMapper = vtk.vtkDataSetMapper()
        dataMapper.SetInputConnection(shrink.GetOutputPort())

        self.shrink_geom = shrink

        # data actor
        self.data_actor = vtk.vtkActor()
        self.data_actor.SetMapper(dataMapper)

        # The outline gives context to the original data.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(sample.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())

        # outline actor
        self.outline_actor = vtk.vtkActor()
        self.outline_actor.SetMapper(outlineMapper)
        outlineProp = self.outline_actor.GetProperty()
        outlineProp.SetColor(0, 0, 0)
예제 #34
0
def gocad2vtk(gcFile, mesh, bcflag, inflag):
    """"
    Function to read gocad polystructure file and output indexes of
    mesh with in the structure.

    """
    print("Reading GOCAD ts file...", bcflag, inflag)
    vrtx, trgl = read_GOCAD_ts(gcFile)
    vrtx, trgl = np.vstack(vrtx), np.vstack(trgl)
    # Adjust the index
    trgl = trgl - 1

    # Make vtk pts
    ptsvtk = vtk.vtkPoints()
    ptsvtk.SetData(npsup.numpy_to_vtk(vrtx, deep=1))

    # Make the polygon connection
    polys = vtk.vtkCellArray()
    for face in trgl:
        poly = vtk.vtkPolygon()
        poly.GetPointIds().SetNumberOfIds(len(face))
        for nrv, vert in enumerate(face):
            poly.GetPointIds().SetId(nrv, vert)
        polys.InsertNextCell(poly)

    # Make the polydata, structure of connections and vrtx
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(ptsvtk)
    polyData.SetPolys(polys)

    # Make implicit func
    ImpDistFunc = vtk.vtkImplicitPolyDataDistance()
    ImpDistFunc.SetInput(polyData)

    # Convert the mesh
    vtkMesh = vtk.vtkRectilinearGrid()
    vtkMesh.SetDimensions(mesh.nNx, mesh.nNy, mesh.nNz)
    vtkMesh.SetXCoordinates(npsup.numpy_to_vtk(mesh.vectorNx, deep=1))
    vtkMesh.SetYCoordinates(npsup.numpy_to_vtk(mesh.vectorNy, deep=1))
    vtkMesh.SetZCoordinates(npsup.numpy_to_vtk(mesh.vectorNz, deep=1))
    # Add indexes
    vtkInd = npsup.numpy_to_vtk(np.arange(mesh.nC), deep=1)
    vtkInd.SetName('Index')
    vtkMesh.GetCellData().AddArray(vtkInd)

    extractImpDistRectGridFilt = vtk.vtkExtractGeometry()
    extractImpDistRectGridFilt.SetImplicitFunction(ImpDistFunc)
    extractImpDistRectGridFilt.SetInputData(vtkMesh)

    if bcflag is True:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOn()

    else:
        extractImpDistRectGridFilt.ExtractBoundaryCellsOff()

    if inflag is True:
        extractImpDistRectGridFilt.ExtractInsideOn()

    else:
        extractImpDistRectGridFilt.ExtractInsideOff()

    print("Extracting indices from grid...")
    # Executing the pipe
    extractImpDistRectGridFilt.Update()

    # Get index inside
    insideGrid = extractImpDistRectGridFilt.GetOutput()
    insideGrid = npsup.vtk_to_numpy(insideGrid.GetCellData().GetArray('Index'))

    # Return the indexes inside
    return insideGrid
예제 #35
0
VTK_DATA_ROOT = vtkGetDataRoot()

# Test and compare vtkGeometryFilter verus
# vtkDataSetSurfaceFilter.

# Control test resolution
res = 10

# Create a synthetic source, then convert to unstructured grid
vol = vtk.vtkImageData()
vol.SetDimensions(res, res, res)

sphere = vtk.vtkSphere()
sphere.SetRadius(10000)

grid = vtk.vtkExtractGeometry()
grid.SetInputData(vol)
grid.SetImplicitFunction(sphere)
grid.Update()
print("Processing {0} hexes".format(grid.GetOutput().GetNumberOfCells()))

# Create a scalar field
ele = vtk.vtkSimpleElevationFilter()
ele.SetInputConnection(grid.GetOutputPort())

# Extract the surface with vtkGeometryFilter and time it. Indicate
# some faces to not not extract.
# the fast extraction mode.
face = [0, 1, 11, 10]
faces = vtk.vtkCellArray()
faces.InsertNextCell(4, face)
예제 #36
0
    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()
예제 #37
0
 def unstructured_grid_to_poly_data(self):
     geometry_filter = vtk.vtkExtractGeometry()
     geometry_filter.SetInputConnection(self.mesh.GetOutputPort())
     geometry_filter.Update()
     return geometry_filter