Python vtk.vtkPolyData() Examples

The following are 30 code examples of vtk.vtkPolyData(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module vtk , or try the search function .
Example #1
Source File: vis.py    From DeepV2D with BSD 3-Clause "New" or "Revised" License 11 votes vote down vote up
def create_pointcloud_polydata(points, colors=None):
    """https://github.com/lmb-freiburg/demon
    Creates a vtkPolyData object with the point cloud from numpy arrays
    
    points: numpy.ndarray
        pointcloud with shape (n,3)
    
    colors: numpy.ndarray
        uint8 array with colors for each point. shape is (n,3)

    Returns vtkPolyData object
    """
    vpoints = vtk.vtkPoints()
    vpoints.SetNumberOfPoints(points.shape[0])
    for i in range(points.shape[0]):
        vpoints.SetPoint(i, points[i])
    vpoly = vtk.vtkPolyData()
    vpoly.SetPoints(vpoints)
    
    if not colors is None:
        vcolors = vtk.vtkUnsignedCharArray()
        vcolors.SetNumberOfComponents(3)
        vcolors.SetName("Colors")
        vcolors.SetNumberOfTuples(points.shape[0])
        for i in range(points.shape[0]):
            vcolors.SetTuple3(i ,colors[i,0],colors[i,1], colors[i,2])
        vpoly.GetPointData().SetScalars(vcolors)

    vcells = vtk.vtkCellArray()
    
    for i in range(points.shape[0]):
        vcells.InsertNextCell(1)
        vcells.InsertCellPoint(i)
        
    vpoly.SetVerts(vcells)
    
    return vpoly 
Example #2
Source File: visualization.py    From CityEnergyAnalyst with MIT License 8 votes vote down vote up
def stl2actor(ageometry_path, ageometry_name, ageometry_color):

    appendfilter = vtk.vtkAppendPolyData()
    render_lib = vtk.vtkSTLReader()
    polydata = vtk.vtkPolyData()
    render_lib.SetFileName(os.path.join(ageometry_path, ageometry_name+".stl"))
    render_lib.Update()
    polydata.ShallowCopy(render_lib.GetOutput())
    appendfilter.AddInputConnection(polydata.GetProducerPort())
    appendfilter.Update()

    #  Remove any duplicate points.
    cleanfilter = vtk.vtkCleanPolyData()
    cleanfilter.SetInputConnection(appendfilter.GetOutputPort())
    cleanfilter.Update()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(cleanfilter.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(ageometry_color)

    return actor, polydata 
Example #3
Source File: earth.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def build_globe(self):
        """Generates the globe as ``vtkPolyData``"""
        # NOTE: https://gitlab.kitware.com/paraview/paraview/issues/19417
        from scipy.spatial import Delaunay
        pos, tex = self.create_sphere()
        pts = self.spherical_to_cartesian(pos[:,0], pos[:,1])
        points = interface.points_to_poly_data(pts).GetPoints()
        texcoords = interface.convert_array(tex, name='Texture Coordinates')
        # Now generate triangles
        cell_connectivity = Delaunay(pos).simplices.astype(int)
        cells = vtk.vtkCellArray()
        cells.SetNumberOfCells(cell_connectivity.shape[0])
        cells.SetCells(cell_connectivity.shape[0], interface.convert_cell_conn(cell_connectivity))
        # Generate output
        output = vtk.vtkPolyData()
        output.SetPoints(points)
        output.GetPointData().SetTCoords(texcoords)
        output.SetPolys(cells)
        return output 
Example #4
Source File: perception.py    From director with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, view):
        TimerCallback.__init__(self)
        self.view = view
        self.reader = None
        self.displayedRevolution = -1
        self.lastScanLine = 0
        self.numberOfScanLines = 1
        self.nextScanLineId = 0
        self.scanLines = []
        self.pointSize = 1
        self.alpha = 0.5
        self.visible = True
        self.initScanLines()

        self.revPolyData = vtk.vtkPolyData()
        self.polyDataObj = vis.PolyDataItem('Multisense Sweep', self.revPolyData, view)
        self.polyDataObj.actor.SetPickable(1)

        self.setPointSize(self.pointSize)
        self.setAlpha(self.alpha)
        self.targetFps = 60
        self.showRevolutionCallback = None
        self.colorizeCallback = None 
Example #5
Source File: visualization.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def points2actor(xyz, apoint_size):
    import vtk
    points = vtk.vtkPoints()
    # Create the topology of the point (a vertex)
    vertices = vtk.vtkCellArray()
    # Add points
    for i in range(0, len(xyz)):
        p = xyz.loc[i].values.tolist()
        point_id = points.InsertNextPoint(p)
        vertices.InsertNextCell(1)
        vertices.InsertCellPoint(point_id)
    # Create a poly data object
    polydata = vtk.vtkPolyData()
    # Set the points and vertices we created as the geometry and topology of the polydata
    polydata.SetPoints(points)
    polydata.SetVerts(vertices)
    polydata.Modified()
    # Mapper for points
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(polydata)
    # ACTOR for points
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(apoint_size)
    return actor, polydata 
Example #6
Source File: vtkpointcloud.py    From semi-auto-anno with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):
        """
        Initialize class
        :param zMin: minimum depth
        :param zMax: maximum depth
        :param maxNumPoints: maximum number of points
        :return: None
        """
        self.maxNumPoints = int(maxNumPoints)
        self.vtkPolyData = vtk.vtkPolyData()
        self.clearPoints()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.vtkPolyData)
        mapper.SetColorModeToDefault()
        mapper.SetScalarRange(zMin, zMax)
        mapper.SetScalarVisibility(1)
        self.vtkActor = vtk.vtkActor()
        self.vtkActor.SetMapper(mapper)
        self.vtkActor.GetProperty().SetPointSize(3.0)
        self.rng = numpy.random.RandomState(23455) 
