Exemplo n.º 1
0
# Generate a time sequence of 3D shapes (from a sphere to a tetrahedron)
# as noisy cloud points, and smooth it with Moving Least Squares (smoothMLS3D).
# This make a simultaneus fit in 4D (space+time).
# smoothMLS3D method returns a vtkActor where points are color coded
# in bins of fitted time.
# Data itself can suggest a meaningful time separation based on the spatial
# distribution of points.
# The nr neighbours in the local 4D fitting must be specified.
#
import numpy as np
from vtkplotter import Plotter, sphere, smoothMLS3D

vp = Plotter(N=2, axes=0)

# generate uniform points on sphere (tol separates points by 2% of actor size)
cc = sphere(res=200).clean(tol=0.02).coordinates()

a, b, noise = .2, .4, .1  # some random warping paramenters, and noise factor
for i in range(5):  # generate a time sequence of 5 shapes
    cs = cc + a * i * cc**2 + b * i * cc**3  # warp sphere in weird ways
    # set absolute time of points actor, and add 1% noise on positions
    vp.points(cs, c=i, alpha=0.5).gaussNoise(1.0).time(0.2 * i)
    vp.show(at=0, zoom=1.4)  # show input clouds as func(time)

asse = smoothMLS3D(vp.actors, neighbours=50)

vp.addScalarBar3D(asse, at=1, pos=(-2, 0, -1))  # color indicates fitted time
vp.show(asse, at=1, zoom=1.4, axes=4, interactive=1)
Exemplo n.º 2
0
# Use scipy to interpolate the value of a scalar known on a set of points
# on a new set of points where the scalar is not defined.
# Two interpolation methods: Radial Basis Function, Nearest point
#
from scipy.interpolate import Rbf, NearestNDInterpolator as Near
import numpy as np
# np.random.seed(0)

# a small set of points for which the scalar is given
x, y, z = np.random.rand(3, 20)

scals = z  # scalar value is just z component

# build the interpolator
itr = Rbf(x, y, z, scals)  # Radial Basis Function interpolator
#itr = Near(list(zip(x,y,z)), scals) # Nearest-neighbour interpolator

# generate a new set of points
t = np.linspace(0, 7, 100)
xi, yi, zi = [np.sin(t) / 10 + .5, np.cos(t) / 5 + .5, (t - 1) / 5]  # an helix

# interpolate scalar values on the new set
scalsi = itr(xi, yi, zi)

from vtkplotter import Plotter
vp = Plotter(verbose=0)
vp.points([x, y, z], r=10, alpha=0.5).pointColors(scals)
vp.points([xi, yi, zi]).pointColors(scalsi)
vp.show(viewup='z')
Exemplo n.º 3
0
# by default use their file names as legend entries.
# No need to use any variables, as actors are stored internally in vp.actors:
vp = Plotter(title='3 shapes')
vp.load('data/250.vtk', c=(1, 0.4, 0), alpha=.3)
vp.load('data/270.vtk', c=(1, 0.6, 0), alpha=.3)
vp.load('data/290.vtk', c=(1, 0.8, 0), alpha=.3)
print('Loaded vtkActors: ', len(vp.actors))
vp.show()

#########################################################################################
# Draw a spline through a set of points:
vp = Plotter(title='Example of splines through 8 random points')

pts = [(u(0, 2), u(0, 2), u(0, 2) + i)
       for i in range(8)]  # build python list of points
vp.points(pts, legend='random points')  # create the vtkActor

for i in range(10):
    vp.spline(pts,
              smooth=i / 10,
              degree=2,
              c=i,
              legend='smoothing ' + str(i / 10))
vp.show()

#########################################################################################
# Draw a cloud of points each one with a different color
# which depends on the point position itself
vp = Plotter(title='color points')

rgb = [(u(0, 255), u(0, 255), u(0, 255)) for i in range(5000)]
Exemplo n.º 4
0
from vtkplotter.actors import Volume

bins = 25  # nr. of voxels per axis
npts = 60  # nr. of points of known scalar value

