Пример #1
0
"""
Show a cube for each available texture name
any jpg file can be used as texture.
"""
from vtkplotter import Plotter, Cube, Text
from vtkplotter.settings import textures, textures_path

print(__doc__)
print(textures_path)
print(textures)

vp = Plotter(N=len(textures), axes=0)

for i, txt in enumerate(textures):
    cb = Cube().texture(txt)
    tname = Text(txt, pos=3)
    vp.show(cb, tname, at=i)

vp.show(interactive=1)
Пример #2
0
    noise is added to its vertices.
 2. the point cloud is smoothened with MLS
    (see moving_least_squares.py)
 3. clean(actor) imposes a minimum distance
    among mesh points where 'tol' is the
    fraction of the actor size.
 4. a triangular mesh is extracted from
    this set of sparse Points, 'bins' is the
    number of voxels of the subdivision
'''
from __future__ import division, print_function
from vtkplotter import Plotter, recoSurface, smoothMLS2D, Points, Text
import numpy as np

vp = Plotter(shape=(1, 5), axes=0)
vp.show(Text(__doc__), at=4)

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

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

act_pts0 = 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())
Пример #3
0
"""
Normal jpg/png images can be loaded,
cropped and rendered as any vtkImageActor
"""
from vtkplotter import Plotter, Text, datadir

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

for i in range(5):
    a = vp.load(datadir+"images/dog.jpg").crop(bottom=0.2) # crop 20%
    a.scale(1-i/10.0).alpha(0.8)   # image can be scaled in size
    a.rotateX(20*i).pos(0,0,30*i)  # (can concatenate methods)

vp += Text(__doc__)

vp.show()
Пример #4
0
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 + 0.5, np.cos(t) / 5 + 0.5, (t - 1) / 5]  # an helix

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


from vtkplotter import Plotter, Points, Text

vp = Plotter(axes=1, bg="w")
vp += Points([x, y, z], r=10, alpha=0.5).pointColors(scals)
vp += Points([xi, yi, zi]).pointColors(scalsi)
vp += Text(__doc__, pos=1, c="dr")

vp.show(viewup="z")
Пример #5
0
"""Lock an object orientation to the scene camera. 
"""
from vtkplotter import Sphere, Text, Plotter

plt = Plotter(axes=1, interactive=0)

sp = Sphere().wireframe()
tx1 = Text("Fixed point", sp.getPoint(10), s=0.07, c="lb")
tx2 = Text("Follow point", sp.getPoint(144), s=0.07, c="lg")

# a camera must exist prior to calling followCamera()
plt.show(sp)
tx2.followCamera()  # a vtkCamera can also be passed as argument

plt.show(sp, tx1, tx2, Text(__doc__), interactive=1)
Пример #6
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, alignProcrustes, Text, Points

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

N = 15  # number of points
x = 1.0  # 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 = Points(pts1, c="r").legend("set1")
act2 = Points(pts2, c="g").legend("set2")
act3 = Points(pts3, c="b").legend("set3")

vp.show(act1, act2, act3, at=0)

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

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

vp.show(aligned, Text(__doc__), at=1, interactive=1)
Пример #7
0
"""Read and show meshio objects"""
import meshio
from vtkplotter import datadir, show, Actor, Text, printc

mesh = meshio.read(datadir + 'shuttle.obj')

# vtkplotter understands meshio format:
printc(mesh, c='y')
show(mesh, Text(__doc__))

# or explicitly convert it to an Actor object:
a = Actor(mesh).lineWidth(1).color('tomato')
show(a)
Пример #8
0
Find the closest point
on the mesh to each random point
"""
import trimesh
import numpy as np
from vtkplotter import Text, show, Arrows

mesh = trimesh.load_remote(
    'https://github.com/mikedh/trimesh/raw/master/models/cycloidal.ply')
points = mesh.bounding_box_oriented.sample_volume(count=30)

# find the closest point on the mesh to each random point
closest_points, distances, triangle_id = mesh.nearest.on_surface(points)
#print('Distance from point to surface of mesh:\n{}'.format(distances))

# create a PointCloud object out of each (n,3) list of points
cloud_original = trimesh.points.PointCloud(points)
cloud_close = trimesh.points.PointCloud(closest_points)

# create a unique color for each point
cloud_colors = np.array([trimesh.visual.random_color() for i in points])

# set the colors on the random point and its nearest point to be the same
cloud_original.vertices_color = cloud_colors
cloud_close.vertices_color = cloud_colors

arrs = Arrows(cloud_original.vertices, cloud_close.vertices, c='w')

## create a scene containing the mesh and two sets of points
show(mesh, cloud_original, cloud_close, arrs, Text(__doc__))
Пример #9
0
"""
Create a set of transparencies 
which can be passed to method pointColors()
"""
from vtkplotter import load, show, Text, datadir

mesh = load(datadir + "beethoven.ply")

# pick y coordinates of vertices and use them as scalars
scals = mesh.getPoints()[:, 1]

# define opacities in the range of the scalar,
# at min(scals) alpha is 0.1,
# at max(scals) alpha is 0.9:
alphas = [0.1, 0.1, 0.3, 0.4, 0.9]

mesh.pointColors(scals, alpha=alphas, cmap="copper")
# print(mesh.scalars('pointColors_copper')) # retrieve scalars

show(mesh, Text(__doc__), axes=9)
Пример #10
0
'''
Intersect a vtkImageData (voxel dataset) with planes.
'''
from vtkplotter import show, loadImageData, probeLine, vector, Text

img = loadImageData('data/embryo.slc')

pos = img.GetCenter()

lines = []
for i in range(60):  # probe scalars on 60 parallel lines
    step = (i - 30) * 2
    p1, p2 = pos + vector(-100, step, step), pos + vector(100, step, step)
    a = probeLine(img, p1, p2, res=200)
    a.alpha(0.5).lineWidth(6)
    lines.append(a)
    #print(a.scalars(0)) # numpy scalars can be access here
    #print(a.scalars('vtkValidPointMask')) # the mask of valid points

show(lines + [Text(__doc__)], axes=4, verbose=0, bg='w')
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.
"""
from vtkplotter import Plotter, Sphere, smoothMLS3D, Points, Text

vp = Plotter(N=2, axes=0, bg="w")

# 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 = 0.2, 0.4, 0.1  # some random warping paramenters, and noise factor
sets = []
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
    ap = Points(cs, c=i, alpha=0.5).addGaussNoise(1.0).time(0.2 * i)
    sets.append(ap)

vp.show(Text(__doc__, c="k"), at=0)
vp.show(sets, at=0, zoom=1.4)  # show input clouds as func(time)

asse = smoothMLS3D(sets, 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)
Пример #12
0
"""
Using normal vtk commands to load a xml vti file
then use vtkplotter to show the resulting 3d image.
"""
import vtk

# Create the reader for the data.
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName("data/vase.vti")
reader.Update()
img = reader.GetOutput()

# specify the data array in the file to process
# img.GetPointData().SetActiveAttribute('SLCImage', 0)

#################################
from vtkplotter import Volume, load, show, Text

# can set colors and transparencies along the scalar range
vol = Volume(img,
             c=["gray", "fuchsia", "dg", (0, 0, 1)],
             alphas=[0.1, 0.2, 0.3, 0.8])

# load command returns an isosurface (vtkActor) of the 3d image
iso = load("data/vase.vti", threshold=140).wire(True).alpha(0.1)

# show command creates and returns an instance of class Plotter
show([vol, iso, Text(__doc__)], verbose=0, bg="w")
Пример #13
0
        ph = np.deg2rad(long)
        p = spher2cart(agrid_reco[j][i], th, ph)
        pts1.append(p)
        ll.append((lat, long))

radii = agrid_reco.T.ravel()
n = 500j
lnmin, lnmax = np.array(ll).min(axis=0), np.array(ll).max(axis=0)
grid = np.mgrid[lnmax[0]:lnmin[0]:(n), lnmin[1]:lnmax[1]:(n + 1j)]
grid_x, grid_y = grid
agrid_reco_finer = griddata(ll, radii, (grid_x, grid_y), method='cubic')

pts2 = []
for i, long in enumerate(
        np.linspace(0, 360, num=agrid_reco_finer.shape[1], endpoint=False)):
    for j, lat in enumerate(
            np.linspace(90, -90, num=agrid_reco_finer.shape[0],
                        endpoint=True)):
        th = np.deg2rad(90 - lat)
        ph = np.deg2rad(long)
        p = spher2cart(agrid_reco_finer[j][i], th, ph)
        pts2.append(p)

act1 = Points(pts1, r=5, c="b", alpha=1)
act1_col = Points(pts1colored, r=8, c="k", alpha=0.5)
act2 = Points(pts2, r=3, c="r", alpha=0.5)
act2.clean(0.01)  # impose point separation of 1% of the bounding box size

comment = Text('spherical harmonics\nexpansion of order ' + str(lmax))
show(act2, comment, at=1, interactive=True)
Пример #14
0
"""
Intersect a vtkImageData (voxel dataset) with planes
"""
from vtkplotter import show, loadImageData, probePlane, vector, Text, datadir

img = loadImageData(datadir + "embryo.slc")

planes = []
for i in range(6):
    print("probing slice plane #", i)
    pos = img.GetCenter() + vector(0, 0, (i - 3) * 25.0)
    a = probePlane(img, origin=pos, normal=(0, 0, 1)).alpha(0.2)
    planes.append(a)
    # print(max(a.scalars(0))) # access scalars this way, 0 means first

show(planes + [Text(__doc__)], axes=4, verbose=0, bg="w")
Пример #15
0
"""
How to share the same color map
across different meshes.
"""
from vtkplotter import load, Text, show, datadir

#####################################
man1 = load(datadir + "man.vtk")
scals = man1.coordinates()[:, 2] * 5 + 27  # pick z coordinates [18->34]

man1.pointColors(scals, cmap="jet", vmin=18, vmax=44)

#####################################
man2 = load(datadir + "man.vtk")
scals = man2.coordinates()[:, 2] * 5 + 37  # pick z coordinates [28->44]

man2.pointColors(scals, cmap="jet", vmin=18, vmax=44)

show([[man1, Text(__doc__)], man2], N=2, elevation=-40)
Пример #16
0
"""
Example usage of removeOutliers()
and cluster() methods.
"""
from vtkplotter import show, cluster, removeOutliers, Text
import numpy as np

# generate 4 random sets of N points in space
N = 2000
f = 0.6
noise1 = np.random.rand(N, 3) * f + np.array([1, 1, 0])
noise2 = np.random.rand(N, 3) * f + np.array([1, 0, 1.2])
noise3 = np.random.rand(N, 3) * f + np.array([0, 1, 1])
noise4 = np.random.randn(N, 3) * f / 8 + np.array([1, 1, 1])

noise4 = removeOutliers(noise4, 0.05)

# merge points to lose their identity
pts = noise1.tolist() + noise2.tolist() + noise3.tolist() + noise4.tolist()

# find back their identity through clustering
cl = cluster(pts, radius=0.1)  # returns a vtkAssembly

show(cl, Text(__doc__), axes=1, viewup='z')
Пример #17
0
"""
Intersect a Volume (voxel dataset) with planes
"""
from vtkplotter import show, load, probePlane, vector, Text, datadir

vol = load(datadir+"embryo.slc")

planes = []
for i in range(6):
    print("probing slice plane #", i)
    pos = vol.imagedata().GetCenter() + vector(0, 0, (i - 3) * 25.0)
    a = probePlane(vol, origin=pos, normal=(0, 0, 1)).alpha(0.2)
    planes.append(a)
    # print(max(a.scalars(0))) # access scalars this way, 0 means first

show(planes, Text(__doc__), axes=4, bg="w")
Пример #18
0
"""
Using normal vtk commands to load a xml vti file
then use vtkplotter to show the resulting 3d image.
"""
import vtk
from vtkplotter import datadir

# Create the reader for the data.
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(datadir+"vase.vti")
reader.Update()
img = reader.GetOutput()

# specify the data array in the file to process
# img.GetPointData().SetActiveAttribute('SLCImage', 0)


#################################
from vtkplotter import Volume, load, show, Text

# can set colors and transparencies along the scalar range
vol = Volume(img, c=["gray", "fuchsia", "dg", (0, 0, 1)], alphas=[0.1, 0.2, 0.3, 0.8])

# load command returns an isosurface (vtkActor) of the 3d image
iso = load("data/vase.vti", threshold=140).wire(True).alpha(0.1)

# show command creates and returns an instance of class Plotter
show(vol, iso, Text(__doc__), verbose=0, bg="w")
generate a scalar field by the signed distance from a polydata, 
save it to stack.tif file,
then extract an isosurface from the 3d image.
'''
from vtkplotter import Plotter, Points, Text

