pointcloud¶
Submodule to manage point clouds.
Points¶

class
vedo.pointcloud.
Points
(inputobj=None, c=0.2, 0.2, 0.2, alpha=1, r=4, blur=False)[source]¶ Bases:
vtkRenderingCorePython.vtkFollower
,vedo.base.BaseActor
Build a
Mesh
made of only vertex points for a list of 2D/3D points. Both shapes (N, 3) or (3, N) are accepted as input, if N>3. For very large point clouds a list of colors and alpha can be assigned to each point in the form c=[(R,G,B,A), … ] where 0 <= R < 256, … 0 <= A < 256. Parameters

addTrail
(offset=None, maxlength=None, n=50, c=None, alpha=None, lw=2)[source]¶ Add a trailing line to mesh. This new mesh is accessible through mesh.trail.

alignTo
(target, iters=100, rigid=False, invert=False, useCentroids=False)[source]¶ Aligned to target mesh through the Iterative Closest Point algorithm.
The core of the algorithm is to match each vertex in one surface with the closest surface point on the other, then apply the transformation that modify one surface to best match the other (in the leastsquare sense).

applyTransform
(transformation, reset=False)[source]¶ Apply a linear or nonlinear transformation to the mesh polygonal data.
 Parameters
transformation – a
vtkTransform
,vtkMatrix4x4
or a 4x4 or 3x3 python or numpy matrix.reset (bool) – if True reset the current transformation matrix to identity after having moved the object, otherwise the internal matrix will stay the same (to only affect visualization). It the input transformation has no internal defined matrix (ie. non linear) then reset will be assumed as True.

averageSize
()[source]¶ Calculate the average size of a mesh. This is the mean of the vertex distances from the center of mass.
Add a 2D caption to an object which follows the camera movements. Latex is not supported. Returns the same input object for concatenation.
See also
vignette()
,flag()
,labels()
andlegend()
with similar functionality. Parameters
txt (str, optional) – text to be rendered. The default is the file name.
point (list, optional) – anchoring point. The default is None.
size (list, optional) – (width, height) of the caption box. The default is (0.30, 0.15).
pad (float, optional) – padding space of the caption box in pixels. The default is 5.
font (str, optional) – font name. Font “LogoType” allows for Japanese and Chinese characters. Use a monospace font for better rendering. The default is “VictorMono”. Type
vedo r fonts
for a font demo.justify (str, optional) – internal text justification. The default is “centerright”.
vspacing (float, optional) – vertical spacing between lines. The default is 1.
c (str, optional) – text and box color. The default is ‘lb’.
alpha (float, optional) – text and box transparency. The default is 1.
ontop (bool, optional) – keep the 2d caption always on top. The default is True.

cellColors
(input_array=None, cmap='jet', alpha=1, vmin=None, vmax=None, arrayName='CellScalars', n=256)[source]¶ DEPRECATED: use cmap(on=’cells’) instead.

cellIndividualColors
(colorlist, alpha=1, alphaPerCell=False)[source]¶ Colorize the faces of a mesh one by one passing a 1to1 list of colors and optionally a list of transparencies.
 Parameters
alphaPerCell (bool) –
Only matters if alpha is a sequence. If so: if True assume that the list of opacities is independent on the colors (same color cells can have different opacity), this can be very slow for large meshes,
if False [default] assume that the alpha matches the color list (same color has the same opacity). This is very fast even for large meshes.

clean
(tol=None)[source]¶ Clean mesh polydata. Can also be used to decimate a mesh if
tol
is large. Iftol=None
only removes coincident points. Parameters
tol – defines how far should be the points from each other in terms of fraction of the bounding box length.

clone2D
(pos=0, 0, coordsys=4, scale=None, c=None, alpha=None, ps=2, lw=1, sendback=False, layer=0)[source]¶ Copy a 3D Mesh into a static 2D image. Returns a
vtkActor2D
. param int coordsys
the coordinate system, options are
Displays
Normalized Display
Viewport (origin is the bottomleft corner of the window)
Normalized Viewport
View (origin is the center of the window)
World (anchor the 2d image to mesh)
 param int ps
point size in pixel units
 param int lw
line width in pixel units
 param bool sendback
put it behind any other 3D object

closestPoint
(pt, N=1, radius=None, returnIds=False)[source]¶ Find the closest point(s) on a mesh given from the input point pt.
 Parameters