img = vtk.vtkImageData()
img.SetDimensions(bins, bins, bins)  # range is [0, bins-1]
img.AllocateScalars(vtk.VTK_FLOAT, 1)

coords = np.random.rand(npts, 3)  # range is [0, 1]
scals = np.abs(coords[:, 2])  # let the scalar be the z of point itself
fact = 1. / (bins - 1)  # conversion factor btw the 2 ranges

vp = Plotter(verbose=0)
vp.ztitle = 'z == scalar value'
cloud = vp.points(coords)

# fill the vtkImageData object
pb = ProgressBar(0, bins, c=4)
for iz in pb.range():
    pb.print()
    for iy in range(bins):
        for ix in range(bins):

            pt = vector(ix, iy, iz) * fact
            closestPointsIDs = cloud.closestPoint(pt, N=5, returnIds=True)

            num, den = 0, 0
            for i in closestPointsIDs:  # work out RBF manually on N points
                invdist = 1 / (mag2(coords[i] - pt) + 1e-06)
                num += scals[i] * invdist
Exemplo n.º 5
0
# In this example we fit a plane to regions of a surface defined by
# N points that are closest to a given point of the surface.
# For some of these point we show the fitting plane.
# Blue points are the N points used for fitting.
# Green histogram is the distribution of residuals from the fitting.
# Both plane center and normal can be accessed from the
# attribute actor.center and actor.normal (direction is arbitrary).
#
from __future__ import division, print_function
from vtkplotter import Plotter
from vtkplotter.analysis import fitPlane

vp = Plotter(verbose=0, axes=0)

s = vp.load('data/shapes/cow.vtk').alpha(0.3).subdivide()  # remesh

variances = []
for i, p in enumerate(s.coordinates()):
    if i % 100: continue  # skip most points
    pts = s.closestPoint(p, N=12)  # find the N closest points to p
    plane = fitPlane(pts, bc='r', alpha=0.3)  # find the fitting plane
    vp.actors.append(plane)
    vp.points(pts)  # blue points
    vp.point(p, c='red 0.2')  # mark in red the current point
    vp.arrow(plane.center, plane.center + plane.normal / 15, c='g')
    variances.append(plane.variance)

vp.histogram(variances, title='variance', c='g')
vp.show()
from vtkplotter import Plotter, arange, sin, cos, sqrt
from vtkplotter.analysis import smoothMLS1D
import numpy as np

N = 9  # nr. of iterations

# build some initial cloud of noisy points along a line
#pts = [ (sin(6*x), sin(2*x)/(x+1), cos(9*x)) for x in arange(0,1, .001)]
#pts = [ (0, sin(x), cos(x)) for x in arange(0,6, .002) ]
pts = [(sqrt(x), sin(x), x / 10) for x in arange(0, 16, .01)]

pts += np.random.randn(len(pts), 3) / 10  # add noise
np.random.shuffle(pts)  # make sure points are not ordered

vp = Plotter(N=N, axes=5)
a = vp.points(pts)
vp.show(a, at=0, legend='cloud')

for i in range(1, N):
    a = a.clone().color(i)
    smoothMLS1D(a, f=0.2)

    # at last iteration make sure points are separated by tol
    if i == N - 1:
        a.clean(tol=.01)

    print('iteration', i, '#points:', len(a.coordinates()))
    vp.show(a, at=i, legend='iter #' + str(i))

vp.show(interactive=1)
Exemplo n.º 7
0
# Retrieve the vtk transformation matrix.
#
from __future__ import division, print_function
from random import uniform as u
from vtkplotter import Plotter
from vtkplotter.analysis import align

vp = Plotter(shape=[1,2], verbose=0, axes=2)

N1 = 15  # number of points of first set
N2 = 10  # number of points of second set
x = 1.   # add some randomness

pts1 = [ (u(0,x), u(0,x), u(0,x)+i) for i in range(N1) ]
pts2 = [ (u(0,x)+3, u(0,x)+i/2+2, u(0,x)+i+1) for i in range(N2) ]