vp = Plotter(verbose=0)

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

# 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 = Points(act.coordinates())

vp.show([fe.GetOutput(), pts, Text(__doc__)])
Пример #20
0
'''
Set a jpeg background image on a vtkRenderingWindow layer,
after the first rendering it can be zoomed to fill the window.
'''
from vtkplotter import Plotter, load, Polygon, Text

doc = Text(__doc__, c='k', bg='w')

vp = Plotter(N=2,
             size=(400, 800),
             axes=4,
             sharecam=0,
             bg='data/images/tropical.jpg')

a1 = load('data/shapes/flamingo.3ds').rotateX(-90)
a2 = Polygon()

vp.show([a1, doc], at=0)

vp.backgroundRenderer.GetActiveCamera().Zoom(2.5)

vp.show(a2, at=1, interactive=1)
Пример #21
0
"""Closing the Rendering Window

Press q:
Control returns to terminal,
window will not close but become unresponsive"""
from vtkplotter import Text, Paraboloid, Hyperboloid, Plotter, show

mesh = Paraboloid()

vp1 = show(mesh, Text(__doc__), title='First Plotter instance')

# Now press 'q' to exit the window interaction,
# windows stays open but not reactive anymore.

# You can go back to interavtion mode by simply calling:
#show()

input(
    '\nControl returned to terminal shell:\nwindow is now unresponsive (press Enter)'
)

