Python vtk.util.numpy_support.numpy_to_vtk() Examples

The following are code examples for showing how to use vtk.util.numpy_support.numpy_to_vtk(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: telluricpy   Author: grosenkj   File: XYZtools.py    MIT License 9 votes vote down vote up
def makeSurfaceVTP(locXYZ):
    # Load the file
    if type(locXYZ) == np.ndarray:
        loc = locXYZ
    elif type(locXYZ) == str:
        loc = np.genfromtxt(locXYZ)

    # Make the pts
    vtkPts = vtk.vtkPoints()
    vtkPts.SetData(npsup.numpy_to_vtk(loc,deep=1))
    # Make the poly data
    polyPtsVTP = vtk.vtkPolyData()
    polyPtsVTP.SetPoints(vtkPts)
    # Triangulate
    del2Filt = vtk.vtkDelaunay2D()
    del2Filt.SetInputData(polyPtsVTP)
    del2Filt.Update()
    # Return
    return del2Filt.GetOutput() 
Example 2
Project: ampscan   Author: abel-research   File: vis.py    MIT License 6 votes vote down vote up
def addActor(self, CMap=None, bands=128, sRange=[0,8]):
        r"""
        Creates an ampActor based upon the ampObject 
        
        """
        self.actor = ampActor()
        #self._v = numpy_support.numpy_to_vtk(self.vert, deep=0)
        self.actor.setVert(self.vert)
        self.actor.setFaces(self.faces)
        self.actor.setNorm()
        # Test if values array is non-zero
        if self.values.any():
            self.actor.setValues(self.values)
            self.createCMap()
            if self.values.min() < 0:
                self.actor.setCMap(self.CMapN2P, bands)
                self.actor.setScalarRange([self.values.min(), self.values.max()])
                self.actor.Mapper.SetLookupTable(self.actor.lut)
            else: 
                self.actor.setCMap(self.CMap02P, bands)
                self.actor.setScalarRange([0, self.values.max()])
                self.actor.Mapper.SetLookupTable(self.actor.lut) 
Example 3
Project: ampscan   Author: abel-research   File: vis.py    MIT License 6 votes vote down vote up
def setVert(self, vert, deep=0):
        """
        Set the vertices of the ampActor
        
        Parameters
        ----------
        vert: ndarray
            The numpy array specifying the vertices 
        deep: int, default 0
            If 1, the numpy array will be deep-copied to the ampActor
        
        """
        self._v = numpy_support.numpy_to_vtk(vert, deep=deep)
        self.points.SetData(self._v)
#            self.points.SetData(vert)
        self.mesh.SetPoints(self.points) 
Example 4
Project: ampscan   Author: abel-research   File: vis.py    MIT License 6 votes vote down vote up
def setNorm(self, norm=None, deep=0):
        r"""
        Sets or calculates the vertex normals 
        
        Parameters
        ----------
        norm: ndarray, default None
            The numpy array specifying the face normals. If None, the inbuilt 
            vtk method will be used to calculate the normals
        deep: int, default 0
            If 1, the numpy array will be deep-copied to the ampActor

        """
        if norm is not None:
            self._n = numpy_support.numpy_to_vtk(norm, deep=deep)
            self.mesh.GetPointData().SetNormals(self._n)
        else:
            self.norm = vtk.vtkPolyDataNormals()
            self.norm.ComputePointNormalsOn()
            self.norm.ComputeCellNormalsOff()
            self.norm.SetFeatureAngle(30.0)
            self.norm.SetInputData(self.mesh)
            self.norm.Update()
            self.mesh.DeepCopy(self.norm.GetOutput())
        self.GetProperty().SetInterpolationToGouraud() 
Example 5
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def numpy_to_vtk(vdata,vname=None,vector=False):
    #print 'Converting %s to vtk array'%vname
    shp=vdata.shape
    if not vdata.flags['C_CONTIGUOUS']:
        deep=1
    else:
        deep=0
    #print 'deep=%i'%deep
    vdata=np.ascontiguousarray(vdata,dtype=vdata.dtype)
    if vector:
        vdata.shape=vdata.size/3,3
    else:
        vdata.shape=vdata.size
    vtkdata=numpy_support.numpy_to_vtk(vdata, deep=deep)
    if vname:
        vtkdata.SetName(vname)
    vdata.shape=shp
    return vtkdata 
Example 6
Project: telluricpy   Author: grosenkj   File: polydata.py    MIT License 6 votes vote down vote up
def extrudePolygon(polyObject,extrudeFactor,vector=None,centered=False):
    """
    Extrude polygons by a scalar factor.
    """
    extrude = vtk.vtkLinearExtrusionFilter()
    extrude.CappingOn()
    if vector is not None:
        extrude.SetExtrusionTypeToVectorExtrusion()
        extrude.SetVector(vector)
    else:
        extrude.SetExtrusionTypeToNormalExtrusion()
        polyObject = normFilter(polyObject)
    extrude.SetInputData(polyObject)
    extrude.SetScaleFactor(extrudeFactor)
    extrude.Update()
    ext = extrude.GetOutput()
    if centered and vector is not None:
        extPts = npsup.vtk_to_numpy(ext.GetPoints().GetData())
        newPts = vtk.vtkPoints()
        newNppts = extPts - (np.array(vector)*(extrudeFactor/2))
        newPts.SetData(npsup.numpy_to_vtk(newNppts,deep=1))
        ext.SetPoints(newPts)

    return ext 
Example 7
Project: pyvista   Author: pyvista   File: grid.py    MIT License 6 votes vote down vote up
def z(self, coords):
        """Set the coordinates along the Z-direction."""
        self.SetZCoordinates(numpy_to_vtk(coords))
        self.Modified()


    # @property
    # def quality(self):
    #     """
    #     Computes the minimum scaled jacobian of each cell.  Cells that have
    #     values below 0 are invalid for a finite element analysis.
    #
    #     Returns
    #     -------
    #     cellquality : np.ndarray
    #         Minimum scaled jacobian of each cell.  Ranges from -1 to 1.
    #
    #     Notes
    #     -----
    #     Requires pyansys to be installed.
    #
    #     """
    #     return UnstructuredGrid(self).quality 
Example 8
Project: pyvista   Author: pyvista   File: common.py    MIT License 6 votes vote down vote up
def t_coords(self, t_coords):
        """Set the array to use as the texture coordinates."""
        if not isinstance(t_coords, np.ndarray):
            raise TypeError('Texture coordinates must be a numpy array')
        if t_coords.ndim != 2:
            raise AssertionError('Texture coordinates must be a 2-dimensional array')
        if t_coords.shape[0] != self.n_points:
            raise AssertionError('Number of texture coordinates ({}) must match number of points ({})'.format(t_coords.shape[0], self.n_points))
        if t_coords.shape[1] != 2:
            raise AssertionError('Texture coordinates must only have 2 components, not ({})'.format(t_coords.shape[1]))
        # if np.min(t_coords) < 0.0 or np.max(t_coords) > 1.0:
        #     warnings.warn('Texture coordinates are typically within (0, 1) range. Textures will repeat on this mesh.', RuntimeWarning)
        # convert the array
        vtkarr = numpy_to_vtk(t_coords)
        vtkarr.SetName('Texture Coordinates')
        self.GetPointData().SetTCoords(vtkarr)
        self.GetPointData().Modified()
        return 
Example 9
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 6 votes vote down vote up
def updateTrail(self):
        currentpos = np.array(self.GetPosition())
        if self.trailOffset:
            currentpos += self.trailOffset
        lastpos = self.trailPoints[-1]
        if lastpos is None:  # reset list
            self.trailPoints = [currentpos] * len(self.trailPoints)
            return
        if np.linalg.norm(currentpos - lastpos) < self.trailSegmentSize:
            return

        self.trailPoints.append(currentpos)  # cycle
        self.trailPoints.pop(0)

        tpoly = self.trail.polydata()
        tpoly.GetPoints().SetData(numpy_to_vtk(self.trailPoints))
        return self 
Example 10
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 6 votes vote down vote up
def addPointScalars(self, scalars, name):
        """
        Add point scalars and assigning it a name.

        |mesh_coloring| |mesh_coloring.py|_
        """
        data = self.inputdata()
        if len(scalars) != data.GetNumberOfPoints():
            colors.printc('~times addPointScalars(): Number of scalars != nr. of points',
                          len(scalars), data.GetNumberOfPoints(), c=1)
            raise RuntimeError()

        arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)
        arr.SetName(name)
        data.GetPointData().AddArray(arr)
        data.GetPointData().SetActiveScalars(name)
        self._mapper.SetArrayName(name)
        if settings.autoResetScalarRange:
            self._mapper.SetScalarRange(np.min(scalars), np.max(scalars))
        self._mapper.SetScalarModeToUsePointData()
        self._mapper.ScalarVisibilityOn()
        return self 
Example 11
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 6 votes vote down vote up
def addCellScalars(self, scalars, name):
        """
        Add cell scalars and assigning it a name.
        """
        data = self.inputdata()
        if isinstance(scalars, str):
            scalars = vtk_to_numpy(data.GetPointData().GetArray(scalars))

        if len(scalars) != data.GetNumberOfCells():
            colors.printc("~times addCellScalars() Number of scalars != nr. of cells",
                          len(scalars), data.GetNumberOfCells(), c=1)
            raise RuntimeError()

        arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)
        arr.SetName(name)
        data.GetCellData().AddArray(arr)
        data.GetCellData().SetActiveScalars(name)
        self._mapper.SetArrayName(name)
        if settings.autoResetScalarRange:
            self._mapper.SetScalarRange(np.min(scalars), np.max(scalars))
        self._mapper.SetScalarModeToUseCellData()
        self._mapper.ScalarVisibilityOn()
        return self 