act1 = vp.points(pts1, c='b', legend='source')
act2 = vp.points(pts2, c='r', legend='target')

vp.show(at=0)

# find best alignment between the 2 sets of points
alpts1 = align(act1, act2).coordinates()

for i in range(N1): #draw arrows to see where points end up
    vp.arrow(pts1[i], alpts1[i], c='k', s=0.007, alpha=.1) 

vp.show(at=1, interactive=1)


Exemplo n.º 8
0
#
from __future__ import division, print_function
import numpy as np
from vtkplotter import Plotter, fitLine, fitPlane

# declare the class instance
vp = Plotter(verbose=0, title='linear fitting')

# draw 500 fit lines superimposed and very transparent
for i in range(500): 
    
    x = np.linspace(-2, 5, 20) # generate each time 20 points
    y = np.linspace( 1, 9, 20)
    z = np.linspace(-5, 3, 20)
    data = np.array(list(zip(x,y,z)))
    data+= np.random.normal(size=data.shape)*0.8 # add gauss noise
    
    vp.add( fitLine(data, lw=4, alpha=0.03) ) # fit a line

# 'data' still contains the last iteration points
vp.points(data, r=10, c='red', legend='random points')

# the first fitted slope direction is stored 
# in actor.info['slope] and actor.info['normal]
print('Line Fit slope = ', vp.actors[0].info['slope']) 

plane = vp.add( fitPlane(data, legend='fitting plane') ) # fit a plane
print('Plan Fit normal=', plane.info['normal']) 

vp.show()
Exemplo n.º 9
0
    vp.actors = [] # clean up the list of actors

    for colony in colonies:

        newcells = []    
        for cell in colony.cells:

            if cell.dieAt(t): continue
            if cell.divideAt(t): 
                newc = cell.split() # make daughter cell
                vp.add(line(cell.pos, newc.pos, c='k', lw=3, alpha=.5))
                newcells.append(newc)
            newcells.append(cell)
        colony.cells = newcells

        pts = [c.pos for c in newcells] # draw all points at once
        vp.points(pts, c=colony.color, r= 5, alpha=.80) # nucleus
        vp.points(pts, c=colony.color, r=15, alpha=.05) # halo
        msg += str(len(colony.cells)) + ','

    pb.print(msg+str(int(t)))
    vp.show(resetcam=0)

# draw the oriented ellipsoid that contains 50% of the cells
for colony in colonies: 
    pts = [c.pos for c in colony.cells]
    a = pcaEllipsoid(pts, pvalue=0.5, c=colony.color, pcaAxes=0, alpha=.3,
            		 legend='1/rate='+str(colony.cells[0].tdiv)+'h')
    vp.add(a)
vp.show(resetcam=0, interactive=1)
Exemplo n.º 10
0

vp = Plotter(shape=[2, 2], verbose=0, axes=3, interactive=0)

shape1 = sphere(alpha=0.2)
shape2 = vp.load('data/shapes/icosahedron.vtk').normalize().lineWidth(1)

agrid1, actorpts1 = makegrid(shape1, N)
vp.show(at=0, actors=[shape1, actorpts1])

agrid2, actorpts2 = makegrid(shape2, N)
vp.show(at=1, actors=[shape2, actorpts2])
vp.camera.Zoom(1.2)
vp.interactive = False

clm1 = pyshtools.SHGrid.from_array(agrid1).expand()
clm2 = pyshtools.SHGrid.from_array(agrid2).expand()
# clm1.plot_spectrum2d() # plot the value of the sph harm. coefficients
# clm2.plot_spectrum2d()

for t in arange(0, 1, 0.005):
    act21 = vp.points(morph(clm2, clm1, t, lmax), c='r', r=4)
    act12 = vp.points(morph(clm1, clm2, t, lmax), c='g', r=4)
    vp.show(at=2,
            actors=act21,
            resetcam=0,
            legend='time: ' + str(int(t * 100)))
    vp.show(at=3, actors=act12)
    vp.camera.Azimuth(2)

vp.show(interactive=1)
Exemplo n.º 11
0
from __future__ import division, print_function
from vtkplotter import Plotter, mag
import numpy as np