vp1.closeWindow()

# window should now close, the Plotter instance becomes unusable
# but mesh objects still exist in it:

print("First Plotter actors:", vp1.actors)
vp1.show()  # THIS HAS NO EFFECT: window does not exist anymore. Cannot reopen.

##################################################################
# Can now create a brand new Plotter and show the old object in it
Пример #22
0
'''
Shrink the triangulation of a mesh to make the inside visible.
'''
from vtkplotter import load, Sphere, show, Text

pot = load('data/shapes/teapot.vtk').shrink(0.75)

s = Sphere(r=0.2).pos(0, 0, -0.5)

show([pot, s, Text(__doc__)], viewup='z')
Пример #23
0
reader.SetFileName(datadir + "vase.vti")
reader.Update()
img = reader.GetOutput()  # vtkImageData object

# NB: the above lines could be reduced to:
#img = load(datadir+"vase.vti").imagedata()

#################################
from vtkplotter import Volume, show, Text

# can set colors and transparencies along the scalar range
# from minimum to maximum value. In this example voxels with
# the smallest value will be completely transparent (and white)
# while voxels with highest value of the scalar will get alpha=0.8
# and color will be=(0,0,1)
vol1 = Volume(img, mode=0)  # composite rendering
vol1.color(["white", "fuchsia", "dg", (0, 0, 1)])
#vol1.color('jet') # a matplotlib colormap name is also accepted
vol1.alpha([0.0, 0.2, 0.3, 0.8])

