analysis

Defines methods useful to analyse 3D meshes.

actor2Volume

vtkplotter.analysis.actor2Volume(actor, spacing=(1, 1, 1))[source]

Convert a mesh it into a Volume where the foreground (exterior) voxels value is 1 and the background (interior) voxels value is 0. Internally the vtkPolyDataToImageStencil class is used.

mesh2volume.py mesh2volume.py

alignICP

vtkplotter.analysis.alignICP(source, target, iters=100, rigid=False)[source]

Return a copy of source actor which is aligned to target actor 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 least-square sense).

alignLandmarks

vtkplotter.analysis.alignLandmarks(source, target, rigid=False)[source]

Find best matching of source points towards target in the mean least square sense, in one single step.

alignProcrustes

vtkplotter.analysis.alignProcrustes(sources, rigid=False)[source]

Return an Assembly of aligned source actors with the Procrustes algorithm. The output Assembly is normalized in size.

Procrustes algorithm takes N set of points and aligns them in a least-squares sense to their mutual mean. The algorithm is iterated until convergence, as the mean must be recomputed after each alignment.

Parameters:rigid (bool) – if True scaling is disabled.

align3.py align3.py

booleanOperation

vtkplotter.analysis.booleanOperation(actor1, operation, actor2)[source]

Volumetric union, intersection and subtraction of surfaces.

Parameters:operation (str) – allowed operations: 'plus', 'intersect', 'minus'.

boolean.py boolean.py

cluster

vtkplotter.analysis.cluster(points, radius)[source]

Clustering of points in space.

radius is the radius of local search. Individual subsets can be accessed through actor.clusters.

clustering.py clustering.py

computeNormalsWithPCA