dt = 0.002
y = [25, -10, -7]  # Starting point (initial condition)
pts, cols = [], []

scene = Plotter(title='Lorenz attractor', axes=2, verbose=0)
scene.point(y, r=20, c='g', alpha=0.3)

for t in np.linspace(0, 20, int(20 / dt)):
    # Integrate a funny differential equation
    dydt = np.array([
        -8 / 3 * y[0] + y[1] * y[2], -10 * (y[1] - y[2]),
        -y[1] * y[0] + 28 * y[1] - y[2]
    ])
    y = y + dydt * dt

    c = np.clip([mag(dydt) * 0.005], 0, 1)[0]  # color by speed
    pts.append(y)
    cols.append([c, 0, 1 - c])

scene.points(pts, r=5, c=cols, alpha=0.3)
scene.show()
Exemplo n.º 12
0
# a polydata, save it to stack.tif file,
# then extract an isosurface from the 3d image.
#
from vtkplotter import Plotter

vp = Plotter(verbose=0)

act = vp.load("data/290.vtk").normalize().subdivide()

# Generate signed distance function and contour it
import vtk

dist = vtk.vtkSignedDistance()
dist.SetInputData(act.polydata())
dist.SetRadius(0.2) #how far out to propagate distance calculation
dist.SetBounds(-2,2, -2,2, -2,2)
dist.SetDimensions(80, 80, 80)
dist.Update()

# vp.write(dist.GetOutput(), 'stack.tif')

fe = vtk.vtkExtractSurface()
fe.SetInputConnection(dist.GetOutputPort())
fe.SetRadius(0.2) # this should match the signed distance radius
fe.Update()

pts = vp.points(act.coordinates())

vp.show([fe.GetOutput(), pts])

Exemplo n.º 13
0
# ################################################################
# Example usage of pointColors
# This method returns a color from a float in the range [0,1]
# by looking it up in matplotlib database of colormaps
# ################################################################
from __future__ import division, print_function
from vtkplotter import Plotter

# these are the available color maps
mapkeys = [
    'afmhot', 'binary', 'bone', 'cool', 'coolwarm', 'copper', 'gist_earth',
    'gray', 'hot', 'jet', 'rainbow', 'winter'
]

vp = Plotter(N=len(mapkeys), axes=0, verbose=0, interactive=0)

#load actor and subdivide mesh to increase the nr of vertex points
# make it invisible:
pts = vp.load('data/shapes/mug.ply', alpha=0).subdivide().coordinates()

for i, key in enumerate(mapkeys):  # for each available color map name
    apts = vp.points(pts).pointColors(pts[:, 1], cmap=key)
    vp.show(apts, at=i, legend=key)

vp.show(interactive=1)
Exemplo n.º 14
0
# Draw the PCA (Principal Component Analysis) ellipsoid that contains 50% of
# a cloud of points, then check if points are inside the surface.
# Extra info is stored in actor.info['sphericity'], 'va', 'vb', 'vc'.
#
from vtkplotter import Plotter
from vtkplotter.analysis import pca
import numpy as np

vp = Plotter(verbose=0, axes=4)

pts = np.random.randn(200, 3)  # random gaussian point cloud

act = pca(pts, pvalue=0.5, pcaAxes=1, legend='PCA ellipsoid')

ipts = act.getActor(0).insidePoints(pts)  # act is a vtkAssembly
opts = act.getActor(0).insidePoints(pts, invert=True)
vp.points(ipts, c='g')
vp.points(opts, c='r')

print('in  points #', len(ipts))
print('out points #', len(opts))
print('sphericity :', act.info['sphericity'])

vp.actors.append(act)  # add actor to the list to be shown (not automatic)
vp.show()
Exemplo n.º 15
0
# generate 3 random sets of points
# and align them using vtkProcrustesAlignmentFilter.
#
from __future__ import division, print_function
from random import uniform as u
from vtkplotter import Plotter
from vtkplotter.analysis import procrustes