Example #7
Source File: synchronizable_deserializer.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def poly_data_builder(state, zf, register):
    instance = vtk.vtkPolyData()
    register.update({state['id']: instance})
    # geometry
    if 'points' in state['properties']:
        points = state['properties']['points']
        vtkpoints = vtk.vtkPoints()
        data_arr = ARRAY_TYPES[points['dataType']]()
        fill_array(data_arr, points, zf)
        vtkpoints.SetData(data_arr)
        instance.SetPoints(vtkpoints)
    for cell_type in ['verts', 'lines', 'polys', 'strips']:
        if cell_type in state['properties']:
            cell_arr = vtk.vtkCellArray()
            fill_array(cell_arr.GetData(), state['properties'][cell_type], zf)
            getattr(instance, 'Set' + capitalize(cell_type))(cell_arr)
    
    # datasets
    fields = state['properties']['fields']
    for dataset in fields:
        data_arr = ARRAY_TYPES[dataset['dataType']]()
        fill_array(data_arr, dataset, zf)
        location = getattr(instance, 'Get' + capitalize(dataset['location']))()
        getattr(location, capitalize(dataset['registration']))(data_arr) 
Example #8
Source File: segmentation.py    From director with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, name, imagesChannel, cameraName, imageManager):
        vis.PolyDataItem.__init__(self, name, vtk.vtkPolyData(), view=None)

        self.addProperty('Channel', imagesChannel)
        self.addProperty('Camera name', cameraName)

        self.addProperty('Decimation', 0, attributes=om.PropertyAttributes(enumNames=['1', '2', '4', '8', '16']))
        self.addProperty('Remove Size', 1000, attributes=om.PropertyAttributes(decimals=0, minimum=0, maximum=100000.0, singleStep=1000))
        self.addProperty('Target FPS', 1.0, attributes=om.PropertyAttributes(decimals=1, minimum=0.1, maximum=30.0, singleStep=0.1))
        self.addProperty('Max Range', 2.0,  attributes=om.PropertyAttributes(decimals=2, minimum=0., maximum=30.0, singleStep=0.25))

        self.timer = TimerCallback()
        self.timer.callback = self.update
        self.lastUtime = 0
        self.imageManager = imageManager
        self.cameraName = cameraName
        self.setProperty('Visible', False)
        self.addProperty('Remove Stale Data', False)
        self.addProperty('Stale Data Timeout', 5.0, attributes=om.PropertyAttributes(decimals=1, minimum=0.1, maximum=30.0, singleStep=0.1))
        self.lastDataReceivedTime = time.time() 