Note
The appropriate kdtree search locator is built on the fly and cached for speed.

cmap
(cname, input_array=None, on='points', arrayName='', vmin=None, vmax=None, alpha=1, n=256)[source]¶ Set individual point/cell colors by providing a list of scalar values and a color map. scalars can be the string name of a
vtkArray
. Parameters
cname (str, list, vtkLookupTable, matplotlib.colors.LinearSegmentedColormap) – color map scheme to transform a real number into a color.
on (str) – either ‘points’ or ‘cells’. Apply the color map as defined on either point or cell data.
arrayName (str) – give a name to the array
vmin (float) – clip scalars to this minimum value
vmax (float) – clip scalars to this maximum value
alpha (float,list) – mesh transparency. Can be a
list
of values one for each vertex.n (int) – number of distinct colors to be used.

color
(c=False, alpha=None)[source]¶ Set/get mesh’s color. If None is passed as input, will use colors from active scalars. Same as mesh.c().

computeNormalsWithPCA
(n=20, orientationPoint=None, flip=False)[source]¶ Generate point normals using PCA (principal component analysis). Basically this estimates a local tangent plane around each sample point p by considering a small neighborhood of points around p, and fitting a plane to the neighborhood (via PCA).
 Parameters
n (int) – neighborhood size to calculate the normal
orientationPoint (list) – adjust the +/ sign of the normals so that the normals all point towards a specified point. If None, perform a traversal of the point cloud and flip neighboring normals so that they are mutually consistent.
flip (bool) – flip all normals

deletePoints
(indices, renamePoints=False)[source]¶ Delete a list of vertices identified by their index.
 Parameters
renamePoints (bool) – if True, point indices and faces are renamed. If False, vertices are not really deleted and faces indices will stay unchanged (default, faster).

density
(dims=40, 40, 40, bounds=None, radius=None, computeGradient=False, locator=None)[source]¶ Generate a density field from a point cloud. Input can also be a set of 3D coordinates. Output is a
Volume
. The local neighborhood is specified as the radius around each sample position (each voxel). The density is expressed as the number of counts in the radius search. Parameters
dims (int,list) – numer of voxels in x, y and z of the output Volume.
computeGradient (bool) – Turn on/off the generation of the gradient vector, gradient magnitude scalar, and function classification scalar. By default this is off. Note that this will increase execution time and the size of the output. (The names of these point data arrays are: “Gradient”, “Gradient Magnitude”, and “Classification”.)
locator (vtkStaticPointLocator) – can be assigned from a previous call for speed.
See example script:

flag
(text=None, font='Normografo', size=18, angle=0, shadow=False, c='k', bg='w', justify=0, delay=150)[source]¶ Add a flag label which becomes visible when hovering the object with mouse. Can be later disabled by setting flag(False).
See also:
labels()
,vignette()
,caption()
andlegend()
. Parameters
text (str, optional) – text string to be rendered. The default is the filename without extension.
font (str, optional) – name of font to use. The default is “Courier”.
size (int, optional) – size of font. The default is 18. Fonts are: “Arial”, “Courier”, “Times”.
angle (float, optional) – rotation angle. The default is 0.
shadow (bool, optional) – add a shadow to the font. The default is False.
c (str, optional) – color name or index. The default is ‘k’.
bg (str, optional) – color name of the background. The default is ‘w’.
justify (TYPE, optional) – justification code. The default is 0.
delay (float, optional) – pop up delay in milliseconds. The default is 150.
flag_labels.py (flag_labels) –

interpolateDataFrom
(source, radius=None, N=None, kernel='shepard', exclude='Normals', nullStrategy=1, nullValue=0)[source]¶ Interpolate over source to port its data onto the current object using various kernels.
If N (number of closest points to use) is set then radius value is ignored.
 Parameters
kernel (str) – available kernels are [shepard, gaussian, linear]
nullStrategy (int) – specify a strategy to use when encountering a “null” point during the interpolation process. Null points occur when the local neighborhood (of nearby points to interpolate from) is empty. Case 0: an output array is created that marks points as being valid (=1) or null (invalid =0), and the nullValue is set as well Case 1: the output data value(s) are set to the provided nullValue Case 2: simply use the closest point to perform the interpolation.
nullValue (float) – see above.