vp = Plotter(shape=[1, 2], verbose=0, axes=2, sharecam=0)

N = 15  # number of points
x = 1.  # add some randomness

pts1 = [(u(0, x), u(0, x), u(0, x) + i) for i in range(N)]
pts2 = [(u(0, x) + 3, u(0, x) + i / 2 + 2, u(0, x) + i + 1) for i in range(N)]
pts3 = [(u(0, x) + 4, u(0, x) + i / 4 - 3, u(0, x) + i - 2) for i in range(N)]

act1 = vp.points(pts1, c='r', legend='set1')
act2 = vp.points(pts2, c='g', legend='set2')
act3 = vp.points(pts3, c='b', legend='set3')

vp.show(at=0)

# find best alignment among the n sets of points,
# return an Assembly formed by the aligned sets
aligned = procrustes([act1, act2, act3])

#print(aligned.info['transform'])

vp.show(aligned, at=1, interactive=1)
Exemplo n.º 16
0
# (values can be copied in the code by pressing C in the rendering window)
vp = Plotter(verbose=0, axes=0, interactive=0)
vp.camera.SetPosition(962, -239, 1034)
vp.camera.SetFocalPoint(0.0, 0.0, 10.0)
vp.camera.SetViewUp(-0.693, -0.479, 0.539)

pb = ProgressBar(0,nc, c='g') # a green progress bar
for t1 in pb.range():  # for each time point
    t2=t1+1
    if t1==nc-1: t2=t1 # avoid index overflow with last time point
    
    vp.actors=[]       # clean up the list of actors at each iteration
    vp.cylinder([0,0,-15], r=260, height=10, texture='marble', res=60)
    vp.cylinder([0,0, 10], r=260, height=50, wire=1, c='gray', res=60)

    pts, cols = [],[]    
    for i,p in enumerate(mesh): # for each vertex in the mesh
        c1, c2 = conc[t1,i], conc[t2,i]
        cgrad = abs(c2-c1)*cgradfac     # intensity of variation
        gx, gy, gz = np.random.randn(3) # make points wiggle a bit
        pts.append(p + vector(gx/4, gy/4, gz + c1*20))
        cols.append([0, c1, cgrad])     # RGB color

    vp.points(pts, c=cols, alpha=1.0, r=6)  # points actor
    vp.points(pts, c=cols, alpha=0.1, r=30) # halos actor
    vp.camera.Azimuth(60/nc) # rotate camera by a fraction
    vp.show() # show the four new actors at each iteration
    pb.print()

vp.show(interactive=1)
Exemplo n.º 17
0
# histogram2D example
#
from vtkplotter import Plotter, histogram2D
import numpy as np

vp = Plotter(axes=1, verbose=0)
vp.xtitle = 'x gaussian, s=1.0'
vp.ytitle = 'y gaussian, s=1.5'
vp.ztitle = 'dN/dx/dy'

N = 20000
x = np.random.randn(N) * 1.0
y = np.random.randn(N) * 1.5

vp.add(histogram2D(x, y, c='dr', bins=15, fill=False))

vp.points([x, y, np.zeros(N)], c='black', alpha=0.1)

vp.show(viewup='z')
Exemplo n.º 18
0
# Blue points are the N points used for fitting.
# Green histogram is the distribution of residuals from the fitting.
# Red histogram is the distribution of the curvatures (1/r**2).
# Fitted radius can be accessed from attribute actor.radius

from __future__ import division, print_function
from vtkplotter import Plotter, fitSphere, histogram, line

vp = Plotter(verbose=0, axes=0)

# load mesh and increase by a lot (N=2) the nr of surface vertices
s = vp.load('data/shapes/cow.vtk').alpha(0.3).subdivide(N=2)

reds, invr = [], []
for i, p in enumerate(s.coordinates()):
    if i%1000: continue           # skip most points
    pts = s.closestPoint(p, N=16) # find the N closest points to p
    sph = fitSphere(pts, alpha=0.05) # find the fitting sphere
    if sph is None: 
    	continue # may fail if all points sit on a plane
    vp.add(sph)
    vp.points(pts)
    vp.add(line(sph.info['center'], p, lw=2))
    reds.append(sph.info['residue'])
    invr.append(1/sph.info['radius']**2)