vtkplotter.analysis.computeNormalsWithPCA(actor, n=20, orientationPoint=None, negate=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.
  • negate (bool) – flip all normals

connectedPoints

vtkplotter.analysis.connectedPoints(actor, 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 non-negative regions id to extract
  • vrange (list) – scalar range to use to extract points based on scalar connectivity
  • seeds (list) – a list of non-negative point seed ids
  • angle (list) – points are connected if the angle between their normals is within this angle threshold (expressed in degrees).

convexHull

vtkplotter.analysis.convexHull(actor_or_list, alphaConstant=0)[source]

Create a 2D/3D Delaunay triangulation of input points.

Parameters:
  • actor_or_list – can be either an Actor or a list of 3D points.
  • alphaConstant (float) – For a non-zero alpha value, only verts, edges, faces, or tetra contained within the circumsphere (of radius alpha) will be output. Otherwise, only tetrahedra will be output.

convexHull.py convexHull.py

delaunay2D

vtkplotter.analysis.delaunay2D(plist, mode='xy', tol=None)[source]

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.py delaunay2d.py

delaunay3D

vtkplotter.analysis.delaunay3D(dataset, alpha=0, tol=None, boundary=True)[source]

Create 3D Delaunay triangulation of input points.

densifyCloud

vtkplotter.analysis.densifyCloud(actor, targetDistance, closestN=6, radius=0, maxIter=None, maxN=None)[source]

Adds 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.

dilateVolume

vtkplotter.analysis.dilateVolume(vol, neighbours=(2, 2, 2))[source]

Replace a voxel with the maximum over an ellipsoidal neighborhood of voxels. If neighbours of an axis is 1, no processing is done on that axis.

See example script: erode_dilate.py

erodeVolume

vtkplotter.analysis.erodeVolume(vol, neighbours=(2, 2, 2))[source]

Replace a voxel with the minimum over an ellipsoidal neighborhood of voxels. If neighbours of an axis is 1, no processing is done on that axis.

See example script: erode_dilate.py

euclideanDistanceVolume

vtkplotter.analysis.euclideanDistanceVolume(vol, anisotropy=False, maxDistance=None)[source]

Implementation of the Euclidean DT (Distance Transform) using Saito’s algorithm. The distance map produced contains the square of the Euclidean distance values. The algorithm has a O(n^(D+1)) complexity over nxnx…xn images in D dimensions.

Check out also: https://en.wikipedia.org/wiki/Distance_transform

Parameters:
  • anisotropy (bool) – used to define whether Spacing should be used in the computation of the distances.
  • maxDistance (float) – any distance bigger than maxDistance will not be computed but set to this specified value instead.

See example script: euclDist.py

extractLargestRegion

vtkplotter.analysis.extractLargestRegion(actor)[source]

Keep only the largest connected part of a mesh and discard all the smaller pieces.

extractSurface

vtkplotter.analysis.extractSurface(volume, radius=0.5)[source]

Generate the zero-crossing isosurface from truncated signed distance volume in input. Output is an Actor object.

extrude

vtkplotter.analysis.extrude(actor, zshift=1, rotation=0, dR=0, cap=True, res=1)[source]

Sweep a polygonal data creating a “skirt” from free edges and lines, and lines from vertices. The input dataset is swept around the z-axis to create new polygonal primitives. For example, sweeping a line results in a cylindrical shell, and sweeping a circle creates a torus.

You can control whether the sweep of a 2D object (i.e., polygon or triangle strip) is capped with the generating geometry. Also, you can control the angle of rotation, and whether translation along the z-axis is performed along with the rotation. (Translation is useful for creating “springs”). You also can adjust the radius of the generating geometry using the “dR” keyword.

The skirt is generated by locating certain topological features. Free edges (edges of polygons or triangle strips only used by one polygon or triangle strips) generate surfaces. This is true also of lines or polylines. Vertices generate lines.

This filter can be used to model axisymmetric objects like cylinders, bottles, and wine glasses; or translational/rotational symmetric objects like springs or corkscrews.

Warning

Some polygonal objects have no free edges (e.g., sphere). When swept, this will result in two separate surfaces if capping is on, or no surface if capping is off.

extrude.py extrude.py

fitLine

vtkplotter.analysis.fitLine(points)[source]

Fits a line through points.

Extra info is stored in actor.info['slope'], actor.info['center'], actor.info['variances'].

fitline.py fitline.py

fitPlane

vtkplotter.analysis.fitPlane(points)[source]

Fits a plane to a set of points.

Extra info is stored in actor.info['normal'], actor.info['center'], actor.info['variance'].

Hint

Example: fitplanes.py

fitSphere

vtkplotter.analysis.fitSphere(coords)[source]

Fits a sphere to a set of points.

Extra info is stored in actor.info['radius'], actor.info['center'], actor.info['residue'].

frequencyPassFilter

vtkplotter.analysis.frequencyPassFilter(volume, lowcutoff=None, highcutoff=None, order=1)[source]

Low-pass and high-pass filtering become trivial in the frequency domain. A portion of the pixels/voxels are simply masked or attenuated. This function applies a high pass Butterworth filter that attenuates the frequency domain image with the function

G_Of_Omega

The gradual attenuation of the filter is important. A simple high-pass filter would simply mask a set of pixels in the frequency domain, but the abrupt transition would cause a ringing effect in the spatial domain.

Parameters:
  • lowcutoff (list) – the cutoff frequencies for x, y and z
  • highcutoff (list) – the cutoff frequencies for x, y and z
  • order (int) – order determines sharpness of the cutoff curve

Check out also this example:

idealpass

geodesic

vtkplotter.analysis.geodesic(actor, start, end)[source]

Dijkstra algorithm to compute the graph geodesic. Takes as input a polygonal mesh and performs a single source shortest path calculation.

Parameters:
  • start (int, list) – start vertex index or close point [x,y,z]
  • end – end vertex index or close point [x,y,z]

geodesic.py geodesic.py

implicitModeller

vtkplotter.analysis.implicitModeller(actor, distance=0.05, res=(110, 40, 20), bounds=(), maxdist=None, outer=True)[source]

Finds the surface at the specified distance from the input one

interpolateToStructuredGrid

vtkplotter.analysis.interpolateToStructuredGrid(actor, kernel=None, radius=None, bounds=None, nullValue=None, dims=None)[source]

Generate a volumetric dataset (vtkStructuredData) by interpolating a scalar or vector field which is only known on a scattered set of points or mesh. Available interpolation kernels are: shepard, gaussian, voronoi, linear.

Parameters:
  • kernel (str) – interpolation kernel type [shepard]
  • radius (float) – radius of the local search
  • bounds (list) – bounding box of the output vtkStructuredGrid object
  • dims (list) – dimensions of the output vtkStructuredGrid object
  • nullValue (float) – value to be assigned to invalid points

interpolateToVolume

vtkplotter.analysis.interpolateToVolume(actor, kernel='shepard', radius=None, bounds=None, nullValue=None, dims=(20, 20, 20))[source]

Generate a Volume by interpolating a scalar or vector field which is only known on a scattered set of points or mesh. Available interpolation kernels are: shepard, gaussian, voronoi, linear.

Parameters:
  • kernel (str) – interpolation kernel type [shepard]
  • radius (float) – radius of the local search
  • bounds (list) – bounding box of the output Volume object
  • dims (list) – dimensions of the output Volume object
  • nullValue (float) – value to be assigned to invalid points

interpolateVolume.py interpolateVolume.py

meshQuality

vtkplotter.analysis.meshQuality(actor, measure=6)[source]

Calculate functions of quality of the elements of a triangular mesh. See class vtkMeshQuality for explaination.

Parameters:measure (int) –

type of estimator

  • EDGE_RATIO, 0
  • ASPECT_RATIO, 1
  • RADIUS_RATIO, 2
  • ASPECT_FROBENIUS, 3
  • MED_ASPECT_FROBENIUS, 4
  • MAX_ASPECT_FROBENIUS, 5
  • MIN_ANGLE, 6
  • COLLAPSE_RATIO, 7
  • MAX_ANGLE, 8
  • CONDITION, 9
  • SCALED_JACOBIAN, 10
  • SHEAR, 11
  • RELATIVE_SIZE_SQUARED, 12
  • SHAPE, 13
  • SHAPE_AND_SIZE, 14
  • DISTORTION, 15
  • MAX_EDGE_RATIO, 16
  • SKEW, 17
  • TAPER, 18
  • VOLUME, 19
  • STRETCH, 20
  • DIAGONAL, 21
  • DIMENSION, 22
  • ODDY, 23
  • SHEAR_AND_SIZE, 24
  • JACOBIAN, 25
  • WARPAGE, 26
  • ASPECT_GAMMA, 27
  • AREA, 28
  • ASPECT_BETA, 29

meshquality.py meshquality.py

normalLines

vtkplotter.analysis.normalLines(actor, ratio=1, atCells=True)[source]

Build an Actor made of the normals at cells shown as lines.

if atCells is False normals are shown at vertices.

pcaEllipsoid

vtkplotter.analysis.pcaEllipsoid(points, pvalue=0.95, pcaAxes=False)[source]

Show the oriented PCA ellipsoid that contains fraction pvalue of points.

Parameters:
  • pvalue (float) – ellypsoid will contain the specified fraction of points.
  • pcaAxes (bool) – if True, show the 3 PCA semi axes.

Extra info is stored in actor.info['sphericity'], actor.info['va'], actor.info['vb'], actor.info['vc'] (sphericity is equal to 0 for a perfect sphere).

Hint

Examples: pca.py cell_main.py

pca.py cell_main.py

pointDensity

vtkplotter.analysis.pointDensity(actor, dims=(30, 30, 30), bounds=None, radius=None, computeGradient=False)[source]

Generate a density field from a point cloud. Output is a Volume. The local neighborhood is specified as a radius around each sample position (each voxel). The density is normalized to the upper value of the scalar range.

See example script: pointDensity.py

pointSampler

vtkplotter.analysis.pointSampler(actor, distance=None)[source]

Algorithm to generate points the specified distance apart.

probeLine

vtkplotter.analysis.probeLine(vol, p1, p2, res=100)[source]

Takes a Volume and probes its scalars along a line defined by 2 points p1 and p2.

probeLine.py probeLine.py

probePlane

vtkplotter.analysis.probePlane(vol, origin=(0, 0, 0), normal=(1, 0, 0))[source]

Takes a Volume and probes its scalars on a plane.

probePlane.py probePlane.py

probePoints

vtkplotter.analysis.probePoints(vol, pts)[source]

Takes a Volume and probes its scalars at the specified points in space.

Note that a mask is also output with valid/invalid points which can be accessed with actor.scalars().

projectSphereFilter

vtkplotter.analysis.projectSphereFilter(actor)[source]

Project a spherical-like object onto a plane.

projectsphere.py projectsphere.py

recoSurface

vtkplotter.analysis.recoSurface(points, bins=256)[source]

Surface reconstruction from a scattered cloud of points.

Parameters:bins (int) – number of voxels in x, y and z.

recosurface.py recosurface.py

removeOutliers

vtkplotter.analysis.removeOutliers(points, radius)[source]

Remove outliers from a cloud of points within the specified radius search.

clustering.py clustering.py

signedDistanceFromPointCloud

vtkplotter.analysis.signedDistanceFromPointCloud(actor, maxradius=None, bounds=None, dims=(20, 20, 20))[source]

Compute signed distances over a volume from an input point cloud. The output is a Volume object whose voxels contains the signed distance from the cloud.

Parameters:
  • maxradius (float) – how far out to propagate distance calculation
  • bounds (list) – volume bounds.
  • dims (list) – dimensions (nr. of voxels) of the output volume.

smoothMLS1D

vtkplotter.analysis.smoothMLS1D(actor, f=0.2, radius=None, showNLines=0)[source]

Smooth actor or points with a Moving Least Squares variant. The list actor.info['variances'] contain the residue calculated for each point. Input actor’s polydata is modified.

Parameters:
  • f (float) – smoothing factor - typical range is [0,2].
  • showNLines (int) – build an actor showing the fitting line for N random points.

smoothMLS2D

vtkplotter.analysis.smoothMLS2D(actor, f=0.2, radius=None, decimate=1, showNPlanes=0)[source]

Smooth actor or points with a Moving Least Squares algorithm variant. The list actor.info['variances'] contains the residue calculated for each point.

Parameters:
  • f (float) – smoothing factor - typical range is [0,2]. Ignored if radius is set.
  • radius (float) – radius search in absolute units. If set then f is ignored.
  • decimate (int) – decimation integer factor.
  • showNPlanes – build a demo actor showing the fitting plane for N random points.

smoothMLS3D

vtkplotter.analysis.smoothMLS3D(actors, neighbours=10)[source]

A time sequence of actors is being smoothed in 4D (3D + time) using a MLS (Moving Least Squares) algorithm variant. The time associated to an actor must be specified in advance with actor.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 space-time to take into account in the fit.

moving_least_squares3D.py moving_least_squares3D.py

splitByConnectivity

vtkplotter.analysis.splitByConnectivity(actor, maxdepth=1000)[source]

Split a mesh by connectivity and order the pieces by increasing area.

Parameters:maxdepth (int) – only consider this number of mesh parts.

splitmesh.py splitmesh.py

streamLines

vtkplotter.analysis.streamLines(domain, probe, integrator='rk4', direction='forward', initialStepSize=None, maxPropagation=None, maxSteps=10000, stepLength=None, extrapolateToBoundingBox={}, surfaceConstrain=False, computeVorticity=True, ribbons=None, tubes={}, scalarRange=None)[source]

Integrate a vector field to generate streamlines.

The integration is performed using a specified integrator (Runge-Kutta). The length of a streamline is governed by specifying a maximum value either in physical arc length or in (local) cell length. Otherwise, the integration terminates upon exiting the field domain.

Parameters:
  • domain – the vtk object that contains the vector field
  • probe (Actor) – the Actor that probes the domain. Its coordinates will be the seeds for the streamlines
  • integrator (str) – Runge-Kutta integrator, either ‘rk2’, ‘rk4’ of ‘rk45’
  • initialStepSize (float) – initial step size of integration
  • maxPropagation (float) – maximum physical length of the streamline
  • maxSteps (int) – maximum nr of steps allowed
  • stepLength (float) – length of step integration.
  • extrapolateToBoundingBox (dict) –

    Vectors defined on a surface are extrapolated to the entire volume defined by its bounding box

    • kernel, (str) - interpolation kernel type [shepard]
    • radius (float)- radius of the local search
    • bounds, (list) - bounding box of the output Volume
    • dims, (list) - dimensions of the output Volume object
    • nullValue, (float) - value to be assigned to invalid points
  • surfaceConstrain (bool) – force streamlines to be computed on a surface
  • computeVorticity (bool) – Turn on/off vorticity computation at streamline points (necessary for generating proper stream-ribbons)
  • ribbons (int) – render lines as ribbons by joining them. An integer value represent the ratio of joining (e.g.: ribbons=2 groups lines 2 by 2)
  • tubes (dict) –

    dictionary containing the parameters for the tube representation:

    • ratio, (int) - draws tube as longitudinal stripes
    • res, (int) - tube resolution (nr. of sides, 24 by default)
    • maxRadiusFactor (float) - max tube radius as a multiple of the min radius
    • varyRadius, (int) - radius varies based on the scalar or vector magnitude:
      • 0 - do not vary radius
      • 1 - vary radius by scalar
      • 2 - vary radius by vector
      • 3 - vary radius by absolute value of scalar
  • scalarRange (list) – specify the scalar range for coloring

surfaceIntersection

vtkplotter.analysis.surfaceIntersection(actor1, actor2, tol=1e-06)[source]

Intersect 2 surfaces and return a line actor.

thinPlateSpline

vtkplotter.analysis.thinPlateSpline(actor, 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 retrieved with actor.getTransform().

Parameters:userFunctions – You may supply both the function and its derivative with respect to r.

volumeCorrelation

vtkplotter.analysis.volumeCorrelation(vol1, vol2, dim=2)[source]

Find the correlation between two volumetric data sets. Keyword dim determines whether the correlation will be 3D, 2D or 1D. The default is a 2D Correlation. The output size will match the size of the first input. The second input is considered the correlation kernel.

volumeFromMesh

vtkplotter.analysis.volumeFromMesh(actor, bounds=None, dims=(20, 20, 20), signed=True, negate=False)[source]

Compute signed distances over a volume from an input mesh. The output is a Volume object whose voxels contains the signed distance from the mesh.

Parameters:
  • bounds (list) – bounds of the output volume.
  • dims (list) – dimensions (nr. of voxels) of the output volume.

See example script: volumeFromMesh.py

volumeOperation

vtkplotter.analysis.volumeOperation(volume1, operation, volume2=None)[source]

Perform operations with Volume objects.

volume2 can be a constant value.

Possible operations are: +, -, /, 1/x, sin, cos, exp, log, abs, **2, sqrt, min, max, atan, atan2, median, mag, dot, gradient, divergence, laplacian.

volumeOperations.py volumeOperations.py

volumeToPoints

vtkplotter.analysis.volumeToPoints(vol)[source]

Extract all image voxels as points. This function takes an input Volume and creates an Actor that contains the points and the point attributes.

See example script: vol2points.py

voronoi3D

vtkplotter.analysis.voronoi3D(nuclei, bbfactor=1, tol=None)[source]

Generate 3D Voronio tasselization with the Voro++ package.

voronoi3d.py voronoi3d.py

warpMeshToPoint

vtkplotter.analysis.warpMeshToPoint(actor, point, factor=0.1, absolute=True)[source]

Modify the mesh coordinates by moving the vertices towards a specified point.

Parameters:
  • factor (float) – value to scale displacement.
  • point (list) – the position to warp towards.
  • absolute (bool) – turning on causes scale factor of the new position to be one unit away from point.
Example:
from vtkplotter import *
s = Cylinder(height=3).wireframe(1)
pt = [4,0,0]
w = warpMeshToPoint(s, pt, factor=0.5).wireframe(0)
show(w,s, Point(pt), axes=1, bg='w')

warpto