labels
(content=None, cells=False, scale=None, rotX=0, rotY=0, rotZ=0, ratio=1, precision=None, font='', justify='bottomleft', c='black', alpha=1, italic=False)[source]¶ Generate value or ID labels for mesh cells or points.
See also:
flag()
,vignette()
,caption()
andlegend()
. Parameters
content (list,int,str) – either ‘id’, array name or array number. A array can also be passed (must match the nr. of points or cells).
cells (bool) – generate labels for cells instead of points [False]
scale (float) – absolute size of labels, if left as None it is automatic
rotX (float) – local rotation angle of label in degrees
ratio (int) – skipping ratio, to reduce nr of labels for large meshes
precision (int) – numeric precision of labels
 Example
from vedo import * s = Sphere(alpha=0.2, res=10).lineWidth(0.1) s.computeNormals().clean() point_ids = s.labels(cells=False).c('green') cell_ids = s.labels(cells=True ).c('black') show(s, point_ids, cell_ids)

legend
(txt=None, pos=2, size=0.2, bg=0.96, 0.96, 0.9, font='')[source]¶ Generate legend text.
 Parameters
Default size and position can be modified by setting attributes
Plotter.legendSize
,Plotter.legendBC
andPlotter.legendPos
.

mirror
(axis='x', origin=[0, 0, 0], reset=False)[source]¶ Mirror the mesh along one of the cartesian axes
 Parameters
axis (str) – axis to use for mirroring, must be set to x, y, z or n. Or any combination of those. Adding ‘n’ reverses mesh faces (hence normals).
origin (list) – use this point as the origin of the mirroring transformation.
reset (bool) – if True keep into account the current position of the object, and then reset its internal transformation matrix to Identity.

normals
(cells=False, compute=True)[source]¶ Retrieve vertex normals as a numpy array.
 Params bool cells
if True return cell normals.
 Params bool compute
if True normals are recalculated if not already present. Note that this might modify the number of mesh points.

pointColors
(input_array=None, cmap='rainbow', alpha=1, vmin=None, vmax=None, arrayName='PointScalars', n=256)[source]¶ DEPRECATED: use cmap() instead.

pointGaussNoise
(sigma)[source]¶ Add gaussian noise to point positions.
 Parameters
sigma (float) – sigma is expressed in percent of the diagonal size of mesh.
 Example
from vedo import Sphere Sphere().addGaussNoise(1.0).show()

points
(pts=None, transformed=True, copy=False)[source]¶ Set/Get the vertex coordinates of the mesh. Argument can be an index, a set of indices or a complete new set of points to update the mesh.

polydata
(transformed=True)[source]¶ Returns the
vtkPolyData
object of aMesh
.Note
If
transformed=True
returns a copy of polydata that corresponds to the current mesh’s position in space.

projectOnPlane
(plane='z', point=None, direction=None)[source]¶ Project the mesh on one of the Cartesian planes.
 Parameters
Note
Parameters point and direction are only used if the given plane is an instance of vedo.shapes.Plane. And one of these two params should be left as None to specify the projection type.
Example
>>> s.projectOnPlane(plane='z') # project to zplane >>> plane = Plane(pos=(4, 8, 4), normal=(1, 0, 1), sx=5) >>> s.projectOnPlane(plane=plane) # orthogonal projection >>> s.projectOnPlane(plane=plane, point=(6, 6, 6)) # perspective projection >>> s.projectOnPlane(plane=plane, direction=(1, 2, 1)) # oblique projection

quantize
(binSize)[source]¶ The user should input binSize and all {x,y,z} coordinates will be quantized to that absolute grain size.
Example
from vedo import Paraboloid Paraboloid().lw(0.1).quantize(0.1).show()

shear
(x=0, y=0, z=0)[source]¶ Apply a shear deformation to the Mesh along one of the main axes. The transformation resets position and rotations so it should be applied first.

smoothMLS1D
(f=0.2, radius=None)[source]¶ Smooth mesh or points with a Moving Least Squares variant. The list
mesh.info['variances']
contain the residue calculated for each point. Input mesh’s polydata is modified.

smoothMLS2D
(f=0.2, radius=None)[source]¶ Smooth mesh or points with a Moving Least Squares algorithm variant. The list
mesh.info['variances']
contains the residue calculated for each point.