vp.add(histogram(reds, title='residue', bins=12, c='g', corner=3))
vp.add(histogram(invr, title='1/r**2',  bins=12, c='r', corner=4))

vp.show(viewup='z')
Exemplo n.º 19
0
for th in np.linspace(0, np.pi,   N, endpoint=True):
    lats = []
    for ph in np.linspace(0, 2*np.pi, N, endpoint=True):
        p  = np.array([sin(th)*cos(ph), sin(th)*sin(ph), cos(th)])*rmax
        intersections = shape.intersectWithLine([0,0,0], p) ### <--
        if len(intersections):
            value = mag(intersections[0])
            lats.append(value - rbias)
            pts.append(intersections[0])
        else:
            lats.append(rmax - rbias)
            pts.append(p)
    agrid.append(lats)
agrid = np.array(agrid)

vp.points(pts, c='b', r=2)
vp.show(at=0)

############################################################
try:
    import pyshtools
except:
    print('Please install pyshtools to run this example')
    print('Follow instructions at https://shtools.oca.eu/shtools')
    exit(0)

grid = pyshtools.SHGrid.from_array(agrid)
grid.plot() # plots the scalars in a 2d plots latitudes vs longitudes

clm = grid.expand()
clm.plot_spectrum2d() # plot the value of the sph harm. coefficients
Exemplo n.º 20
0
# Example for delaunay2D() and cellCenters()
#
from vtkplotter import Plotter, delaunay2D

vp = Plotter(shape=(1, 2), interactive=0)

d0 = vp.load('data/250.vtk', legend='original mesh').rotateY(-90)

coords = d0.coordinates()  # get the coordinates of the mesh vertices
# Build a mesh starting from points in space
#  (points must be projectable on the XY plane)
d1 = delaunay2D(coords, c='r', wire=1, legend='delaunay mesh')

cents = d1.cellCenters()
ap = vp.points(cents, legend='cell centers')

vp.show([d0, d1], at=0)  # NB: d0 and d1 are slightly different
vp.show([d1, ap], at=1, interactive=1)
Exemplo n.º 21
0
# ################################################################
# Example usage of colorMap(value, name)
# This method returns a color from a float in the range [0,1]
# by looking it up in matplotlib database of colormaps
# ################################################################
from __future__ import division, print_function
from vtkplotter import Plotter, colorMap

mapkeys = [
    'afmhot', 'binary', 'bone', 'cool', 'coolwarm', 'copper', 'gist_earth',
    'gray', 'hot', 'jet', 'rainbow', 'winter'
]

vp = Plotter(shape=(3, 4), axes=3, verbose=0, interactive=0)

#load actor and subdivide mesh to increase the nr of vertex points
act = vp.load('data/shapes/mug.ply', c='gray/0.1', wire=1).subdivide()
pts = act.coordinates()
print('range in y is:', act.ybounds())

for i, key in enumerate(mapkeys):  # for each available color map name

    # make a list of colors based on the y position of point p
    cols = [colorMap(p[1] / .087, name=key) for p in pts]

    apts = vp.points(pts, cols)

    vp.show([act, apts], at=i, legend=key)

vp.show(interactive=1)
Exemplo n.º 22
0
screen = vp.add(grid(pos=[0, 0, -D], sx=0.1, sy=0.1, resx=200, resy=50))
screen.wire(False)  # show it as a solid plane (not as wireframe)

k = 0.0 + 1j * 2 * pi / lambda1  # complex wave number
norm = len(slits) * 5e+5
amplitudes = []

for i, x in enumerate(screen.coordinates()):
    psi = 0
    for s in slits:
        r = mag(x - s)
        psi += exp(k * r) / r
    psi2 = real(psi * conj(psi))  # psi squared
    amplitudes.append(psi2)
    screen.point(i, x + [0, 0, psi2 / norm])  # elevate grid in z