Example 12
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 6 votes vote down vote up
def addGaussNoise(self, sigma):
        """
        Add gaussian noise.

        :param float sigma: sigma is expressed in percent of the diagonal size of actor.

        :Example:
            .. code-block:: python

                from vtkplotter import Sphere

                Sphere().addGaussNoise(1.0).show()
        """
        sz = self.diagonalSize()
        pts = self.coordinates()
        n = len(pts)
        ns = np.random.randn(n, 3) * sigma * sz / 100
        vpts = vtk.vtkPoints()
        vpts.SetNumberOfPoints(n)
        vpts.SetData(numpy_to_vtk(pts + ns, deep=True))
        self._polydata.SetPoints(vpts)
        self._polydata.GetPoints().Modified()
        self.addPointVectors(-ns, 'GaussNoise')
        return self 
Example 13
Project: vtkplotter   Author: marcomusy   File: analysis.py    MIT License 6 votes vote down vote up
def delaunay2D(plist, mode='xy', tol=None):
    """
    Create a mesh from points in the XY plane.
    If `mode='fit'` then the filter computes a best fitting
    plane and projects the points onto it.

    |delaunay2d| |delaunay2d.py|_
    """
    pd = vtk.vtkPolyData()
    vpts = vtk.vtkPoints()
    vpts.SetData(numpy_to_vtk(plist, deep=True))
    pd.SetPoints(vpts)
    delny = vtk.vtkDelaunay2D()
    delny.SetInputData(pd)
    if tol:
        delny.SetTolerance(tol)
    if mode=='fit':
        delny.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE)
    delny.Update()
    return Actor(delny.GetOutput()) 
Example 14
Project: discretize   Author: simpeg   File: vtkModule.py    MIT License 6 votes vote down vote up
def assign_cell_data(vtkDS, models=None):
    """Assign the model(s) to the VTK dataset as CellData

    Parameters
    ----------

    vtkDS : pyvista.Common
        Any given VTK data object that has cell data

    models : dict(numpy.ndarray)
        Name('s) and array('s). Match number of cells

    """
    nc = vtkDS.GetNumberOfCells()
    if models is not None:
        for name, mod in models.items():
            # Convert numpy array
            if mod.shape[0] != nc:
                raise RuntimeError('Number of model cells ({}) (first axis of model array) for "{}" does not match number of mesh cells ({}).'.format(mod.shape[0], name, nc))
            vtkDoubleArr = nps.numpy_to_vtk(mod, deep=1)
            vtkDoubleArr.SetName(name)
            vtkDS.GetCellData().AddArray(vtkDoubleArr)
    return vtkDS 
Example 15
Project: discretize   Author: simpeg   File: vtkModule.py    MIT License 6 votes vote down vote up
def __create_structured_grid(ptsMat, dims, models=None):
        """An internal helper to build out structured grids"""
        # Adjust if result was 2D:
        if ptsMat.shape[1] == 2:
            # Figure out which dim is null
            nullDim = dims.index(None)
            ptsMat = np.insert(ptsMat, nullDim, np.zeros(ptsMat.shape[0]), axis=1)
        if ptsMat.shape[1] != 3:
            raise RuntimeError('Points of the mesh are improperly defined.')
        # Convert the points
        vtkPts = vtk.vtkPoints()
        vtkPts.SetData(nps.numpy_to_vtk(ptsMat, deep=True))
        # Uncover hidden dimension
        for i, d in enumerate(dims):
            if d is None:
                dims[i] = 0
            dims[i] = dims[i] + 1
        output = vtk.vtkStructuredGrid()
        output.SetDimensions(dims[0], dims[1], dims[2]) # note this subtracts 1
        output.SetPoints(vtkPts)
        # Assign the model('s) to the object
        return assign_cell_data(output, models=models) 
Example 16
Project: NURBS-Python   Author: orbingol   File: VisVTK.py    MIT License 5 votes vote down vote up
def render(self, **kwargs):
        """ Plots the volume and the control points. """
        # Calling parent function
        super(VisVolume, self).render(**kwargs)

        # Initialize a list to store VTK actors
        vtk_actors = []

        # Start plotting
        for plot in self._plots:
            # Plot control points
            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:
                # Points as spheres
                pts = np.array(plot['ptsarr'], dtype=np.float)
                vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                temp_actor = vtkh.create_actor_pts(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                                   name=plot['name'], index=plot['idx'])
                vtk_actors.append(temp_actor)

            # Plot evaluated points
            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:
                pts = np.array(plot['ptsarr'], dtype=np.float)
                vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                temp_actor = vtkh.create_actor_pts(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                                   name=plot['name'], index=plot['idx'])
                vtk_actors.append(temp_actor)

        # Render actors
        return vtkh.create_render_window(vtk_actors, dict(KeyPressEvent=(self.vconf.keypress_callback, 1.0)),
                                         figure_size=self.vconf.figure_size) 
Example 17
Project: NURBS-Python   Author: orbingol   File: VisVTK.py    MIT License 5 votes vote down vote up
def render(self, **kwargs):
        """ Plots the volume and the control points. """
        # Calling parent function
        super(VisVoxel, self).render(**kwargs)

        # Initialize a list to store VTK actors
        vtk_actors = []

        # Start plotting
        for plot in self._plots:
            # Plot control points
            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:
                # Points as spheres
                pts = np.array(plot['ptsarr'], dtype=np.float)
                vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                temp_actor = vtkh.create_actor_pts(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                                   name=plot['name'], index=plot['idx'])
                vtk_actors.append(temp_actor)

            # Plot evaluated points
            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:
                faces = np.array(plot['ptsarr'][1], dtype=np.float)
                filled = np.array(plot['ptsarr'][2], dtype=np.int)
                grid_filled = faces[filled == 1]
                temp_actor = vtkh.create_actor_hexahedron(grid=grid_filled, color=vtkh.create_color(plot['color']),
                                                          name=plot['name'], index=plot['idx'])
                vtk_actors.append(temp_actor)

        # Render actors
        return vtkh.create_render_window(vtk_actors, dict(KeyPressEvent=(self.vconf.keypress_callback, 1.0)),
                                         figure_size=self.vconf.figure_size) 
Example 18
Project: ampscan   Author: abel-research   File: vis.py    MIT License 5 votes vote down vote up
def setValues(self, values, deep=0):
        """
        Set the values of the ampActor
        
        Parameters
        ----------
        values: ndarray
            Scalar data attached to each vertex
        deep: int, default 0
            If 1, the numpy array will be deep-copied to the ampActor
        
        """
        self._values = numpy_support.numpy_to_vtk(values, deep=deep)
        self.mesh.GetPointData().SetScalars(self._values) 
Example 19
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def addVTKvariable(sgrid,varname,vardata,vector=False):
    shape=[i for i in reversed(vardata.shape[:3])]
    if len(vardata.shape) == 4:
        shape.append(vardata.shape[3])
    print 'Adding variable %s with shape %s'%(varname,str(shape))
    vdata=numpy_to_vtk(vardata,varname,vector)
    sgrid.GetPointData().AddArray(vdata) 
Example 20
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def getVTKpoints(grid):
    shape=grid.shape
    #nlen=np.prod(shape[:-1])
    #grid.shape=(nlen,shape[-1])
    vgrid=numpy_to_vtk(grid,vector=True)
    pts=vtk.vtkPoints() #@UndefinedVariable
    pts.SetData(vgrid)
    return pts 
Example 21
Project: BrainSpace   Author: MICA-MNI   File: wrappers.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def SetTable(self, table):
        """Set table.

        Wraps the `SetTable` method of `vtkLookupTable` to accept an ndarray.

        Parameters
        ----------
        table : vtkUnsignedCharArray or ndarray, shape = (n, 4)
            Table array used to map scalars to colors.
        """
        if isinstance(table, np.ndarray):
            table = numpy_to_vtk(table)
        self.VTKObject.SetTable(table) 
Example 22
Project: javelin   Author: rosswhitfield   File: io.py    MIT License 5 votes vote down vote up
def numpy_to_vti(array, origin, spacing, filename):
    """This function write a VtkImageData vti file from a numpy array.

    :param array: input array
    :type array: :class:`numpy.ndarray`
    :param origin: the origin of the array
    :type origin: array like object of values
    :param spacing: the step in each dimension
    :type spacing: array like object of values
    :param filename: output filename (.vti)
    :type filename: str
    """

    if array.ndim != 3:
        raise ValueError("Only works with 3 dimensional arrays")

    import vtk
    from vtk.util.numpy_support import numpy_to_vtk, get_vtk_array_type

    vtkArray = numpy_to_vtk(num_array=array.flatten('F'), deep=True,
                            array_type=get_vtk_array_type(array.dtype))

    imageData = vtk.vtkImageData()
    imageData.SetOrigin(origin)
    imageData.SetSpacing(spacing)
    imageData.SetDimensions(array.shape)
    imageData.GetPointData().SetScalars(vtkArray)

    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(filename)
    writer.SetInputData(imageData)
    writer.Write() 
Example 23
Project: telluricpy   Author: grosenkj   File: GIStools.py    MIT License 5 votes vote down vote up
def makePolygon(polygon,elevation=0,triangulate=False):
    """
    Function to make a 2D vtk polygon PolyData from points making up a polygon.

    Inputs
        polygon - array list of vertices in clockwise order
        elevation - float, elevation of the polygon
        triangulate - boolean, triangulate the surface

    Output
        polyData - returns polydata of the surface polygon
    """

    # Make a enclosed polygons
    nrBasepts = len(polygon)
    ptsArr = np.hstack((polygon,np.ones((polygon.shape[0],1))*elevation))
    ppts = vtk.vtkPoints()
    ppts.SetData(npsup.numpy_to_vtk(ptsArr,deep=1))
    # Make the cells array of polygons
    polys = vtk.vtkCellArray()
    poly = vtk.vtkPolygon()
    poly.GetPointIds().SetNumberOfIds(len(ptsArr))
    for ind in np.arange(len(ptsArr)):
        poly.GetPointIds().SetId(ind,ind)
    polys.InsertNextCell(poly)

    polyPolyData = vtk.vtkPolyData()
    polyPolyData.SetPoints(ppts)
    polyPolyData.SetPolys(polys)
    if triangulate:
        triFilt = vtk.vtkTriangleFilter()
        triFilt.SetInputData(polyPolyData)
        triFilt.Update()
        return triFilt.GetOutput()
    else:
        return polyPolyData 