Example #9
Source File: vtkpointcloud.py    From deep-prior-pp with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, pts=None, zMin=-10.0, zMax=10.0, maxNumPoints=1e6, color='depth'):
        """
        Initialize class
        :param zMin: minimum depth
        :param zMax: maximum depth
        :param maxNumPoints: maximum number of points
        :return: None
        """
        self.color = color
        self.maxNumPoints = int(maxNumPoints)
        self.vtkPolyData = vtk.vtkPolyData()
        self.clearPoints()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.vtkPolyData)
        mapper.SetColorModeToDefault()
        mapper.SetScalarRange(zMin, zMax)
        mapper.SetScalarVisibility(1)
        self.vtkActor = vtk.vtkActor()
        self.vtkActor.SetMapper(mapper)
        self.vtkActor.GetProperty().SetPointSize(3.0)
        self.rng = numpy.random.RandomState(23455)

        if pts is not None:
            self.addPoints(pts) 
Example #10
Source File: visualization.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def face_points2actor(fps_df):

    cell_array = vtk.vtkCellArray()
    points = vtk.vtkPoints()
    point_id = 0
    for i in range(fps_df.shape[0]):
        polygon = vtk.vtkPolygon()
        polygon.GetPointIds().SetNumberOfIds(3)
        for n in range(3):
            points.InsertNextPoint(fps_df.ix[i, 0+3*n], fps_df.ix[i, 1+3*n], fps_df.ix[i, 2+3*n])
            polygon.GetPointIds().SetId(n, point_id)
            point_id += 1
        cell_array.InsertNextCell(polygon)
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetPolys(cell_array)

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(polydata)
    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    return actor, polydata 
Example #11
Source File: test_code_vasp_01.py    From PyChemia with MIT License 6 votes vote down vote up
def Frequencies(bands, src):
    """
    Count the number of scalars in each band.
    :param: bands - the bands.
    :param: src - the vtkPolyData source.
    :return: The frequencies of the scalars in each band.
    """
    freq = dict()
    for i in range(len(bands)):
        freq[i] = 0
    tuples = src.GetPointData().GetScalars().GetNumberOfTuples()
    for i in range(tuples):
        x = src.GetPointData().GetScalars().GetTuple1(i)
        for j in range(len(bands)):
            if x <= bands[j][2]:
                freq[j] += 1
                break
    return freq 
Example #12
Source File: test_code_vasp_01.py    From PyChemia with MIT License 6 votes vote down vote up
def MakeParametricSource():
    """
    Make a parametric surface as the source.
    :return: vtkPolyData with normal and scalar data.
    """
    fn = vtk.vtkParametricRandomHills()
    fn.AllowRandomGenerationOn()
    fn.SetRandomSeed(1)
    fn.SetNumberOfHills(30)
    if fn.GetClassName() == 'vtkParametricRandomHills':
        # Make the normals face out of the surface.
        fn.ClockwiseOrderingOff()

    source = vtk.vtkParametricFunctionSource()
    source.SetParametricFunction(fn)
    source.SetUResolution(50)
    source.SetVResolution(50)
    source.SetScalarModeToZ()
    source.Update()
    # Name the arrays (not needed in VTK 6.2+ for vtkParametricFunctionSource)
    source.GetOutput().GetPointData().GetNormals().SetName('Normals')
    source.GetOutput().GetPointData().GetScalars().SetName('Scalars')
    return source.GetOutput() 
Example #13
Source File: vtkPointSetOutlierRemoval.py    From pcloudpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_input(self, input_data):
        """
        set input data

        Parameters
        ----------
        input-data : vtkPolyData


        Returns
        -------
        is_valid: bool
            Returns True if the input_data is valid for processing

        """
        if isinstance(input_data, vtkPolyData):
            super(vtkPointSetOutlierEstimation, self).set_input(input_data)
            return True
        else:
            return False 