# a transparency for the GRADIENT of the scalar can also be set:
# in this case when the scalar is ~constant the gradient is ~zero
# and the voxel are made transparent:
vol1.alphaGradient([0.0, 0.5, 0.9])

# mode = 1 is maximum-projection volume rendering
vol2 = load(datadir + "vase.vti").mode(1).addPos(60, 0, 0)

# show command creates and returns an instance of class Plotter
show(vol1, vol2, Text(__doc__), bg="w", axes=1)
Пример #24
0
"""
Using normal vtk commands to load a xml vti file
then use vtkplotter to show the resulting 3d image.
"""
import vtk
from vtkplotter import datadir

# Create the reader for the data.
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(datadir + "vase.vti")
reader.Update()
img = reader.GetOutput()

# specify the data array in the file to process
# img.GetPointData().SetActiveAttribute('SLCImage', 0)

#################################
from vtkplotter import Volume, load, show, Text

# can set colors and transparencies along the scalar range
vol = Volume(img,
             c=["gray", "fuchsia", "dg", (0, 0, 1)],
             alpha=[0.1, 0.2, 0.3, 0.8])

# load command returns an isosurface (vtkActor) of the 3d image
iso = load(datadir + "vase.vti", threshold=140).wire(True).alpha(0.1)

# show command creates and returns an instance of class Plotter
show(vol, iso, Text(__doc__), bg="w")
Пример #25
0
"""
Intersect a Volume (voxel dataset) with planes.
"""
from vtkplotter import show, loadVolume, probeLine, vector, Text, datadir