thinPlateSpline
(sourcePts, targetPts, userFunctions=None, None, sigma=1)[source]¶ Thin Plate Spline transformations describe a nonlinear warp transform defined by a set of source and target landmarks. Any point on the mesh close to a source landmark will be moved to a place close to the corresponding target landmark. The points in between are interpolated smoothly using Bookstein’s Thin Plate Spline algorithm.
Transformation object can be accessed with
mesh.transform
. Parameters
userFunctions – You may supply both the function and its derivative with respect to r.

threshold
(scalars, above=None, below=None, on='points')[source]¶ Extracts cells where scalar value satisfies threshold criterion.
 Parameters

transformWithLandmarks
(sourceLandmarks, targetLandmarks, rigid=False)[source]¶ Trasform mesh orientation and position based on a set of landmarks points. The algorithm finds the best matching of source points to target points in the mean least square sense, in one single step.

vignette
(txt=None, point=None, offset=None, s=None, font='', rounded=True, c=None, alpha=1, lw=2, italic=0)[source]¶ Generate and return a vignette to describe an object. Returns a
Mesh
object. Parameters
txt (str, optional) – Text to display. The default is the filename or the object name.
point (list, optional) – position of the vignette pointer. The default is None.
offset (list, optional) – text offset wrt the application point. The default is None.
s (float, optional) – size of the vignette. The default is None.
font (str, optional) – text font. The default is “”.
rounded (bool, optional) – draw a rounded or squared box around the text. The default is True.
c (list, optional) – text and box color. The default is None.
alpha (float, optional) – transparency of text and box. The default is 1.
lw (float, optional) – line with of box frame. The default is 2.
italic (float, optional) – italicness of text. The default is 0.

warpByVectors
(vects, factor=1, useCells=False)[source]¶ Modify point coordinates by moving points along vector times the scale factor. Useful for showing flow profiles or mechanical deformation. Input can be an existing point/cell data array or a new array, in this case it will be named ‘WarpVectors’.
 Parameters
Example
from vedo import * b = load(datadir+'dodecahedron.vtk').computeNormals() b.warpByVectors("Normals", factor=0.15).show()

warpToPoint
(point, factor=0.1, absolute=True)[source]¶ Modify the mesh coordinates by moving the vertices towards a specified point.
 Parameters
 Example
from vedo import * s = Cylinder(height=3).wireframe() pt = [4,0,0] w = s.clone().warpToPoint(pt, factor=0.5).wireframe(False) show(w,s, Point(pt), axes=1)
cluster¶
connectedPoints¶

vedo.pointcloud.
connectedPoints
(mesh, radius, mode=0, regions=(), vrange=0, 1, seeds=(), angle=0)[source]¶ Extracts and/or segments points from a point cloud based on geometric distance measures (e.g., proximity, normal alignments, etc.) and optional measures such as scalar range. The default operation is to segment the points into “connected” regions where the connection is determined by an appropriate distance measure. Each region is given a region id.
Optionally, the filter can output the largest connected region of points; a particular region (via id specification); those regions that are seeded using a list of input point ids; or the region of points closest to a specified position.
The key parameter of this filter is the radius defining a sphere around each point which defines a local neighborhood: any other points in the local neighborhood are assumed connected to the point. Note that the radius is defined in absolute terms.
Other parameters are used to further qualify what it means to be a neighboring point. For example, scalar range and/or point normals can be used to further constrain the neighborhood. Also the extraction mode defines how the filter operates. By default, all regions are extracted but it is possible to extract particular regions; the region closest to a seed point; seeded regions; or the largest region found while processing. By default, all regions are extracted.
On output, all points are labeled with a region number. However note that the number of input and output points may not be the same: if not extracting all regions then the output size may be less than the input size.
 Parameters
radius (float) – radius variable specifying a local sphere used to define local point neighborhood
mode (int) –
0, Extract all regions
1, Extract point seeded regions
2, Extract largest region
3, Test specified regions
4, Extract all regions with scalar connectivity
5, Extract point seeded regions
regions (list) – a list of nonnegative regions id to extract
vrange (list) – scalar range to use to extract points based on scalar connectivity
seeds (list) – a list of nonnegative point seed ids
angle (list) – points are connected if the angle between their normals is within this angle threshold (expressed in degrees).
delaunay2D¶
densifyCloud¶