Example #14
Source File: filters_test.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_slider(self):
        """`SlideSliceAlongPoints`: use slider"""
        # Set up the algorithm
        alg = SlideSliceAlongPoints(n_slices=10)
        slc = alg.apply(self.points, self.grid)
        self.assertTrue(isinstance(slc, vtk.vtkPolyData))
        alg.set_location(30)
        alg.Update()
        self.assertTrue(isinstance(slc, vtk.vtkPolyData))
        alg.set_location(95)
        alg.Update()
        self.assertTrue(isinstance(slc, vtk.vtkPolyData))
        # Can we really test anything further on this?
        #   Testing the slice positions would be crazy difficult




############################################################################### 
Example #15
Source File: test_common.py    From pyvista with MIT License 6 votes vote down vote up
def test_shallow_copy_back_propagation():
    """Test that the original data object's points get modified after a
    shallow copy.

    Reference: https://github.com/pyvista/pyvista/issues/375#issuecomment-531691483
    """
    # Case 1
    points = vtk.vtkPoints()
    points.InsertNextPoint(0.0, 0.0, 0.0)
    points.InsertNextPoint(1.0, 0.0, 0.0)
    points.InsertNextPoint(2.0, 0.0, 0.0)
    original = vtk.vtkPolyData()
    original.SetPoints(points)
    wrapped = pyvista.PolyData(original, deep=False)
    wrapped.points[:] = 2.8
    orig_points = vtk_to_numpy(original.GetPoints().GetData())
    assert np.allclose(orig_points, wrapped.points)
    # Case 2
    original = vtk.vtkPolyData()
    wrapped = pyvista.PolyData(original, deep=False)
    wrapped.points = np.random.rand(5, 3)
    orig_points = vtk_to_numpy(original.GetPoints().GetData())
    assert np.allclose(orig_points, wrapped.points) 
Example #16
Source File: converters.py    From pcloudpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_polydata_from(points, tr_re):

    numberPoints = len(points)
    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    points_vtk = numpy_to_vtk(np.asarray(points, order='C',dtype=ntype), deep=1)
    Points.SetNumberOfPoints(numberPoints)
    Points.SetData(points_vtk)

    Triangles = vtkCellArray()
    for item in tr_re:
        Triangle = vtkTriangle()
        Triangle.GetPointIds().SetId(0,item[0])
        Triangle.GetPointIds().SetId(1,item[1])
        Triangle.GetPointIds().SetId(2,item[2])
        Triangles.InsertNextCell(Triangle)

    polydata = vtkPolyData()
    polydata.SetPoints(Points)
    polydata.SetPolys(Triangles)

    polydata.Modified()
    polydata.Update()

    return polydata 
Example #17
Source File: vtkPointSetNormalsEstimation.py    From pcloudpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_input(self, input_data):
        """
        set input data

        Parameters
        ----------
        input-data : vtkPolyData


        Returns
        -------
        is_valid: bool
            Returns True if the input_data is valid for processing

        """
        if isinstance(input_data, vtkPolyData):
            super(vtkPointSetNormalsEstimation, self).set_input(input_data)
            return True
        else:
            return False 
Example #18
Source File: ScreenedPoisson.py    From pcloudpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_input(self, input_data):
        """
        set input data

        Parameters
        ----------
        input-data : vtkPolyData

        Returns
        -------
        is_valid: bool
            Returns True if the input_data is valid for processing

        """
        if isinstance(input_data, vtkPolyData):
            super(ScreenedPoisson, self).set_input(input_data)
            return True
        else:
            return False 
Example #19
Source File: base.py    From pcloudpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_input(self, input_data):

        """
        set input data

        Parameters
        ----------
        input-data : vtkPolyData

        Returns
        -------
        is_valid: bool
            Returns True if the input_data is valid for processing

        """
        if isinstance(input_data, vtkPolyData):
            self.input_ = input_data
            return True
        else:
            return False 
Example #20
Source File: vtkpointcloud.py    From deep-prior with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):
        """
        Initialize class
        :param zMin: minimum depth
        :param zMax: maximum depth
        :param maxNumPoints: maximum number of points
        :return: None
        """
        self.maxNumPoints = int(maxNumPoints)
        self.vtkPolyData = vtk.vtkPolyData()
        self.clearPoints()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.vtkPolyData)
        mapper.SetColorModeToDefault()
        mapper.SetScalarRange(zMin, zMax)
        mapper.SetScalarVisibility(1)
        self.vtkActor = vtk.vtkActor()
        self.vtkActor.SetMapper(mapper) 