vol = loadVolume(datadir+"embryo.slc")

pos = vol.imagedata().GetCenter()

lines = []
for i in range(60):  # probe scalars on 60 parallel lines
    step = (i - 30) * 2
    p1, p2 = pos + vector(-100, step, step), pos + vector(100, step, step)
    a = probeLine(vol, p1, p2, res=200)
    a.alpha(0.5).lineWidth(6)
    lines.append(a)
    # print(a.scalars(0)) # numpy scalars can be access here
    # print(a.scalars('vtkValidPointMask')) # the mask of valid points

show(lines, Text(__doc__), axes=4, bg="w")
Пример #26
0
"""
Shrink the triangulation of a mesh
to make the inside visible.
"""
from vtkplotter import load, Sphere, show, Text, datadir

pot = load(datadir+"teapot.vtk").shrink(0.75)

s = Sphere(r=0.2).pos(0, 0, -0.5)

show(pot, s, Text(__doc__), viewup="z")
'''
Extracts the cells where scalar value satisfies a threshold criterion.
'''
from vtkplotter import load, Text, show

doc = Text(__doc__)

man = load('data/shapes/man.vtk')

scals = man.coordinates()[:, 1] + 37  # pick y coords of vertices

man.pointColors(scals, cmap='cool')
man.addScalarBar(title='threshold', horizontal=True)

# make a copy and threshold the mesh
cutman = man.clone().threshold(scals, vmin=36.9, vmax=37.5)

# distribute the actors on 2 renderers
show([[man, doc], cutman], N=2, elevation=-30)
Пример #28
0
'''
Mirror a mesh along one of the Cartesian axes.
'''
from vtkplotter import Plotter, Text

vp = Plotter(axes=2)

myted1 = vp.load('data/shapes/teddy.vtk')

myted2 = myted1.clone().mirror('y').pos([0, 3, 0]).color('green')

vp.show([myted1, myted2, Text(__doc__)], viewup='z')
Пример #29
0
RingThickness = 0.3  # thickness of the toroid
RingRadius = 1
k = 1.4e-23  # Boltzmann constant
T = 300  # room temperature
dt = 1.5e-5
#############################################################


def reflection(p, pos):
    n = versor(pos)
    return np.dot(np.identity(3) - 2 * n * n[:, np.newaxis], p)


vp = Plotter(title="gas in toroid", interactive=0, axes=0, bg="w")

vp.add(Text(__doc__))

vp.add(Torus(c="g", r=RingRadius, thickness=RingThickness, alpha=0.1).wire(1))  ### <--

Atoms = []
poslist = []
plist, mlist, rlist = [], [], []
mass = Matom * Ratom ** 3 / Ratom ** 3
pavg = np.sqrt(2.0 * mass * 1.5 * k * T)  # average kinetic energy p**2/(2mass) = (3/2)kT

for i in range(Natoms):
    alpha = 2 * np.pi * random()
    x = RingRadius * np.cos(alpha) * 0.9
    y = RingRadius * np.sin(alpha) * 0.9
    z = 0
    Atoms = Atoms + [vp.add(Sphere(pos=(x, y, z), r=Ratom, c=i))]  ### <--
Пример #30
0
from vtkplotter import Cube, Text, show, collection
from vtkplotter.settings import fonts

Text("List of available fonts:")

Cube().c('white').rotateX(20).rotateZ(20)

for i, f in enumerate(fonts):
    Text(f + ':  The quick fox jumps over the lazy dog.',
         pos=(5, i * 40 + 20),
         font=f,
         c=i % 3)

show(collection(), axes=False)