本文整理汇总了Python中vtk.util.numpy_support.numpy_to_vtk方法的典型用法代码示例。如果您正苦于以下问题:Python numpy_support.numpy_to_vtk方法的具体用法?Python numpy_support.numpy_to_vtk怎么用?Python numpy_support.numpy_to_vtk使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类vtk.util.numpy_support
的用法示例。
在下文中一共展示了numpy_support.numpy_to_vtk方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: assign_cell_data
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
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
示例2: __create_structured_grid
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
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)
示例3: create_surface_points
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
def create_surface_points(self, vertices):
"""
Method to create the points that form the surfaces
Args:
vertices (numpy.array): 2D array (XYZ) with the coordinates of the points
Returns:
vtk.vtkPoints: with the coordinates of the points
"""
Points = vtk.vtkPoints()
if self.ve != 1:
vertices[:, 2] = vertices[:, 2] * self.ve
# raise NotImplementedError('Vertical exageration for surfaces not implemented yet.')
# for v in vertices:
# v[-1] = self.ve * v[-1]
# Points.InsertNextPoint(v)
Points.SetData(numpy_to_vtk(vertices))
return Points
示例4: volume_to_vtk
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
def volume_to_vtk(volelement):
"""Convert the volume element to a VTK data object.
Args:
volelement (:class:`omf.volume.VolumeElement`): The volume element to
convert
"""
output = volume_grid_geom_to_vtk(volelement.geometry)
shp = get_volume_shape(volelement.geometry)
# Add data to output
for data in volelement.data:
arr = data.array.array
arr = np.reshape(arr, shp).flatten(order='F')
c = nps.numpy_to_vtk(num_array=arr, deep=True)
c.SetName(data.name)
loc = data.location
if loc == 'vertices':
output.GetPointData().AddArray(c)
else:
output.GetCellData().AddArray(c)
return pyvista.wrap(output)
# Now set up the display names for the docs
示例5: CreateTriangles
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
def CreateTriangles(self, pc, triangles):
"Create a mesh from triangles"
self.verts = vtk.vtkPoints()
self.points_npy = pc[:, :3].copy()
self.verts.SetData(numpy_support.numpy_to_vtk(self.points_npy))
nTri = len(triangles)
self.cells = vtk.vtkCellArray()
self.pd = vtk.vtkPolyData()
# - Note that the cell array looks like this: [3 vtx0 vtx1 vtx2 3 vtx3 ... ]
self.cells_npy = np.column_stack(
[np.full(nTri, 3, dtype=np.int64), triangles.astype(np.int64)]
).ravel()
self.cells.SetCells(nTri, numpy_support.numpy_to_vtkIdTypeArray(self.cells_npy))
self.pd.SetPoints(self.verts)
self.pd.SetPolys(self.cells)
self.SetupPipelineMesh()
示例6: render
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
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)
示例7: numpy_to_image
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
def numpy_to_image(numpy_array):
"""
@brief Convert a numpy 2D or 3D array to a vtkImageData object
@param numpy_array 2D or 3D numpy array containing image data
@return vtkImageData with the numpy_array content
"""
shape = numpy_array.shape
if len(shape) < 2:
raise Exception('numpy array must have dimensionality of at least 2')
h, w = shape[0], shape[1]
c = 1
if len(shape) == 3:
c = shape[2]
# Reshape 2D image to 1D array suitable for conversion to a
# vtkArray with numpy_support.numpy_to_vtk()
linear_array = np.reshape(numpy_array, (w*h, c))
vtk_array = numpy_to_vtk(linear_array)
image = vtkImageData()
image.SetDimensions(w, h, 1)
image.AllocateScalars()
image.GetPointData().GetScalars().DeepCopy(vtk_array)
return image
示例8: vtk_points
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
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
示例9: _from_arrays
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
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.
"""
# Set the coordinates along each axial direction
# Must at least be an x array
x = np.unique(x.ravel())
self.SetXCoordinates(numpy_to_vtk(x))
if y is not None:
y = np.unique(y.ravel())
self.SetYCoordinates(numpy_to_vtk(y))
if z is not None:
z = np.unique(z.ravel())
self.SetZCoordinates(numpy_to_vtk(z))
# Ensure dimensions are properly set
self._update_dimensions()
示例10: x
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
def x(self, coords):
"""Set the coordinates along the X-direction."""
self.SetXCoordinates(numpy_to_vtk(coords))
self._update_dimensions()
self.Modified()
示例11: z
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
def z(self, coords):
"""Set the coordinates along the Z-direction."""
self.SetZCoordinates(numpy_to_vtk(coords))
self._update_dimensions()
self.Modified()
示例12: save_vtk
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
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()
示例13: save_vtk_labels
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
def save_vtk_labels(filename, tracts, scalars, lines_indices=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.GetPointData().SetScalars(ns.numpy_to_vtk(scalars))
poly_data.BuildCells()
# poly_data.SetScalars(scalars)
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()
示例14: convert_cell_conn
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
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)
示例15: getVtkFromNumpy
# 需要导入模块: from vtk.util import numpy_support [as 别名]
# 或者: from vtk.util.numpy_support import numpy_to_vtk [as 别名]
def getVtkFromNumpy(numpyArray):
def MakeCallback(numpyArray):
def Closure(caller, event):
closureArray = numpyArray
return Closure
vtkArray = numpy_support.numpy_to_vtk(numpyArray)
vtkArray.AddObserver('DeleteEvent', MakeCallback(numpyArray))
return vtkArray