Example 24
Project: telluricpy   Author: grosenkj   File: dataset.py    MIT License 5 votes vote down vote up
def addNPDataArrays(vtkObj,arrDict,arrType='Cell'):
    """ Function to add a nparray to vtkObject"""
    for nameArr,npArr in arrDict.iteritems():
        vtkArr = npsup.numpy_to_vtk(npArr,deep=1)
        vtkArr.SetName(nameArr)
        if arrType == 'Cell':
            vtkObj.GetCellData().AddArray(vtkArr)
        elif arrType == 'Point':
            vtkObj.GetPointData().AddArray(vtkArr)
        else:
            raise Exception('Not a support arrType') 
Example 25
Project: LightField   Author: nicrip   File: Primitives.py    MIT License 5 votes vote down vote up
def LineStrip(numpy_array, color_array=None):
    if color_array is not None:
        numpy_array = _convertLineStripToLineList(numpy_array)
        return LineList(numpy_array, color_array)

    if np.shape(numpy_array)[0] == 3:
        numpy_array = np.transpose(numpy_array)
    len_array = np.shape(numpy_array)[0]

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(len_array)
    points.SetData(nps.numpy_to_vtk(numpy_array, deep=1))

    lines = vtk.vtkCellArray()
    lines.InsertNextCell(len_array)
    for i in xrange(len_array):
        lines.InsertCellPoint(i)

    polygon = vtk.vtkPolyData()
    polygon.SetPoints(points)
    polygon.SetLines(lines)

    polygonMapper = vtk.vtkPolyDataMapper()
    polygonMapper.SetInputConnection(polygon.GetProducerPort())

    actor = vtk.vtkActor()
    actor.SetMapper(polygonMapper)

    return actor 
Example 26
Project: LightField   Author: nicrip   File: Primitives.py    MIT License 5 votes vote down vote up
def LineList(numpy_array, color_array=None):
    if np.shape(numpy_array)[0] == 3:
        numpy_array = np.transpose(numpy_array)
    len_array = np.shape(numpy_array)[0]

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(len_array)
    points.SetData(nps.numpy_to_vtk(numpy_array, deep=1))

    lines = vtk.vtkCellArray()
    num_lines = len_array/2
    line_count = 0
    for i in xrange(0, len_array, 2):
        lines.InsertNextCell(2)
        lines.InsertCellPoint(i)
        lines.InsertCellPoint(i+1)
        line_count += 1
        if line_count == num_lines:
            break

    polygon = vtk.vtkPolyData()
    polygon.SetPoints(points)
    polygon.SetLines(lines)

    # color
    if color_array is not None:
        if np.shape(color_array)[0] == 3:
            color_array = np.transpose(color_array)
        colors = nps.numpy_to_vtk(color_array, deep=1)
        colors.SetName("Colors")
        polygon.GetCellData().SetScalars(colors)

    polygonMapper = vtk.vtkPolyDataMapper()
    polygonMapper.SetInputConnection(polygon.GetProducerPort())

    actor = vtk.vtkActor()
    actor.SetMapper(polygonMapper)

    return actor 
Example 27
Project: LightField   Author: nicrip   File: Primitives.py    MIT License 5 votes vote down vote up
def LineLoop(numpy_array, color_array=None):
    if color_array is not None:
        numpy_array = _convertLineLoopToLineList(numpy_array)
        return LineList(numpy_array, color_array)

    if np.shape(numpy_array)[0] == 3:
        numpy_array = np.transpose(numpy_array)
    len_array = np.shape(numpy_array)[0]

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(len_array)
    points.SetData(nps.numpy_to_vtk(numpy_array, deep=1))

    lines = vtk.vtkCellArray()
    lines.InsertNextCell(len_array+1)
    for i in xrange(len_array):
        lines.InsertCellPoint(i)
    lines.InsertCellPoint(0)

    polygon = vtk.vtkPolyData()
    polygon.SetPoints(points)
    polygon.SetLines(lines)

    polygonMapper = vtk.vtkPolyDataMapper()
    polygonMapper.SetInputConnection(polygon.GetProducerPort())

    actor = vtk.vtkActor()
    actor.SetMapper(polygonMapper)

    return actor 
Example 28
Project: LightField   Author: nicrip   File: Primitives.py    MIT License 5 votes vote down vote up
def TriangleStrip(numpy_array, color_array=None):
    if color_array is not None:
        numpy_array = _convertTriangleStripToTriangleList(numpy_array)
        return TriangleList(numpy_array, color_array)

    if np.shape(numpy_array)[0] == 3:
        numpy_array = np.transpose(numpy_array)
    len_array = np.shape(numpy_array)[0]

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(len_array)
    points.SetData(nps.numpy_to_vtk(numpy_array, deep=1))

    triangleStrip = vtk.vtkTriangleStrip()
    triangleStrip.GetPointIds().SetNumberOfIds(len_array)
    for i in xrange(len_array):
        triangleStrip.GetPointIds().SetId(i,i)
     
    cells = vtk.vtkCellArray()
    cells.InsertNextCell(triangleStrip)
     
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetStrips(cells)

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(polydata)
     
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor 
Example 29
Project: LightField   Author: nicrip   File: Primitives.py    MIT License 5 votes vote down vote up
def PointCloud(numpy_array, color_array=None):
    if np.shape(numpy_array)[0] == 3:
        numpy_array = np.transpose(numpy_array)
    len_array = np.shape(numpy_array)[0]

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(len_array)
    points.SetData(nps.numpy_to_vtk(numpy_array, deep=1))

    verts = vtk.vtkCellArray()
    for i in xrange(len_array):
        verts.InsertNextCell(1)
        verts.InsertCellPoint(i)
     
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetVerts(verts)

    # color
    if color_array is not None:
        if np.shape(color_array)[0] == 3:
            color_array = np.transpose(color_array)
        colors = nps.numpy_to_vtk(color_array, deep=1)
        colors.SetName("Colors")
        polydata.GetCellData().SetScalars(colors)

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(polydata)
     
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor 
Example 30
Project: pyvista   Author: pyvista   File: helpers.py    MIT License 5 votes vote down vote up
def vtk_points(points, deep=True):
    """Convert numpy points to a vtkPoints object."""
    if not points.flags['C_CONTIGUOUS']:
        points = np.ascontiguousarray(points)
    vtkpts = vtk.vtkPoints()
    vtkpts.SetData(nps.numpy_to_vtk(points, deep=deep))
    return vtkpts 
Example 31
Project: pyvista   Author: pyvista   File: grid.py    MIT License 5 votes vote down vote up
def _from_arrays(self, x, y, z):
        """Create VTK rectilinear grid directly from numpy arrays.

        Each array gives the uniques coordinates of the mesh along each axial
        direction. To help ensure you are using this correctly, we take the unique
        values of each argument.

        Parameters
        ----------
        x : np.ndarray
            Coordinates of the nodes in x direction.

        y : np.ndarray
            Coordinates of the nodes in y direction.

        z : np.ndarray
            Coordinates of the nodes in z direction.

        """
        x = np.unique(x.ravel())
        y = np.unique(y.ravel())
        z = np.unique(z.ravel())
        # Set the cell spacings and dimensions of the grid
        self.SetDimensions(len(x), len(y), len(z))
        self.SetXCoordinates(numpy_to_vtk(x))
        self.SetYCoordinates(numpy_to_vtk(y))
        self.SetZCoordinates(numpy_to_vtk(z)) 
Example 32
Project: pyvista   Author: pyvista   File: grid.py    MIT License 5 votes vote down vote up
def x(self, coords):
        """Set the coordinates along the X-direction."""
        self.SetXCoordinates(numpy_to_vtk(coords))
        self.Modified() 
Example 33
Project: vtkplotter   Author: marcomusy   File: dolfin.py    MIT License 5 votes vote down vote up
def move(self, u=None, deltas=None):
        """Move mesh according to solution `u`
        or from calculated vertex displacements `deltas`.
        """
        if u is None:
            u = self.u
        if deltas is None:
            if self.u_values is not None:
                deltas = self.u_values
            else:
                deltas = _compute_uvalues(u, self.mesh)
                self.u_values = deltas

        if hasattr(self.mesh, "coordinates"):
            coords = self.mesh.coordinates()
        else:
            coords = self.mesh.geometry.points

        if coords.shape != deltas.shape:
            printc("ERROR: Try to move mesh with wrong solution type shape:",
                  coords.shape, 'vs', deltas.shape, c=1)
            printc("Mesh is not moved. Try mode='color' in plot().", c=1)
            return

        movedpts = coords + deltas
        if movedpts.shape[1] == 2: #2d
            movedpts = np.c_[movedpts, np.zeros(movedpts.shape[0])]
        self.polydata(False).GetPoints().SetData(numpy_to_vtk(movedpts))
        self._polydata.GetPoints().Modified() 
Example 34
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 5 votes vote down vote up
def setPoints(self, pts):
        """
        Set specific points coordinates in mesh. Input is a python list.
        Actor transformation is reset to its mesh position/orientation.

        :param list pts: new coordinates of mesh vertices.
        """
        vpts = self._polydata.GetPoints()
        vpts.SetData(numpy_to_vtk(np.ascontiguousarray(pts), deep=True))
        self._polydata.GetPoints().Modified()
        # reset actor to identity matrix position/rotation:
        self.PokeMatrix(vtk.vtkMatrix4x4())
        return self 