screen.pointColors(amplitudes, cmap='hot')

vp.points(array(slits) * 200, c='w')  # slits scale magnified by factor 200

vp.add(grid(sx=0.1, sy=0.1, resx=6, resy=6,
            c='white/.1'))  # add some annotation
vp.add(line([0, 0, 0], [0, 0, -D], c='white/.1'))
vp.text("source plane", pos=[-.05, -.053, 0], s=.002, c='gray')
vp.text('detector plane D = ' + str(D) + ' m',
        pos=[-.05, -.053, -D],
        s=.002,
        c='gray')

vp.show(zoom=1.1)
Exemplo n.º 23
0
for i, p in enumerate(s.coordinates()):
    pts = s.closestPoint(p, N=12) # find the N closest points to p
    sph = fitSphere(pts)       # find the fitting sphere     
    if sph is None: continue

    value = sph.info['radius']*10
    color = colorMap(value, name='jet') # map value to a RGB color
    n = norm(p-sph.info['center']) # unit vector from sphere center to p
    vals.append(value)
    cols.append(color) 
    pts1.append(p)
    pts2.append(p+n/8)
    if not i%500: 
        print(i,'/',s.N())
    
vp.points(pts1, c=cols)
vp.addScalarBar()
vp.lines(pts1, pts2, c='black 0.2')
vp.histogram(vals, title='values', bins=20, vrange=[0,1])

vp.show()









Exemplo n.º 24
0
# be moved to a place close to the corresponding target landmark.
# The points in between are interpolated using Bookstein's algorithm.
#
from vtkplotter import Plotter, thinPlateSpline
import numpy as np
np.random.seed(1)

vp = Plotter(verbose=0)

act = vp.load('data/shuttle.obj')

# pick 4 random points
indxs = np.random.randint(0, act.N(), 4)

# and move them randomly by a little
ptsource, pttarget = [], []
for i in indxs:
    ptold = act.point(i)
    ptnew = ptold + np.random.rand(3) * 0.2
    act.point(i, ptnew)
    ptsource.append(ptold)
    pttarget.append(ptnew)
    print(ptold, '->', ptnew)

warped = thinPlateSpline(act, ptsource, pttarget)
warped.alpha(0.4).color('b')
#print(warped.info['transform']) # saved here.

apts = vp.points(ptsource, r=15, c='r')
vp.show([act, warped, apts], viewup='z')
Exemplo n.º 25
0
# generate two random sets of points as 2 actors
# and align them using the Iterative Closest Point algorithm.
#
from __future__ import division
from random import uniform as u
from vtkplotter import Plotter, align, arrow

vp = Plotter(shape=[1, 2], verbose=0, axes=2)

N1 = 15  # number of points of first set
N2 = 15  # number of points of second set
x = 1.  # add some randomness

pts1 = [(u(0, x), u(0, x), u(0, x) + i) for i in range(N1)]
pts2 = [(u(0, x) + 3, u(0, x) + i / 2 + 2, u(0, x) + i + 1) for i in range(N2)]

act1 = vp.points(pts1, r=8, c='b', legend='source')
act2 = vp.points(pts2, r=8, c='r', legend='target')

vp.show(at=0)

# find best alignment between the 2 sets of points, e.i. find
# how to move act1 to best match act2
alpts1 = align(act1, act2).coordinates()
vp.points(alpts1, r=8, c='b')

for i in range(N1):  #draw arrows to see where points end up
    vp.add(arrow(pts1[i], alpts1[i], c='k', s=0.007, alpha=.1))

vp.show(at=1, interactive=1)
Exemplo n.º 26
0
# 4. a triangular mesh is extracted from this set of sparse points
#    'bins' is the number of voxels of the subdivision
# NB: recoSurface only works with vtk version >7
#
from __future__ import division, print_function
from vtkplotter import Plotter
from vtkplotter.analysis import recoSurface, smoothMLS2D
import numpy as np

vp = Plotter(shape=(1, 4), axes=0)

act = vp.load('data/shapes/pumpkin.vtk')
vp.show(act, at=0)