Example #21
Source File: tract_io.py    From geomloss with MIT License 5 votes vote down vote up
def save_vtk(filename, tracts, lines_indices=None, scalars = None):

	lengths = [len(p) for p in tracts]
	line_starts = ns.numpy.r_[0, ns.numpy.cumsum(lengths)]
	if lines_indices is None:
		lines_indices = [ns.numpy.arange(length) + line_start for length, line_start in izip(lengths, line_starts)]

	ids = ns.numpy.hstack([ns.numpy.r_[c[0], c[1]] for c in izip(lengths, lines_indices)])
	vtk_ids = ns.numpy_to_vtkIdTypeArray(ids, deep=True)

	cell_array = vtk.vtkCellArray()
	cell_array.SetCells(len(tracts), vtk_ids)
	points = ns.numpy.vstack(tracts).astype(ns.get_vtk_to_numpy_typemap()[vtk.VTK_DOUBLE])
	points_array = ns.numpy_to_vtk(points, deep=True)

	poly_data = vtk.vtkPolyData()
	vtk_points = vtk.vtkPoints()
	vtk_points.SetData(points_array)
	poly_data.SetPoints(vtk_points)
	poly_data.SetLines(cell_array)
	poly_data.BuildCells()

	if filename.endswith('.xml') or filename.endswith('.vtp'):
		writer = vtk.vtkXMLPolyDataWriter()
		writer.SetDataModeToBinary()
	else:
		writer = vtk.vtkPolyDataWriter()
		writer.SetFileTypeToBinary()


	writer.SetFileName(filename)
	if hasattr(vtk, 'VTK_MAJOR_VERSION') and vtk.VTK_MAJOR_VERSION > 5:
		writer.SetInputData(poly_data)
	else:
		writer.SetInput(poly_data)
	writer.Write() 
Example #22
Source File: slicing.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_slice(self, pts, data, planes, output):
        """Internal helper to perfrom the filter
        """
        # numPoints = pts.GetNumberOfPoints()
        # Set number of blocks based on user choice in the selction
        output.SetNumberOfBlocks(self.get_number_of_slices())
        blk = 0
        for i, plane in enumerate(planes):
            temp = vtk.vtkPolyData()
            self._slice(data, temp, plane)
            output.SetBlock(blk, temp)
            output.GetMetaData(blk).Set(vtk.vtkCompositeDataSet.NAME(), 'Slice%.2d' % blk)
            blk += 1
        return output 
Example #23
Source File: vis.py    From demon with GNU General Public License v3.0 5 votes vote down vote up
def create_pointcloud_polydata(points, colors=None):
    """Creates a vtkPolyData object with the point cloud from numpy arrays
    
    points: numpy.ndarray
        pointcloud with shape (n,3)
    
    colors: numpy.ndarray
        uint8 array with colors for each point. shape is (n,3)

    Returns vtkPolyData object
    """
    import vtk
    vpoints = vtk.vtkPoints()
    vpoints.SetNumberOfPoints(points.shape[0])
    for i in range(points.shape[0]):
        vpoints.SetPoint(i, points[i])
    vpoly = vtk.vtkPolyData()
    vpoly.SetPoints(vpoints)
    
    if not colors is None:
        vcolors = vtk.vtkUnsignedCharArray()
        vcolors.SetNumberOfComponents(3)
        vcolors.SetName("Colors")
        vcolors.SetNumberOfTuples(points.shape[0])
        for i in range(points.shape[0]):
            vcolors.SetTuple3(i ,colors[i,0],colors[i,1], colors[i,2])
        vpoly.GetPointData().SetScalars(vcolors)

    vcells = vtk.vtkCellArray()
    
    for i in range(points.shape[0]):
        vcells.InsertNextCell(1)
        vcells.InsertCellPoint(i)
        
    vpoly.SetVerts(vcells)
    
    return vpoly 
Example #24
Source File: earth.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, radius=6371.0e6):
        AlgorithmBase.__init__(self,
                               nInputPorts=0,
                               nOutputPorts=1, outputType='vtkPolyData')
        self.__radius = radius 