Example 35
Project: vtkplotter   Author: marcomusy   File: actors.py    MIT License 5 votes vote down vote up
def __init__(self, obj=None):
        vtk.vtkImageActor.__init__(self)
        Prop.__init__(self)

        if utils.isSequence(obj) and len(obj):
            iac = vtk.vtkImageAppendComponents()
            for i in range(3):
                #arr = np.flip(np.flip(array[:,:,i], 0), 0).ravel()
                arr = np.flip(obj[:,:,i], 0).ravel()
                varb = numpy_to_vtk(arr, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
                imgb = vtk.vtkImageData()
                imgb.SetDimensions(obj.shape[1], obj.shape[0], 1)
                imgb.GetPointData().SetScalars(varb)
                iac.AddInputData(0, imgb)
            iac.Update()
            self.SetInputData(iac.GetOutput())
            #self.mirror()

        elif isinstance(obj, str):
            if ".png" in obj:
                picr = vtk.vtkPNGReader()
            elif ".jpg" in obj or ".jpeg" in obj:
                picr = vtk.vtkJPEGReader()
            elif ".bmp" in obj:
                picr = vtk.vtkBMPReader()
            picr.SetFileName(obj)
            picr.Update()
            self.SetInputData(picr.GetOutput()) 
Example 36
Project: MeshParty   Author: sdorkenw   File: trimesh_vtk.py    Apache License 2.0 5 votes vote down vote up
def numpy_rep_to_vtk(vertices, shapes, edges=None):
    """ converts a numpy representation of vertices and vertex connection graph
      to a polydata object and corresponding cell array

    Parameters
    ----------
    vertices: a Nx3 numpy array of vertex locations
    shapes: a MxK numpy array of vertex connectivity
                       (could be triangles (K=3) or edges (K=2))

    Returns
    -------
    vtk.vtkPolyData
        a polydata object with point set according to vertices,
    vtkCellArray
        a vtkCellArray of the shapes

    """

    mesh = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    points.SetData(numpy_to_vtk(vertices, deep=1))
    mesh.SetPoints(points)

    cells = numpy_to_vtk_cells(shapes)
    if edges is not None:
        if len(edges) > 0:
            edges = numpy_to_vtk_cells(edges)
        else:
            edges = None

    return mesh, cells, edges 
Example 37
Project: PVGeo   Author: OpenGeoVis   File: interface.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_cell_conn(cell_connectivity):
    """Converts cell connectivity arrays to a cell matrix array that makes sense
    for VTK cell arrays.
    """
    cellsMat = np.concatenate(
            (
                np.ones((cell_connectivity.shape[0], 1), dtype=np.int64)*cell_connectivity.shape[1],
                cell_connectivity
            ),
            axis=1).ravel()
    return nps.numpy_to_vtk(cellsMat, deep=True, array_type=vtk.VTK_ID_TYPE) 
Example 38
Project: spark-mpi-experimentation   Author: Kitware   File: gdalRead.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def processFile(fileName):
    print('Processing %s' % fileName)
    year, imgDims, mint, maxt, avgt, avgBand = readFileAndCompute(fileName)

    print('    Year: %s, min avg temp: %f deg F, max avg temp: %f deg F, earth avg temp: %f deg F' % (year, kToF(mint), kToF(maxt), kToF(avgt)))

    imgData = vtk.vtkImageData()
    imgData.SetDimensions(imgDims[0], imgDims[1], 0)
    imgData.SetSpacing(1, 1, 1)
    imgData.SetOrigin(0, 0, 0)
    imgData.SetExtent(0, imgDims[0] - 1, 0, imgDims[1] - 1, 0, 0)
    imgData.AllocateScalars(vtk.VTK_FLOAT, 1)

    pointData = imgData.GetPointData()
    dataArray = numpy_support.numpy_to_vtk(np.ndarray.flatten(avgBand[::-1,:], 0))
    dataArray.SetName('Annual Avg Temp')
    pointData.SetScalars(dataArray)

    imgWriter = vtkIOXML.vtkXMLImageDataWriter()
    imgWriter.SetFileName('tasmax_%s.vti' % (year))
    imgWriter.SetInputData(imgData)
    imgWriter.Write()

# ---------------------------------------------------------------------------

# for fileName in fileNames:
#     fpath = os.path.join(basepath, fileName)
#     processFile(fpath) 
Example 39
Project: spark-mpi-experimentation   Author: Kitware   File: convertToMultiArray.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def processFile(fileName):
    # junk = raw_input('blah')

    print('Processing %s' % fileName)

    year = fileName.split('_')[-1][:-4]
    dataset = gdal.Open(fileName)
    numBands = dataset.RasterCount

    imgDims = [dataset.RasterXSize, dataset.RasterYSize]

    imgData = vtk.vtkImageData()
    imgData.SetDimensions(imgDims[0], imgDims[1], 0)
    imgData.SetSpacing(1, 1, 1)
    imgData.SetOrigin(0, 0, 0)
    imgData.SetExtent(0, imgDims[0] - 1, 0, imgDims[1] - 1, 0, 0)

    pointData = imgData.GetPointData()

    # for bandId in range(numBands):
    for bandId in [0, 89, 179, 269]:
        print('  band %d' % (bandId + 1))
        band = dataset.GetRasterBand(bandId + 1).ReadAsArray()

        dataArray = numpy_support.numpy_to_vtk(np.ndarray.flatten(band[::-1,:], 0).astype(np.dtype(np.int32)), deep = 1)
        dataArray.SetName('Daily Max (%d)' % (bandId + 1))
        pointData.AddArray(dataArray)

    pointData.SetActiveScalars('Daily Max (0)')

    imgWriter = vtkIOXML.vtkXMLImageDataWriter()
    imgWriter.SetFileName('tasmax_%s.vti' % (year))
    imgWriter.SetInputData(imgData)
    imgWriter.Write()

# ---------------------------------------------------------------------------

# for fileName in fileNames:
#     fpath = os.path.join(basepath, fileName)
#     processFile(fpath) 
Example 40
Project: Pegamoid   Author: Jellby   File: pegamoid.py    GNU General Public License v3.0 5 votes vote down vote up
def set_transparency(self, white_background, black_background):
    wdata = numpy_support.vtk_to_numpy(white_background.GetPointData().GetScalars()).astype(float)
    bdata = numpy_support.vtk_to_numpy(black_background.GetPointData().GetScalars()).astype(float)
    if (bdata.shape[1] == 3):
      output = np.hstack((bdata, np.ones((bdata.shape[0], 1))))
    else:
      output = deepcopy(bdata)
    alpha = 255 - (wdata[:,0:3].max(1) - bdata[:,0:3].max(1))
    mask = alpha > 0
    output[:,0:3] *= 255/np.where(mask[:,np.newaxis], alpha[:,np.newaxis], 255)
    output[:,3] = alpha
    oi = vtk.vtkImageData()
    oi.CopyStructure(black_background)
    oi.GetPointData().SetScalars(numpy_support.numpy_to_vtk(output, 1, vtk.VTK_UNSIGNED_CHAR))
    return oi 
Example 41
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 5 votes vote down vote up
def del_all_lines(self):
        """
        Deletes all lines.
        """
        vtk_data = numpy_support.numpy_to_vtkIdTypeArray(np.array([], dtype=np.int64), deep=True)
        self.lines.SetCells(0, vtk_data)

        vtk_data = numpy_support.numpy_to_vtk(num_array=np.array([]), deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        self.line_colors.DeepCopy(vtk_data)

        self.lines_poly.Modified() 
Example 42
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 5 votes vote down vote up
def set_all_point_colors(self, color):
        """
        Sets the color of every point.

        Args:
            color (tuple, list, np.ndarray, np.generic): a single rgb color in the form of [[int, int, int]]
        """
        np_color_data = numpy_support.vtk_to_numpy(self.point_colors)
        np_color_data = np.tile(color, (np_color_data.shape[0], 1))
        vtk_data = numpy_support.numpy_to_vtk(num_array=np_color_data, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        self.point_colors.DeepCopy(vtk_data) 
Example 43
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 5 votes vote down vote up
def set_point_colors(self, colors, point_indices=None):
        if point_indices is None:
            if isinstance(colors, (list, tuple, np.ndarray, np.generic)):
                vtk_data = numpy_support.numpy_to_vtk(num_array=colors, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
                self.point_colors.DeepCopy(vtk_data)
        elif isinstance(point_indices, (list, tuple, np.ndarray, np.generic)):
            np_color_data = numpy_support.vtk_to_numpy(self.point_colors)
            np_color_data[point_indices] = colors
            vtk_data = numpy_support.numpy_to_vtk(num_array=np_color_data, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
            self.point_colors.DeepCopy(vtk_data)

        # self.points_poly.GetPointData().GetScalars().Modified()
        self.points_poly.Modified() 
Example 44
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 5 votes vote down vote up
def position_points(self, positions, point_indices=None):
        #todo:unit test

        """
        Untested with most recent changes.

        Sets the positions of specific points, all points, or one point.

        Args:
            positions ():
            point_indices ():
        """
        if point_indices == None:
            vtk_data = numpy_support.numpy_to_vtk(num_array=positions, deep=True, array_type=vtk.VTK_FLOAT)
            self.points.DeepCopy(vtk_data)
        elif isinstance(point_indices, (list, tuple)):
            if isinstance(positions, (list, tuple)):
                for i in range(len(point_indices)):
                    x, y, z = positions[i % len(positions)]
                    self.points.SetPoint(point_indices[i], (x, y, z))
            else:
                for i in range(len(point_indices)):
                    x, y, z = positions
                    self.points.SetPoint(point_indices[i], (x, y, z))
        else:
            x, y, z = positions
            self.points.SetPoint(point_indices, (x, y, z))
        self.points_poly.Modified() 
Example 45
Project: mCTSegmentation   Author: MIPT-Oulu   File: visualization.py    MIT License 5 votes vote down vote up
def numpy2vtk(stack, spacing, color):
    dims = stack.shape
    stack64bit = stack.ravel().astype(np.float64) * color
    vtk_array = numpy_support.numpy_to_vtk(stack64bit, array_type=vtk.VTK_FLOAT)
    vtk_data = vtk.vtkImageData()
    vtk_data.SetExtent(0, dims[2] - 1, 0, dims[1] - 1, 0, dims[0] - 1)
    # Use spacing != 1, if axes dimensions should differ from data dimensions
    vtk_data.SetSpacing(spacing, spacing, spacing)
    # Set vtk array to image data
    vtk_data.GetPointData().SetScalars(vtk_array)
    return vtk_data 
Example 46
Project: NURBS-Python   Author: orbingol   File: VisVTK.py    MIT License 4 votes vote down vote up
def render(self, **kwargs):
        """ Plots the curve and the control points polygon. """
        # Calling parent function
        super(VisCurve3D, self).render(**kwargs)

        # Initialize a list to store VTK actors
        vtk_actors = []

        # Start plotting
        for plot in self._plots:
            # Plot control points
            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:
                # Points as spheres
                pts = np.array(plot['ptsarr'], dtype=np.float)
                # Handle 2-dimensional data
                if pts.shape[1] == 2:
                    pts = np.c_[pts, np.zeros(pts.shape[0], dtype=np.float)]
                vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                actor1 = vtkh.create_actor_pts(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                               name=plot['name'], idx=plot['idx'])
                vtk_actors.append(actor1)
                # Lines
                actor2 = vtkh.create_actor_polygon(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                                   name=plot['name'], index=plot['idx'], size=self.vconf.line_width)
                vtk_actors.append(actor2)

            # Plot evaluated points
            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:
                pts = np.array(plot['ptsarr'], dtype=np.float)
                # Handle 2-dimensional data
                if pts.shape[1] == 2:
                    pts = np.c_[pts, np.zeros(pts.shape[0], dtype=np.float)]
                vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                actor1 = vtkh.create_actor_polygon(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                                   name=plot['name'], index=plot['idx'], size=self.vconf.line_width * 2)
                vtk_actors.append(actor1)

        # Render actors
        return vtkh.create_render_window(vtk_actors, dict(KeyPressEvent=(self.vconf.keypress_callback, 1.0)),
                                         figure_size=self.vconf.figure_size)


# It is easier to plot 2-dimensional curves with VisCurve3D 
Example 47
Project: NURBS-Python   Author: orbingol   File: VisVTK.py    MIT License 4 votes vote down vote up
def render(self, **kwargs):
        """ Plots the surface and the control points grid. """
        # Calling parent function
        super(VisSurface, self).render(**kwargs)

        # Initialize a list to store VTK actors
        vtk_actors = []

        # Start plotting
        for plot in self._plots:
            # Plot control points
            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:
                vertices = [v.data for v in plot['ptsarr'][0]]
                faces = [q.data for q in plot['ptsarr'][1]]
                # Points as spheres
                pts = np.array(vertices, dtype=np.float)
                vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                actor1 = vtkh.create_actor_pts(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                               name=plot['name'], index=plot['idx'])
                vtk_actors.append(actor1)
                # Quad mesh
                lines = np.array(faces, dtype=np.int)
                actor2 = vtkh.create_actor_mesh(pts=vtkpts, lines=lines, color=vtkh.create_color(plot['color']),
                                                name=plot['name'], index=plot['idx'], size=self.vconf.line_width)
                vtk_actors.append(actor2)

            # Plot evaluated points
            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:
                vertices = [v.data for v in plot['ptsarr'][0]]
                vtkpts = numpy_to_vtk(vertices, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                faces = [t.data for t in plot['ptsarr'][1]]
                tris = np.array(faces, dtype=np.int)
                actor1 = vtkh.create_actor_tri(pts=vtkpts, tris=tris, color=vtkh.create_color(plot['color']),
                                               name=plot['name'], index=plot['idx'])
                vtk_actors.append(actor1)

            # Plot trim curves
            if self.vconf.display_trims:
                if plot['type'] == 'trimcurve':
                    pts = np.array(plot['ptsarr'], dtype=np.float)
                    vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                    vtkpts.SetName(plot['name'])
                    actor1 = vtkh.create_actor_polygon(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                                       name=plot['name'], index=plot['idx'], size=self.vconf.trim_size)
                    vtk_actors.append(actor1)

        # Render actors
        return vtkh.create_render_window(vtk_actors, dict(KeyPressEvent=(self.vconf.keypress_callback, 1.0)),
                                         figure_size=self.vconf.figure_size) 
Example 48
Project: BrainSpace   Author: MICA-MNI   File: mesh_creation.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def build_polydata(points, cells=None):
    """Build surface (PolyData) from points and cells.

    Parameters
    ----------
    points : ndarray, shape = (n_points, 3)
        Array of points.
    cells : ndarray, shape = (n_cells, nd), optional
        Array of cells. Cells can be vertex (nd=1), line (nd=2) or
        triangle (nd=3). Default is None (no topology information).

    Returns
    -------
    output : BSPolyData
        Returns surface (PolyData).

    See Also
    --------
    :func:`to_vertex`
    :func:`to_lines`

    Notes
    -----
    Point ids within cells must start from 0 (first point) and contain all
    points.

    """

    s = BSPolyData()
    s.SetPoints(points)

    if cells is not None:
        n_points = points.shape[0]
        if cells.min() > 0:
            raise ValueError('Cell with Id 0 is missing.')
        if cells.max() != n_points - 1:
            raise ValueError('Cells do not include all points.')
        if np.unique(cells).size != n_points:
            raise ValueError('Cells do not include all points.')

        n_cells, n_points_cell = cells.shape
        vtk_cells = np.empty((n_cells, n_points_cell + 1), dtype=np.uintp)
        vtk_cells[:, 0] = n_points_cell
        vtk_cells[:, 1:] = cells

        cells = numpy_to_vtk(vtk_cells, array_type=VTK_ID_TYPE)
        ca = vtkCellArray()
        ca.SetCells(n_cells, cells)
        if n_points_cell == 1:
            s.SetVerts(ca)
        elif n_points_cell == 2:
            s.SetLines(ca)
        else:
            s.SetPolys(ca)

    # Triangulation needed
    return serial_connect(s, vtkTriangleFilter()) 
Example 49
Project: telluricpy   Author: grosenkj   File: polydata.py    MIT License 4 votes vote down vote up
def polyDataList2polyhedVTU(polyDataList):
    """
    Function that makes polyhedron ugrid from a list of watertight polygons stored in PolyData.



    """

    # What is needed is:
    #   allPoints -vtkPoints-
    #   pointsIds -vtkIdList- for each cell
    #   hedronFaces -vtkCellArray- with all the faces.
    # Insert cells with
    # ugrid.InsertNextCell(vtk.vtkPolyHedron,
    #           nrVerts,hedronVertPtsIds,nrFaces,faceCellArray.GetPointer())
    def makeIdList(polyData,ptsShift):
        """
        Make a vtkIdList for a polyhedron from a polydata
        """
        ptsIds = vtk.vtkIdList()
        numCellFaces = polyData.GetNumberOfCells()
        ptsIds.InsertNextId(numCellFaces) # Number of cell faces
        # Add the faces
        for cF in range(numCellFaces):
            numPtsInFace = polyData.GetCell(cF).GetNumberOfPoints()
            ptsIds.InsertNextId(numPtsInFace)
            for cPF in range(numPtsInFace):
                ptsIds.InsertNextId(polyData.GetCell(cF).GetPointId(cPF)+ptsShift)
        return ptsIds
    # Start
    unstructGrid = vtk.vtkUnstructuredGrid()
    nrPts = 0
    hedronList = []
    for vtkPolyData in polyDataList:
        pts = npsup.vtk_to_numpy(vtkPolyData.GetPoints().GetData())
        nrVert = pts.shape[0]
        cellIdList = makeIdList(vtkPolyData,nrPts)
        unstructGrid.InsertNextCell(vtk.VTK_POLYHEDRON,cellIdList)

        try:
            npPts = np.concatenate((npPts,pts))
        except NameError as e:
            npPts = pts.copy()
        nrPts = nrPts + pts.shape[0]

    # Make the grid
    # Set the points
    vtkPts = vtk.vtkPoints()
    vtkPts.SetData(npsup.numpy_to_vtk(npPts,deep=1))
    unstructGrid.SetPoints(vtkPts)

    # Return
    return unstructGrid 
Example 50
Project: LightField   Author: nicrip   File: Primitives.py    MIT License 4 votes vote down vote up
def TriangleList(numpy_array, color_array=None):
    if np.shape(numpy_array)[0] == 3:
        numpy_array = np.transpose(numpy_array)
    len_array = np.shape(numpy_array)[0]

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(len_array)
    points.SetData(nps.numpy_to_vtk(numpy_array, deep=1))

    cells = vtk.vtkCellArray()
    num_triangles = len_array/3
    triangle_count = 0
    for i in xrange(0, len_array, 3):
        triangle = vtk.vtkTriangle()
        triangle.GetPointIds().SetNumberOfIds(3)
        triangle.GetPointIds().SetId(0,i)
        triangle.GetPointIds().SetId(1,i+1)
        triangle.GetPointIds().SetId(2,i+2)
        cells.InsertNextCell(triangle)
        triangle_count += 1
        if triangle_count == num_triangles:
            break
     
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetPolys(cells)

    # color
    if color_array is not None:
        if np.shape(color_array)[0] == 3:
            color_array = np.transpose(color_array)
        colors = nps.numpy_to_vtk(color_array, deep=1)
        colors.SetName("Colors")
        polydata.GetCellData().SetScalars(colors)

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(polydata)
     
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor 
Example 51
Project: LightField   Author: nicrip   File: Primitives.py    MIT License 4 votes vote down vote up
def TexturedQuad(numpy_array, image_path):
    if np.shape(numpy_array)[0] == 3:
        numpy_array = np.transpose(numpy_array)

    if image_path[-4:].lower() == '.jpg' or image_path[-4:].lower() == '.jpeg':
        reader = vtk.vtkJPEGReader()
        reader.SetFileName(image_path)
        reader.Update()
    elif image_path[-4:].lower() == '.png':
        reader = vtk.vtkPNGReader()
        reader.SetFileName(image_path)
        reader.Update()
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(4)
    points.SetData(nps.numpy_to_vtk(numpy_array, deep=1))

    quad = vtk.vtkQuad()
    quad.GetPointIds().SetId(0,0)
    quad.GetPointIds().SetId(1,1)
    quad.GetPointIds().SetId(2,2)
    quad.GetPointIds().SetId(3,3)

    quads = vtk.vtkCellArray()
    quads.InsertNextCell(quad)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetPolys(quads)

    texCoords = vtk.vtkFloatArray()
    texCoords.SetNumberOfComponents(2)
    texCoords.SetName("TextureCoordinates")
    texCoords.InsertNextTuple((0.0, 0.0))
    texCoords.InsertNextTuple((1.0, 0.0))
    texCoords.InsertNextTuple((1.0, 1.0))
    texCoords.InsertNextTuple((0.0, 1.0))

    polydata.GetPointData().SetTCoords(texCoords)

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(polydata)
     
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)

    return actor 
Example 52
Project: pyvista   Author: pyvista   File: helpers.py    MIT License 4 votes vote down vote up
def convert_array(arr, name=None, deep=0, array_type=None):
    """Convert a NumPy array to a vtkDataArray or vice versa.

    Parameters
    -----------
    arr : ndarray or vtkDataArry
        A numpy array or vtkDataArry to convert
    name : str
        The name of the data array for VTK
    deep : bool
        if input is numpy array then deep copy values

    Return
    ------
    vtkDataArray, ndarray, or DataFrame:
        the converted array (if input is a NumPy ndaray then returns
        ``vtkDataArray`` or is input is ``vtkDataArray`` then returns NumPy
        ``ndarray``). If pdf==True and the input is ``vtkDataArry``,
        return a pandas DataFrame.

    """
    if arr is None:
        return
    if isinstance(arr, np.ndarray):
        if arr.dtype is np.dtype('O'):
            arr = arr.astype('|S')
        arr = np.ascontiguousarray(arr)
        try:
            # This will handle numerical data
            arr = np.ascontiguousarray(arr)
            vtk_data = nps.numpy_to_vtk(num_array=arr, deep=deep, array_type=array_type)
        except ValueError:
            # This handles strings
            typ = get_vtk_type(arr.dtype)
            if typ == 13:
                vtk_data = convert_string_array(arr)
        if isinstance(name, str):
            vtk_data.SetName(name)
        return vtk_data
    # Otherwise input must be a vtkDataArray
    if not isinstance(arr, (vtk.vtkDataArray, vtk.vtkBitArray, vtk.vtkStringArray)):
        raise TypeError('Invalid input array type ({}).'.format(type(arr)))
    # Handle booleans
    if isinstance(arr, vtk.vtkBitArray):
        arr = vtk_bit_array_to_char(arr)
    # Handle string arrays
    if isinstance(arr, vtk.vtkStringArray):
        return convert_string_array(arr)
    # Convert from vtkDataArry to NumPy
    return nps.vtk_to_numpy(arr) 
Example 53
Project: pyvista   Author: pyvista   File: helpers.py    MIT License 4 votes vote down vote up
def vector_poly_data(orig, vec):
    """Create a vtkPolyData object composed of vectors."""
    # shape, dimension checking
    if not isinstance(orig, np.ndarray):
        orig = np.asarray(orig)

    if not isinstance(vec, np.ndarray):
        vec = np.asarray(vec)

    if orig.ndim != 2:
        orig = orig.reshape((-1, 3))
    elif orig.shape[1] != 3:
        raise Exception('orig array must be 3D')

    if vec.ndim != 2:
        vec = vec.reshape((-1, 3))
    elif vec.shape[1] != 3:
        raise Exception('vec array must be 3D')

    # Create vtk points and cells objects
    vpts = vtk.vtkPoints()
    vpts.SetData(nps.numpy_to_vtk(np.ascontiguousarray(orig), deep=True))

    npts = orig.shape[0]
    cells = np.hstack((np.ones((npts, 1), 'int'),
                       np.arange(npts).reshape((-1, 1))))

    if cells.dtype != ctypes.c_int64 or cells.flags.c_contiguous:
        cells = np.ascontiguousarray(cells, ctypes.c_int64)
    cells = np.reshape(cells, (2*npts))
    vcells = vtk.vtkCellArray()
    vcells.SetCells(npts, nps.numpy_to_vtkIdTypeArray(cells, deep=True))

    # Create vtkPolyData object
    pdata = vtk.vtkPolyData()
    pdata.SetPoints(vpts)
    pdata.SetVerts(vcells)

    # Add vectors to polydata
    name = 'vectors'
    vtkfloat = nps.numpy_to_vtk(np.ascontiguousarray(vec), deep=True)
    vtkfloat.SetName(name)
    pdata.GetPointData().AddArray(vtkfloat)
    pdata.GetPointData().SetActiveVectors(name)

    # Add magnitude of vectors to polydata
    name = 'mag'
    scalars = (vec * vec).sum(1)**0.5
    vtkfloat = nps.numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)
    vtkfloat.SetName(name)
    pdata.GetPointData().AddArray(vtkfloat)
    pdata.GetPointData().SetActiveScalars(name)

    return pyvista.PolyData(pdata) 
Example 54
Project: vtkplotter   Author: marcomusy   File: shapes.py    MIT License 4 votes vote down vote up
def _PointsColors(plist, r, cols, alpha):
    n = len(plist)
    if n != len(cols):
        printc("~times mismatch in Points() colors", n, len(cols), c=1)
        raise RuntimeError()
    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(n)
    src.Update()
    vgf = vtk.vtkVertexGlyphFilter()
    vgf.SetInputData(src.GetOutput())
    vgf.Update()
    pd = vgf.GetOutput()
    pd.GetPoints().SetData(numpy_to_vtk(plist, deep=True))

    ucols = vtk.vtkUnsignedCharArray()
    ucols.SetNumberOfComponents(4)
    ucols.SetName("pointsRGBA")
    if utils.isSequence(alpha):
        if len(alpha) != n:
            printc("~times mismatch in Points() alphas", n, len(alpha), c=1)
            raise RuntimeError()
        alphas = alpha
        alpha = 1
    else:
       alphas = (alpha,) * n

    if utils.isSequence(cols):
        c = None
        if len(cols[0]) == 4:
            for i in range(n): # FAST
                rc,gc,bc,ac = cols[i]
                ucols.InsertNextTuple4(rc, gc, bc, ac)
        else:
            for i in range(n): # SLOW
                rc,gc,bc = getColor(cols[i])
                ucols.InsertNextTuple4(rc*255, gc*255, bc*255, alphas[i]*255)
    else:
        c = cols

    pd.GetPointData().SetScalars(ucols)
    actor = Actor(pd, c, alpha).flat().pointSize(r)
    actor.mapper().ScalarVisibilityOn()
    return actor 
Example 55
Project: vtkplotter   Author: marcomusy   File: shapes.py    MIT License 4 votes vote down vote up
def Line(p0, p1=None, c="r", alpha=1, lw=1, dotted=False, res=None):
    """
    Build the line segment between points `p0` and `p1`.
    If `p0` is a list of points returns the line connecting them.
    A 2D set of coords can also be passed as p0=[x..], p1=[y..].

    :param c: color name, number, or list of [R,G,B] colors.
    :type c: int, str, list
    :param float alpha: transparency in range [0,1].
    :param lw: line width.
    :param bool dotted: draw a dotted line
    :param int res: number of intermediate points in the segment
    """
    if isinstance(p0, vtk.vtkActor): p0 = p0.GetPosition()
    if isinstance(p1, vtk.vtkActor): p1 = p1.GetPosition()

    # detect if user is passing a 2D list of points as p0=xlist, p1=ylist:
    if len(p0) > 3:
        if not utils.isSequence(p0[0]) and not utils.isSequence(p1[0]) and len(p0)==len(p1):
            # assume input is 2D xlist, ylist
            p0 = np.stack((p0, p1), axis=1)
            p1 = None

    # detect if user is passing a list of points:
    if utils.isSequence(p0[0]):
        ppoints = vtk.vtkPoints()  # Generate the polyline
        dim = len((p0[0]))
        if dim == 2:
            for i, p in enumerate(p0):
                ppoints.InsertPoint(i, p[0], p[1], 0)
        else:
            ppoints.SetData(numpy_to_vtk(p0, deep=True))
        lines = vtk.vtkCellArray()  # Create the polyline.
        lines.InsertNextCell(len(p0))
        for i in range(len(p0)):
            lines.InsertCellPoint(i)
        poly = vtk.vtkPolyData()
        poly.SetPoints(ppoints)
        poly.SetLines(lines)
    else:  # or just 2 points to link
        lineSource = vtk.vtkLineSource()
        lineSource.SetPoint1(p0)
        lineSource.SetPoint2(p1)
        if res:
            lineSource.SetResolution(res)
        lineSource.Update()
        poly = lineSource.GetOutput()

    actor = Actor(poly, c, alpha).lw(lw)
    if dotted:
        actor.GetProperty().SetLineStipplePattern(0xF0F0)
        actor.GetProperty().SetLineStippleRepeatFactor(1)
    actor.base = np.array(p0)
    actor.top = np.array(p1)
    settings.collectable_actors.append(actor)
    actor.name = "Line"
    return actor 
Example 56
Project: vtkplotter   Author: marcomusy   File: shapes.py    MIT License 4 votes vote down vote up
def Spline(points, smooth=0.5, degree=2, s=2, res=None):
    """
    Return an ``Actor`` for a spline which does not necessarly
    passing exactly through all the input points.
    Needs to import `scypi`.

    :param float smooth: smoothing factor.

        - 0 = interpolate points exactly.
        - 1 = average point positions.

    :param int degree: degree of the spline (1<degree<5)
    :param int res: number of points on the spline

    |tutorial_spline| |tutorial.py|_
    """
    from scipy.interpolate import splprep, splev
    if res is None:
        res = len(points)*20

    points = np.array(points)

    minx, miny, minz = np.min(points, axis=0)
    maxx, maxy, maxz = np.max(points, axis=0)
    maxb = max(maxx - minx, maxy - miny, maxz - minz)
    smooth *= maxb / 2  # must be in absolute units

    tckp, _ = splprep(points.T, task=0, s=smooth, k=degree)  # find the knots
    # evaluate spLine, including interpolated points:
    xnew, ynew, znew = splev(np.linspace(0, 1, res), tckp)

    ppoints = vtk.vtkPoints()  # Generate the polyline for the spline
    profileData = vtk.vtkPolyData()
    ppoints.SetData(numpy_to_vtk(np.c_[xnew, ynew, znew], deep=True))
    lines = vtk.vtkCellArray()  # Create the polyline
    lines.InsertNextCell(res)
    for i in range(res):
        lines.InsertCellPoint(i)
    profileData.SetPoints(ppoints)
    profileData.SetLines(lines)
    actline = Actor(profileData)
    actline.GetProperty().SetLineWidth(s)
    actline.base = np.array(points[0])
    actline.top = np.array(points[-1])
    settings.collectable_actors.append(actline)
    actline.name = "Spline"
    return actline 
Example 57
Project: vtkplotter   Author: marcomusy   File: shapes.py    MIT License 4 votes vote down vote up
def Tube(points, r=1, c="r", alpha=1, res=12):
    """Build a tube along the line defined by a set of points.

    :param r: constant radius or list of radii.
    :type r: float, list
    :param c: constant color or list of colors for each point.
    :type c: float, list

    |ribbon.py|_ |tube.py|_

        |ribbon| |tube|
    """
    ppoints = vtk.vtkPoints()  # Generate the polyline
    ppoints.SetData(numpy_to_vtk(points, deep=True))
    lines = vtk.vtkCellArray()
    lines.InsertNextCell(len(points))
    for i in range(len(points)):
        lines.InsertCellPoint(i)
    polyln = vtk.vtkPolyData()
    polyln.SetPoints(ppoints)
    polyln.SetLines(lines)

    tuf = vtk.vtkTubeFilter()
    tuf.CappingOn()
    tuf.SetNumberOfSides(res)
    tuf.SetInputData(polyln)
    if utils.isSequence(r):
        arr = numpy_to_vtk(np.ascontiguousarray(r), deep=True)
        arr.SetName("TubeRadius")
        polyln.GetPointData().AddArray(arr)
        polyln.GetPointData().SetActiveScalars("TubeRadius")
        tuf.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
    else:
        tuf.SetRadius(r)

    usingColScals = False
    if utils.isSequence(c) and len(c) != 3:
        usingColScals = True
        cc = vtk.vtkUnsignedCharArray()
        cc.SetName("TubeColors")
        cc.SetNumberOfComponents(3)
        cc.SetNumberOfTuples(len(c))
        for i, ic in enumerate(c):
            r, g, b = getColor(ic)
            cc.InsertTuple3(i, int(255 * r), int(255 * g), int(255 * b))
        polyln.GetPointData().AddArray(cc)
        c = None
    tuf.Update()

    actor = Actor(tuf.GetOutput(), c, alpha, computeNormals=0).phong()
    if usingColScals:
        actor.mapper().SetScalarModeToUsePointFieldData()
        actor.mapper().ScalarVisibilityOn()
        actor.mapper().SelectColorArray("TubeColors")
        actor.mapper().Modified()

    actor.base = np.array(points[0])
    actor.top = np.array(points[-1])
    settings.collectable_actors.append(actor)
    actor.name = "Tube"
    return actor 
Example 58
Project: discretize   Author: simpeg   File: vtkModule.py    MIT License 4 votes vote down vote up
def __tree_mesh_to_vtk(mesh, models=None):
        """
        Constructs a :class:`pyvista.UnstructuredGrid` object of this tree mesh and
        the given models as ``cell_arrays`` of that ``pyvista`` dataset.

        Parameters
        ----------

        mesh : discretize.TreeMesh
            The tree mesh to convert to a :class:`pyvista.UnstructuredGrid`

        models : dict(numpy.ndarray)
            Name('s) and array('s). Match number of cells

        """
        # Make the data parts for the vtu object
        # Points
        ptsMat = np.vstack((mesh.gridN, mesh.gridhN))

        # Adjust if result was 2D (voxels are pixels in 2D):
        VTK_CELL_TYPE = vtk.VTK_VOXEL
        if ptsMat.shape[1] == 2:
            # Add Z values of 0.0 if 2D
            ptsMat = np.c_[ptsMat, np.zeros(ptsMat.shape[0])]
            VTK_CELL_TYPE = vtk.VTK_PIXEL
        if ptsMat.shape[1] != 3:
            raise RuntimeError('Points of the mesh are improperly defined.')
        # Rotate the points to the cartesian system
        ptsMat = np.dot(ptsMat, mesh.rotation_matrix)
        # Grab the points
        vtkPts = vtk.vtkPoints()
        vtkPts.SetData(nps.numpy_to_vtk(ptsMat, deep=True))
        # Cells
        cellArray = [c for c in mesh]
        cellConn = np.array([cell.nodes for cell in cellArray])
        cellsMat = np.concatenate((np.ones((cellConn.shape[0], 1), dtype=int)*cellConn.shape[1], cellConn), axis=1).ravel()
        cellsArr = vtk.vtkCellArray()
        cellsArr.SetNumberOfCells(cellConn.shape[0])
        cellsArr.SetCells(cellConn.shape[0], nps.numpy_to_vtk(cellsMat, deep=True, array_type=vtk.VTK_ID_TYPE))
        # Make the object
        output = vtk.vtkUnstructuredGrid()
        output.SetPoints(vtkPts)
        output.SetCells(VTK_CELL_TYPE, cellsArr)
        # Add the level of refinement as a cell array
        cell_levels = np.array([cell._level for cell in cellArray])
        refineLevelArr = nps.numpy_to_vtk(cell_levels, deep=1)
        refineLevelArr.SetName('octreeLevel')
        output.GetCellData().AddArray(refineLevelArr)
        ubc_order = mesh._ubc_order
        # order_ubc will re-order from treemesh ordering to UBC ordering
        # need the opposite operation
        un_order = np.empty_like(ubc_order)
        un_order[ubc_order] = np.arange(len(ubc_order))
        order = nps.numpy_to_vtk(un_order)
        order.SetName('index_cell_corner')
        output.GetCellData().AddArray(order)
        # Assign the model('s) to the object
        return assign_cell_data(output, models=models) 
Example 59
Project: discretize   Author: simpeg   File: vtkModule.py    MIT License 4 votes vote down vote up
def __tensor_mesh_to_vtk(mesh, models=None):
        """
        Constructs a :class:`pyvista.RectilinearGrid`
        (or a :class:`pyvista.StructuredGrid`) object of this tensor mesh and the
        given models as ``cell_arrays`` of that grid.
        If the mesh is defined on a normal cartesian system then a rectilinear
        grid is generated. Otherwise, a structured grid is generated.

        Parameters
        ----------

        mesh : discretize.TensorMesh
            The tensor mesh to convert to a :class:`pyvista.RectilinearGrid`

        models : dict(numpy.ndarray)
            Name('s) and array('s). Match number of cells

        """
        # Deal with dimensionalities
        if mesh.dim >= 1:
            vX = mesh.vectorNx
            xD = mesh.nNx
            yD, zD = 1, 1
            vY, vZ = np.array([0, 0])
        if mesh.dim >= 2:
            vY = mesh.vectorNy
            yD = mesh.nNy
        if mesh.dim == 3:
            vZ = mesh.vectorNz
            zD = mesh.nNz
        # If axis orientations are standard then use a vtkRectilinearGrid
        if not mesh.reference_is_rotated:
            # Use rectilinear VTK grid.
            # Assign the spatial information.
            output = vtk.vtkRectilinearGrid()
            output.SetDimensions(xD, yD, zD)
            output.SetXCoordinates(nps.numpy_to_vtk(vX, deep=1))
            output.SetYCoordinates(nps.numpy_to_vtk(vY, deep=1))
            output.SetZCoordinates(nps.numpy_to_vtk(vZ, deep=1))
            return assign_cell_data(output, models=models)
        # Use a structured grid where points are rotated to the cartesian system
        ptsMat = InterfaceVTK.__get_rotated_nodes(mesh)
        dims = [mesh.nCx, mesh.nCy, mesh.nCz]
        # Assign the model('s) to the object
        return InterfaceVTK.__create_structured_grid(ptsMat, dims, models=models) 
Example 60
Project: spark-mpi-experimentation   Author: Kitware   File: convertToFileSeries.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def processFile(directory, filename):
    # junk = raw_input('blah')

    fpath = os.path.join(directory, filename)

    print('Processing %s' % filename)

    year = filename.split('_')[-1][:-4]
    dataset = gdal.Open(fpath)
    numBands = dataset.RasterCount

    imgDims = [dataset.RasterXSize, dataset.RasterYSize]

    for bandId in range(numBands):
    # for bandId in [0, 89, 179, 269]:
        imgData = vtk.vtkImageData()
        imgData.SetDimensions(imgDims[0], imgDims[1], 0)
        imgData.SetSpacing(1, 1, 1)
        imgData.SetOrigin(0, 0, 0)
        imgData.SetExtent(0, imgDims[0] - 1, 0, imgDims[1] - 1, 0, 0)
        imgData.AllocateScalars(vtk.VTK_FLOAT, 1)

        band = dataset.GetRasterBand(bandId + 1).ReadAsArray()

        pointData = imgData.GetPointData()
        dataArray = numpy_support.numpy_to_vtk(np.ndarray.flatten(band[::-1,:], 0).astype(np.dtype(np.int32)), deep = 1)
        dataArray.SetName('Daily Max')
        pointData.SetScalars(dataArray)

        imgWriter = vtkIOXML.vtkXMLImageDataWriter()
        outputFileName = '%s_%d.vti' % (filename, (bandId + 1))
        imgWriter.SetFileName(outputFileName)
        imgWriter.SetInputData(imgData)
        imgWriter.Write()

        print('    wrote to %s' % outputFileName)

# ---------------------------------------------------------------------------

# for fileName in fileNames:
#     fpath = os.path.join(basepath, fileName)
#     processFile(fpath) 
Example 61
Project: spark-mpi-experimentation   Author: Kitware   File: nonSparkReadAll.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def computeAveragesUsingNumpy():
    for fileName in fileNames:
        fpath = os.path.join(basepath, fileName)
        print('processing %s' % fpath)

        year = fileName.split('_')[-1][:-4]

        dataset = gdal.Open(fpath)
    
        sumArray = ma.zeros((dataset.RasterYSize, dataset.RasterXSize))
        total = 0
        count = 0
        numBands = dataset.RasterCount
    
        for bandId in range(numBands):
            band = ma.masked_outside(dataset.GetRasterBand(bandId + 1).ReadAsArray(), VALUE_RANGE[0], VALUE_RANGE[1])
            sumArray += band
    
        sumArray /= numBands
        total = ma.sum(ma.sum(sumArray))
        count = sumArray.count()
        minCell = ma.min(sumArray)
        maxCell = ma.max(sumArray)
        imgDims = [dataset.RasterXSize, dataset.RasterYSize]

        print('  finished computing averge for %s, writing image data' % year)

        imgData = vtk.vtkImageData()
        imgData.SetDimensions(imgDims[0], imgDims[1], 0)
        imgData.SetSpacing(1, 1, 1)
        imgData.SetOrigin(0, 0, 0)
        imgData.SetExtent(0, imgDims[0] - 1, 0, imgDims[1] - 1, 0, 0)
        imgData.AllocateScalars(vtk.VTK_FLOAT, 1)

        pointData = imgData.GetPointData()
        dataArray = numpy_support.numpy_to_vtk(np.ndarray.flatten(sumArray[::-1,:], 0).astype(np.dtype(np.int32)), deep = 1)
        dataArray.SetName('Annual Avg Temp')
        pointData.SetScalars(dataArray)
    
        imgWriter = vtkIOXML.vtkXMLImageDataWriter()
        imgWriter.SetFileName('tasmax_%s.vti' % (year))
        imgWriter.SetInputData(imgData)
        imgWriter.Write()

        print('  finished writing image data for %s' % year) 
Example 62
Project: spark-mpi-experimentation   Author: Kitware   File: convertTo3DImageData.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def computeAveragesAndBuildImgData():
    imgDims = [1440, 720, 10]

    imgData = vtk.vtkImageData()
    imgData.SetDimensions(imgDims[0] + 1, imgDims[1] + 1, imgDims[2] + 1)
    imgData.SetSpacing(1, 1, 1)
    imgData.SetOrigin(0, 0, 0)
    imgData.SetExtent(0, imgDims[0], 0, imgDims[1], 0, imgDims[2])
    imgData.AllocateScalars(vtk.VTK_FLOAT, 1)

    flattenedArrays = []

    for fileName in fileNames:
        fpath = os.path.join(basepath, fileName)
        print('processing %s' % fpath)

        year = fileName.split('_')[-1][:-4]

        dataset = gdal.Open(fpath)
    
        sumArray = ma.zeros((dataset.RasterYSize, dataset.RasterXSize))
        total = 0
        count = 0
        numBands = dataset.RasterCount
    
        for bandId in range(numBands):
            band = ma.masked_outside(dataset.GetRasterBand(bandId + 1).ReadAsArray(), VALUE_RANGE[0], VALUE_RANGE[1])
            sumArray += band
    
        sumArray /= numBands
        total = ma.sum(ma.sum(sumArray))
        count = sumArray.count()
        minCell = ma.min(sumArray)
        maxCell = ma.max(sumArray)
        imgDims = [dataset.RasterXSize, dataset.RasterYSize]

        # flattenedArrays.append(np.ndarray.flatten(sumArray[::-1,:], 0).astype(np.dtype(np.float32)))
        flattenedArrays.append(np.ndarray.flatten(sumArray[::-1,:], 0))

    allYearsAvgs = np.ma.concatenate(flattenedArrays)

    cellData = imgData.GetCellData()
    dataArray = numpy_support.numpy_to_vtk(np.ndarray.flatten(allYearsAvgs, 0), deep = 1)
    dataArray.SetName('Annual Avg Temp')
    cellData.SetScalars(dataArray)

    imgWriter = vtkIOXML.vtkXMLImageDataWriter()
    imgWriter.SetFileName('/data/scott/Documents/tasmax.vti')
    imgWriter.SetInputData(imgData)
    imgWriter.Write()

    print('\nFinished writing image data\n') 
Example 63
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 4 votes vote down vote up
def add_lines(self, lines, line_colors):
        """
        Adds multiple lines between any sets of points.

        Args:
            lines (list, tuple, np.ndarray, np.generic):
                An array in the format of [2, point_a, point_b, 2, point_c, point_d, ...]. The two is needed for VTK's
                  lines.
            line_colors (list, tuple, np.ndarray, np.generic):
                An array in the format of [[r1, g1, b1], [r2, g2, b2], ...], with the same length as the number of
                  lines.
        Returns:
            list: An array containing the memory locations of each of the newly inserted lines.

        """
        assert (isinstance(lines, (list, tuple, np.ndarray, np.generic)))
        assert (isinstance(line_colors, (list, tuple, np.ndarray, np.generic)))

        np_line_data = numpy_support.vtk_to_numpy(self.lines.GetData())
        np_line_color_data = numpy_support.vtk_to_numpy(self.line_colors)

        #todo: add lines in unused locations if possible
        mem_locations = range(int(len(np_line_data) / 3), int((len(np_line_data) + len(lines)) / 3))

        np_line_data = np.append(np_line_data, lines)

        if len(np_line_color_data) > 0:
            np_line_color_data = np.append(np_line_color_data, line_colors, axis=0)
        else:
            np_line_color_data = line_colors

        vtk_line_data = numpy_support.numpy_to_vtkIdTypeArray(np_line_data, deep=True)
        self.lines.SetCells(int(len(np_line_data) / 3), vtk_line_data)

        vtk_line_color_data = numpy_support.numpy_to_vtk(num_array=np_line_color_data,
                                                         deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        self.line_colors.DeepCopy(vtk_line_color_data)

        self.lines_poly.Modified()

        self.line_id_array.add_ids(mem_locations)

        return mem_locations 
Example 64
Project: PyGPNeural   Author: PyGPAI   File: vtk_animation_timer_callback.py    MIT License 4 votes vote down vote up
def del_lines(self, line_indices):
        #todo: change idarray to use tuples of (start,end) locations and set this to delete those partitions
        """
        Delete specific lines.

        Args:
            line_indices (tuple, list, np.ndarray, np.generic):
                An array of integers or a single integer representing line memory locations(s) to delete.
        """
        np_data = numpy_support.vtk_to_numpy(self.lines.GetData())

        np_color_data = numpy_support.vtk_to_numpy(self.line_colors)

        if isinstance(line_indices, (tuple, list, np.ndarray, np.generic)):
            last_loc = -1
            loc = 0
            np_new_data = []
            np_new_color_data = []
            for i in range(len(line_indices)):
                loc = self.line_id_array.pop_id(line_indices[i])
                if loc==None:
                    #todo: put warning here
                    continue

                if len(np_new_data) > 0:
                    np_new_data = np.append(np_new_data, np_data[(last_loc + 1) * 3:loc * 3], axis=0)
                else:
                    np_new_data = np_data[(last_loc + 1) * 3:loc * 3]

                if len(np_new_color_data) > 0:
                    np_new_color_data = np.append(np_new_color_data, np_color_data[(last_loc + 1):loc], axis=0)
                else:
                    np_new_color_data = np_color_data[(last_loc + 1):loc]

                last_loc = loc

            last_loc = loc
            loc = len(np_data) / 3

            np_data = np.append(np_new_data, np_data[(last_loc + 1) * 3:loc * 3], axis=0)

            np_data = np_data.astype(np.int64)

            np_color_data = np.append(np_new_color_data, np_color_data[(last_loc + 1):loc], axis=0)
        else:
            raise TypeError("Deletion list should be tuple, list, np.ndarray, or np.generic")

        vtk_data = numpy_support.numpy_to_vtkIdTypeArray(np_data, deep=True)
        self.lines.SetCells(int(len(np_data) / 3), vtk_data)

        vtk_data = numpy_support.numpy_to_vtk(num_array=np_color_data, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        self.line_colors.DeepCopy(vtk_data)

        self.lines_poly.Modified()