vedo.pointcloud.
densifyCloud
(mesh, targetDistance, closestN=6, radius=0, maxIter=None, maxN=None)[source]¶ Add new points to an input point cloud. The new points are created in such a way that all points in any local neighborhood are within a target distance of one another.
The algorithm works as follows. For each input point, the distance to all points in its neighborhood is computed. If any of its neighbors is further than the target distance, the edge connecting the point and its neighbor is bisected and a new point is inserted at the bisection point. A single pass is completed once all the input points are visited. Then the process repeats to the limit of the maximum number of iterations.
Note
Points will be created in an iterative fashion until all points in their local neighborhood are the target distance apart or less. Note that the process may terminate early due to the limit on the maximum number of iterations. By default the target distance is set to 0.5. Note that the TargetDistance should be less than the Radius or nothing will change on output.
Warning
This class can generate a lot of points very quickly. The maximum number of iterations is by default set to =1.0 for this reason. Increase the number of iterations very carefully. Also, maxN can be set to limit the explosion of points. It is also recommended that a N closest neighborhood is used.
fitLine¶
fitPlane¶

vedo.pointcloud.
fitPlane
(points)[source]¶ Fits a plane to a set of points.
Extra info is stored in
Plane.normal
,Plane.center
,Plane.variance
.Hint
Example: fitplanes.py
fitSphere¶
pcaEllipsoid¶

vedo.pointcloud.
pcaEllipsoid
(points, pvalue=0.95)[source]¶ Show the oriented PCA ellipsoid that contains fraction pvalue of points.
 Parameters
pvalue (float) – ellypsoid will contain the specified fraction of points.
Extra can be calculated with
mesh.asphericity()
,mesh.asphericity_error()
(asphericity is equal to 0 for a perfect sphere).Axes can be accessed in
mesh.va
,mesh.vb
,mesh.vc
. End point of the axes are stored inmesh.axis1
,mesh.axis12
andmesh.axis3
.
pointCloudFrom¶
recoSurface¶

vedo.pointcloud.
recoSurface
(pts, dims=250, 250, 250, radius=None, sampleSize=None, holeFilling=True, bounds=(), pad=0.1)[source]¶ Surface reconstruction from a scattered cloud of points.
 Parameters
dims (int) – number of voxels in x, y and z to control precision.
radius (float) – radius of influence of each point. Smaller values generally improve performance markedly. Note that after the signed distance function is computed, any voxel taking on the value >= radius is presumed to be “unseen” or uninitialized.
sampleSize (int) – if normals are not present they will be calculated using this sample size per point.
holeFilling (bool) – enables hole filling, this generates separating surfaces between the empty and unseen portions of the volume.
bounds (list) – region in space in which to perform the sampling in format (xmin,xmax, ymin,ymax, zim, zmax)
pad (float) – increase by this fraction the bounding box
removeOutliers¶
smoothMLS3D¶

vedo.pointcloud.
smoothMLS3D
(meshs, neighbours=10)[source]¶ A time sequence of point clouds (Mesh) is being smoothed in 4D (3D + time) using a MLS (Moving Least Squares) algorithm variant. The time associated to an mesh must be specified in advance with
mesh.time()
method. Data itself can suggest a meaningful time separation based on the spatial distribution of points. Parameters
neighbours (int) – fixed nr. of neighbours in spacetime to take into account in the fit.
visiblePoints¶

vedo.pointcloud.
visiblePoints
(mesh, area=(), tol=None, invert=False)[source]¶ Extract points based on whether they are visible or not. Visibility is determined by accessing the zbuffer of a rendering window. The position of each input point is converted into display coordinates, and then the zvalue at that point is obtained. If within the userspecified tolerance, the point is considered visible. Associated data attributes are passed to the output as well.
This filter also allows you to specify a rectangular window in display (pixel) coordinates in which the visible points must lie.
 Parameters
 Example
from vedo import Ellipsoid, show, visiblePoints s = Ellipsoid().rotateY(30) #Camera options: pos, focalPoint, viewup, distance, # clippingRange, parallelScale, thickness, viewAngle camopts = dict(pos=(0,0,25), focalPoint=(0,0,0)) show(s, camera=camopts, offscreen=True) m = visiblePoints(s) #print('visible pts:', m.points()) # numpy array show(m, new=True, axes=1) # optionally draw result on a new window