noise = np.random.randn(act.N(), 3) * 0.05

act_pts0 = vp.points(act.coordinates() + noise, r=3)  #add noise
act_pts1 = act_pts0.clone()  #make a copy to modify
vp.show(act_pts0, at=1, legend='noisy cloud')

smoothMLS2D(act_pts1, f=0.4)  #smooth cloud, input actor is modified

print('Nr of points before cleaning polydata:', act_pts1.N())
act_pts1.clean(tol=0.01)  #impose a min distance among mesh points
print('             after  cleaning polydata:', act_pts1.N())

vp.show(act_pts1, at=2, legend='smooth cloud')

act_reco = recoSurface(act_pts1, bins=128)  #reconstructed from points
vp.show(act_reco, at=3, axes=7, interactive=1, legend='surf reco')
from __future__ import division, print_function
from vtkplotter import Plotter, colorMap
from vtkplotter.analysis import smoothMLS2D
import numpy as np


vp1 = Plotter(shape=(1,4), axes=4)

act = vp1.load('data/shapes/bunny.obj', c='k 0.05', wire=1).normalize().subdivide()
pts = act.coordinates(copy=True)      # pts is a copy of the points not a reference
pts += np.random.randn(len(pts),3)/40 # add noise, will not mess up the original points


#################################### smooth cloud with MLS
# build the points actor
s0 = vp1.points(pts, c='blue', r=3, legend='point cloud') 
vp1.show(s0, at=0) 

s1 = s0.clone(c='dg')                 # a dark green copy of s0

# project s1 points into a smooth surface of points 
# return a demo actor showing 30 regressions at random points
mls1 = smoothMLS2D(s1, f=0.5, showNPlanes=30) # first pass
vp1.show(mls1, at=1, legend='first pass') 

mls2 = smoothMLS2D(s1, f=0.3, showNPlanes=30) # second pass
vp1.show(mls2, at=2, legend='second pass') 

mls3 = smoothMLS2D(s1, f=0.1)                 # third pass
vp1.show(s1,   at=3, legend='third pass', zoom=1.3) 
Exemplo n.º 28
0
from __future__ import division, print_function
from vtkplotter import Plotter, mag
import numpy as np

scene = Plotter(title='Lorenz attractor', axes=2, verbose = 0)

dt = 0.001
y = [25, -10, -7] # Starting point (initial condition)
pts, cols = [], []
scene.point(y, r=20, c='g', alpha=0.3)

for t in np.linspace(0,20, int(20/dt)):
  # Integrate a funny differential equation
  dydt = np.array([-8/3*y[0]+ y[1]*y[2], -10*(y[1]-y[2]), -y[1]*y[0]+28*y[1]-y[2]])
  y = y + dydt * dt

  c = np.clip( [mag(dydt) * 0.005], 0, 1)[0] # color by speed
  pts.append(y)
  cols.append([c,0, 1-c])

scene.points(pts, cols, r=2)
scene.show()

Exemplo n.º 29
0
    for colony in colonies:

        newcells = []
        for cell in colony.cells:

            if cell.dieAt(t): continue
            if cell.divideAt(t):
                newc = cell.split()  # make daughter cell
                vp.line(cell.pos, newc.pos, c='k', lw=3, alpha=.5)
                newcells.append(newc)
            newcells.append(cell)
        colony.cells = newcells

        pts = [c.pos for c in newcells]  # draw all points at once
        vp.points(pts, c=colony.color, r=5, alpha=.80)  # nucleus
        vp.points(pts, c=colony.color, r=15, alpha=.05)  # halo
        msg += str(len(colony.cells)) + ','

    pb.print(msg + str(int(t)))
    vp.show(resetcam=0)

# draw the oriented ellipsoid that contains 50% of the cells
for colony in colonies:
    pts = [c.pos for c in colony.cells]
    a = pca(pts,
            pvalue=0.5,
            c=colony.color,
            pcaAxes=0,
            alpha=.3,
            legend='1/rate=' + str(colony.cells[0].tdiv) + 'h')