Example #25
Source File: filters.py    From pyvista with MIT License 5 votes vote down vote up
def fill_holes(poly_data, hole_size, inplace=False, progress_bar=False):  # pragma: no cover
        """
        Fill holes in a pyvista.PolyData or vtk.vtkPolyData object.

        Holes are identified by locating boundary edges, linking them together
        into loops, and then triangulating the resulting loops. Note that you
        can specify an approximate limit to the size of the hole that can be
        filled.

        Parameters
        ----------
        hole_size : float
            Specifies the maximum hole size to fill. This is represented as a
            radius to the bounding circumsphere containing the hole. Note that
            this is an approximate area; the actual area cannot be computed
            without first triangulating the hole.

        inplace : bool, optional
            Return new mesh or overwrite input.

        progress_bar : bool, optional
            Display a progress bar to indicate progress.

        Returns
        -------
        mesh : pyvista.PolyData
            Mesh with holes filled.  None when inplace=True

        """
        logging.warning('pyvista.PolyData.fill_holes is known to segfault. '
                        'Use at your own risk')
        alg = vtk.vtkFillHolesFilter()
        alg.SetHoleSize(hole_size)
        alg.SetInputData(poly_data)
        _update_alg(alg, progress_bar, 'Filling Holes')

        mesh = _get_output(alg)
        if inplace:
            poly_data.overwrite(mesh)
        else:
            return mesh 
Example #26
Source File: slicing.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, n_slices=5, nearest_nbr=True):
        ManySlicesAlongPoints.__init__(self, outputType='vtkPolyData')
        self.__planes = None
        self.__loc = 50 # Percent (halfway) 
Example #27
Source File: filters.py    From pyvista with MIT License 5 votes vote down vote up
def _clip_with_function(dataset, function, invert=True, value=0.0):
        """Clip using an implicit function (internal helper)."""
        if isinstance(dataset, vtk.vtkPolyData):
            alg = vtk.vtkClipPolyData()
        # elif isinstance(dataset, vtk.vtkImageData):
        #     alg = vtk.vtkClipVolume()
        #     alg.SetMixed3DCellGeneration(True)
        else:
            alg = vtk.vtkTableBasedClipDataSet()
        alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut
        alg.SetValue(value)
        alg.SetClipFunction(function) # the implicit function
        alg.SetInsideOut(invert) # invert the clip if needed
        alg.Update() # Perform the Cut
        return _get_output(alg) 
Example #28
Source File: slicing.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def RequestData(self, request, inInfo, outInfo):
        """Used by pipeline to generate output
        """
        # Get input/output of Proxy
        pdi = self.GetInputData(inInfo, 0, 0)
        # Get output:
        #output = self.GetOutputData(outInfo, 0)
        output = vtk.vtkMultiBlockDataSet.GetData(outInfo, 0)
        self._set_axial_range(pdi)
        normal = self.get_normal()
        # Perfrom task
        # Set number of blocks based on user choice in the selction
        output.SetNumberOfBlocks(self.get_number_of_slices())
        blk = 0
        for i in range(self.get_number_of_slices()):
            temp = vtk.vtkPolyData()
            origin = self._get_origin(pdi, i)
            plane = self._generate_plane(origin, normal)
            # Perfrom slice for that index
            self._slice(pdi, temp, plane)
            output.SetBlock(blk, temp)
            output.GetMetaData(blk).Set(vtk.vtkCompositeDataSet.NAME(), 'Slice%.2d' % i)
            blk += 1

        return 1



    #### Getters / Setters #### 
Example #29
Source File: filters.py    From pyvista with MIT License 5 votes vote down vote up
def __add__(poly_data, mesh):
        """Merge these two meshes."""
        if not isinstance(mesh, vtk.vtkPolyData):
            return DataSetFilters.__add__(poly_data, mesh)
        return PolyDataFilters.boolean_add(poly_data, mesh) 
Example #30
Source File: earth.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, radius=6371.0e6, npar=15, nmer=36, **kwargs):
        AlgorithmBase.__init__(self, nInputPorts=0, nOutputPorts=1, outputType='vtkPolyData')
        self.__radius = radius
        self.__npar = npar
        self.__nmer = nmer
        # TODO: use **kwargs