Exemple #1
0
def showSolution3D(S, start, goal):
    from vtkplotter import Text2D, Text, Cube, Line, Grid, merge, show

    pts, cubes, txts = [], [], []
    pts = [(x, -y) for y, x in S[0]]
    for y, line in enumerate(Z):
        for x, c in enumerate(line):
            if c: cubes.append(Cube([x, -y, 0]))

    path = Line(pts).lw(6).c('tomato')
    walls = merge(cubes).clean().flat().texture('wood1')

    sy, sx = S[1].shape
    gradient = np.flip(S[1], axis=0).ravel()
    grd = Grid(pos=((sx - 1) / 2, -(sy - 1) / 2, -0.49),
               sx=sx,
               sy=sy,
               resx=sx,
               resy=sy)
    grd.lw(0).wireframe(False).cellColors(gradient, cmap='gist_earth_r')
    grd.addScalarBar(title='Gradient', horizontal=True, c='k')

    txts.append(Text2D(__doc__, c='k'))
    txts.append(Text('Start', pos=[start[1] - 1, -start[0] + 1.5, 1], c='k'))
    txts.append(Text('Goal!', pos=[goal[1] - 2, -goal[0] - 2.7, 1], c='k'))
    show(path, walls, grd, txts, axes=0, zoom=1.2)
Exemple #2
0
	def add_text(self, text, **kwargs):
		"""
			Adds a 2D text to the scene. Default params are to crate a large black
			text at the top of the rendering window.

			:param text: str with text to write
			:param kwargs: keyword arguments accepted by vtkplotter.shapes.Text2D
		"""
		pos = kwargs.pop('pos', 8)
		size = kwargs.pop('size', 1.75)
		color = kwargs.pop('color', 'k')
		alpha = kwargs.pop('alpha', 1)
		font = kwargs.pop('font', 'Montserrat')

		txt = self.add_vtkactor(Text2D(
				text,
				pos=pos,
				s=size,
				c=color,
				alpha=alpha,
			)
		)
		return txt
Exemple #3
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 cab be retrieved with:
mesh.asphericity()
mesh.asphericity_error()
"""
from vtkplotter import Plotter, pcaEllipsoid, Points, Text2D
import numpy as np

vp = Plotter(axes=1)

pts = np.random.randn(500, 3) * [3, 2, 1]  # random gaussian point cloud

elli = pcaEllipsoid(pts, pvalue=0.5)

ipts = elli.insidePoints(pts)  # elli is a vtkAssembly
opts = elli.insidePoints(pts, invert=True)

vp += Points(ipts, c="g")
vp += Points(opts, c="r")
vp += [elli, Text2D(__doc__)]

print("inside  points #", len(ipts))
print("outside points #", len(opts))
print("asphericity:", elli.asphericity(), '+-', elli.asphericity_error())
print("axis 1 size:", elli.va)
print("axis 2 size:", elli.vb)
print("axis 3 size:", elli.vc)
vp.show()
"""Modify a Volume dataset and
colorize voxels individually
"""
from vtkplotter import Text2D, Volume, show
import numpy as np

vol = Volume(shape=(10,11,12), mode=0)
vol.alpha(0.8).jittering(False)
vol.interpolation(0) # nearest neighbour interpolation type

# Overwrite the (sofar empty) voxel data with new data
vol.imagedata().AllocateScalars(3, 4) # type 3 corresponds to np.uint8
arr = vol.getPointArray()
arr[:] = np.random.randint(0,255, (10*11*12,4)).astype(np.uint8)

# For 4 component data, the first 3 directly represent RGB, no lookup table.
# (see https://vtk.org/doc/nightly/html/classvtkVolumeProperty.html):
vol.GetProperty().IndependentComponentsOff()

show(vol, Text2D(__doc__), axes=1)
Exemple #5
0
"""
from vtkplotter import Plotter, datadir, Text2D


def slider1(widget, event):
    value = widget.GetRepresentation().GetValue()
    mesh.color(value)


def slider2(widget, event):
    value = widget.GetRepresentation().GetValue()
    mesh.alpha(value)


vp = Plotter(axes=0)
mesh = vp.load(datadir + "magnolia.vtk").flat().lw(0.1)

# pos = position corner number: horizontal [1-4] or vertical [11-14]
vp.addSlider2D(slider1, -9, 9, value=0, pos=4, title="color number")

vp.addSlider2D(slider2,
               xmin=0.01,
               xmax=0.99,
               value=0.5,
               pos=14,
               c="blue",
               title="alpha value (opacity)")

vp += Text2D(__doc__)
vp.show()
Exemple #6
0
agrid_reco = grid_reco.to_array()

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

radii = agrid_reco.T.ravel()
n = 250j
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)

mesh2 = Points(pts2, r=2, c="r", alpha=0.5)
mesh2.clean(0.01) # impose point separation of 1% of the bounding box size

comment = Text2D('spherical harmonics\nexpansion of order '+str(lmax))
show(mesh2, comment, at=1, interactive=True)
Exemple #7
0
"""
Show a cube for each available texture name.
Any jpg file can be used as texture.
"""
from vtkplotter import Plotter, Cube, Text2D
from vtkplotter.settings import textures, textures_path

print(__doc__)
print('textures_path:', textures_path)
print('textures:', textures)

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

for i, name in enumerate(textures):
    if i>30: break
    cb = Cube().texture(name)
    tname = Text2D(name, pos=3)
    vp.show(cb, tname, at=i)

vp.show(interactive=1)
Exemple #8
0
    v_cyclic=True,
    function=one_sheet_hyperboloid,
    adaptor_class=VtkAdaptor,
)
poly_data = DodecaTessagon(**options).create_mesh()
dodeca = Mesh(poly_data).x(5).computeNormals()
dodeca.lineWidth(1).backColor('tomato')


# ---------------------------------------------------------
def chubby_torus(u, v):
    return general_torus(5, 1.5, v, warp_var(u, 0.2))

options = dict(
    u_range=[0.0, 1.0],
    v_range=[0.0, 1.0],
    u_num=2,
    v_num=12,
    color_pattern=1,
    function=chubby_torus,
    adaptor_class=VtkAdaptor,
)
poly_data = FloretTessagon(**options).create_mesh()
poly_data.GetCellData().GetScalars().SetName("color_pattern")
floret = Mesh(poly_data).reverse().y(-9).scale(0.7)
floret.cellColors("color_pattern", cmap='Greens_r').lineWidth(0.1)

# ---------------------------------------------------------
show(rhombus, dodeca, floret, Text2D(__doc__), axes=1)

Exemple #9
0
'''
for i in range(10):
    Cone().x(i) # no variable assigned!
show(...) # show all sofar created objs
'''
from vtkplotter import Cone, Text2D, show

for i in range(10):
    Cone().x(2 * i).color(i)  # no variable assigned

Text2D(__doc__)

# three points, aka ellipsis, retrieves the list of all created objects
show(..., axes=1, viewup='z')
Exemple #10
0
"""Create a set of transparencies
which can be passed to method pointColors()
"""
from vtkplotter import load, show, Text2D, datadir

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

# pick y coordinates of vertices and use them as scalars
scals = mesh.points()[:, 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.getPointArray('pointColors_copper')) # retrieve scalars

show(mesh, Text2D(__doc__), axes=9)
Exemple #11
0
"""
from vtkplotter import Mesh, Text2D, datadir, show

# define a polygon of 4 vertices:
polygon = [
    [
        (82, 92, 47),
        (87, 88, 47),  # x,y,z of vertices
        (93, 95, 47),
        (88, 99, 47)
    ],
    [[0, 1, 2, 3]],  # vertex connectivity
]

# texture coordinates, one (u,v) pair for each vertex:
tc = [(0, 0), (1, 0), (1, 1), (0, 1)]
#tc = [(0,0), (2,0), (2,2), (0,2)]

# create the Mesh(vtkActor) object
m = Mesh(polygon)

m.texture(
    datadir + "images/dog.jpg",
    tcoords=tc,
    interpolate=True,
    repeat=True,  # when tcoords extend beyond [0,1]
    edgeClamp=False,  #  only used when repeat is False
)

show(m, Text2D(__doc__), axes=8)
Exemple #12
0
    titleDepth=0,  # extrusion fractional depth of title text
    xyGrid=True,  # show a gridded wall on plane xy
    yzGrid=True,
    zxGrid=False,
    zxGrid2=True,  # show zx plane on opposite side of the bounding box
    xyPlaneColor='green',
    xyGridColor='darkgreen',  # line color
    xyAlpha=0.2,  # plane opacity
    showTicks=True,  # show major ticks
    xTitlePosition=0.5,  # title fractional positions along axis
    xTitleOffset=0.02,  # title fractional offset distance from axis line
    xTitleJustify="top-center",
    xTitleRotation=20,
    xLineColor='black',
    zLineColor='blue',
    zTitleColor='blue',
    zTitleBackfaceColor='red',  # color of axis title on the backface
    zTitleSize=0.05,
    xHighlightZero=True,  # draw a line highlighting zero position if in range
    xHighlightZeroColor='tomato',
    xTickLength=0.015,
    xTickThickness=0.0025,
    xTickColor='black',
    xMinorTicks=3,  # number of minor ticks btw two major ticks
    tipSize=0.01,  # size of the arrow tip cone
    xLabelSize=0.02,  # size of the numeric labels along axis
    xLabelOffset=-0.05,  # offset of numeric labels
)

show(box, Text2D(__doc__), axes=axes_opts)
Exemple #13
0
import trimesh
import numpy as np
from vtkplotter import show, Plane, Text2D, printc, download

# load the mesh from filename, file objects are also supported
f = download(
    'https://github.com/mikedh/trimesh/raw/master/models/featuretype.STL')
mesh = trimesh.load_mesh(f)

# get a single cross section of the mesh
txt = Text2D('cross section of the mesh', c='k')
mslice = mesh.section(plane_origin=mesh.centroid, plane_normal=[0, 0, 1])

pl = Plane(mesh.centroid, normal=[0, 0, 1], sx=6, sy=4, alpha=0.3)

slice_2D, to_3D = mslice.to_planar()

# show objects on N=2 non-synced renderers:
show([(mesh, pl), (slice_2D, txt)], N=2, sharecam=False, axes=True)

# if we wanted to take a bunch of parallel slices, like for a 3D printer
# we can do that easily with the section_multiplane method
# we're going to slice the mesh into evenly spaced chunks along z
# this takes the (2,3) bounding box and slices it into [minz, maxz]
z_extents = mesh.bounds[:, 2]
# slice every .125 model units (eg, inches)
z_levels = np.arange(*z_extents, step=0.125)

# find a bunch of parallel cross sections
sections = mesh.section_multiplane(plane_origin=mesh.bounds[0],
                                   plane_normal=[0, 0, 1],
Exemple #14
0
"""
Identifies and fills holes in input mesh.
Holes are identified by locating boundary edges, linking them
together into loops, and then triangulating the resulting loops.
size: approximate limit to the size of the hole that can be filled.
"""
from vtkplotter import load, show, Text2D, datadir

a = load(datadir + "bunny.obj")

b = a.clone().fillHoles(size=0.1)
b.color("b").wireframe(True).legend("filled mesh")

show(a, b, Text2D(__doc__), elevation=-70)
Exemple #15
0
"""Find the overlap area of 2 triangles"""
from vtkplotter import Mesh, Text2D, show
import numpy as np

verts1 = [(1.9, 0.5), (2.1, 0.8), (2.4, 0.4)]
verts2 = [(2.3, 0.8), (1.8, 0.4), (2.1, 0.3)]
faces = [(0, 1, 2)]

m1 = Mesh([verts1, faces]).c('g').lw(4).wireframe()
m2 = Mesh([verts2, faces]).c('b').lw(4).wireframe()

m3 = m1.clone().wireframe(False).c('tomato').lw(0)

zax = (0, 0, 1)
v0, v1, v2 = np.insert(np.array(verts2), 2, 0, axis=1)

m3.cutWithPlane(origin=v0, normal=np.cross(zax, v1 - v0))
if m3.NPoints():
    m3.cutWithPlane(origin=v1, normal=np.cross(zax, v2 - v1))
if m3.NPoints():
    m3.cutWithPlane(origin=v2, normal=np.cross(zax, v0 - v2))

print("Area of overlap:", m3.area())
show(m1, m2, m3, Text2D(__doc__), axes=8, verbose=0)
Exemple #16
0
for edge, L in zip(edges, length):
    g.add_edge(*edge, length=L)

# alternative method for weighted graph creation
ga = nx.from_edgelist([(e[0], e[1], {
    "length": L
}) for e, L in zip(edges, length)])

# arbitrary indices of mesh.vertices to test with
start = 0
end = int(len(mesh.vertices) / 2.0)

# run the shortest path query using length for edge weight
path = nx.shortest_path(g, source=start, target=end, weight="length")

################################### VISUALIZE RESULT
from vtkplotter import Text2D, show

# make the sphere transparent-ish
mesh.visual.face_colors = [100, 100, 100, 100]

# Path3D with the path between the points
path_visual = trimesh.load_path(mesh.vertices[path])

# visualizable two points
points_visual = trimesh.points.PointCloud(mesh.vertices[[start, end]])

txt = Text2D('Shortest path query\nusing length for edge weight', c='blue')

show(mesh, points_visual, path_visual, txt, axes=6)
Exemple #17
0
"""
Show a cube for each available color name
"""
print(__doc__)
from vtkplotter import Plotter, Cube, Text2D
from vtkplotter.colors import colors, getColor
from operator import itemgetter

# sorting by hex color code:
sorted_colors = sorted(colors.items(), key=itemgetter(1))
# or by name:
# sorted_colors = sorted(colors.items(), key=itemgetter(0))

vp = Plotter(N=len(sorted_colors), axes=0, size="fullscreen")

for i, sc in enumerate(sorted_colors):
    cname = sc[0]
    rgb = getColor(cname)
    cb = Cube(c=rgb)
    tname = Text2D(cname, pos=3)
    vp.show(cb, tname, at=i)

vp.camera.Azimuth(20)
vp.camera.Elevation(20)

print("click on any cube and press i")
vp.show(interactive=1)
Exemple #18
0
def view_mesh(
    meshes: list,
    output_file: str,
    mesh_names: list = [],
    patient_data="",
    plid="",
    scan_path="",
):
    logging.info("Opening mesh viewer.")
    settings.useDepthPeeling = True
    vmeshes = []

    def slider1(widget, event):
        value = widget.GetRepresentation().GetValue()
        vmeshes[index].color(value)

    def slider2(widget, event):
        value = widget.GetRepresentation().GetValue()
        vmeshes[index].opacity(value)

    def buttonfunc():
        global index
        bu.switch()
        index = mesh_names.index(bu.status())

    def background_swap():
        bg_button.switch()
        vp.backgroundRenderer.SetBackground(colors.getColor(
            bg_button.status()))

    def ar_view():
        save()
        holo_registration_wrapper.start_viewer(output_file, plid)

    def save():
        write_mesh_as_glb_with_colour(vmeshes, output_file)

    def open_scan():
        external_2d_viewer.start(scan_path)

    vp = Plotter(
        sharecam=False,
        bg="./core/client/images/hologram_icon2.png",
        bg2='black',
        shape=[1, 1],
        size=[640, 480],
        interactive=False,
    )

    # pos = position corner number: horizontal [1-4] or vertical [11-14]
    vp.addSlider2D(slider1, -9, 9, value=0, pos=4, title="color number")

    left_side_x = 0.1

    vp.addSlider2D(
        slider2,
        xmin=0.00,
        xmax=1.00,
        value=0.5,
        pos=14,
        c="blue",
        title="alpha value (opacity)",
    )

    bu = vp.addButton(
        buttonfunc,
        pos=(0.5, 0.05),  # x,y fraction from bottom left corner
        states=mesh_names,
        font=font_style,  # arial, courier, times
        size=25,
        bold=True,
        italic=False,
    )

    save_button = vp.addButton(
        save,
        pos=(left_side_x, 0.05),  # x,y fraction from bottom left corner
        states=["Save"],
        font=font_style,  # arial, courier, times
        size=25,
        bold=True,
        italic=False,
    )

    if holo_registration_wrapper.is_supported(plid):
        ar_button = vp.addButton(
            ar_view,
            pos=(left_side_x, 0.20),
            states=["AR View"],
            font=font_style,
            size=25,
            bold=True,
            italic=False,
        )

    if scan_path != "":
        scan_button = vp.addButton(
            open_scan,
            pos=(left_side_x, 0.15),
            states=["2D View"],
            font=font_style,
            size=25,
            bold=True,
            italic=False,
        )

    bg_button = vp.addButton(
        background_swap,
        pos=(left_side_x, 0.10),  # x,y fraction from bottom left corner
        states=["black", "white"],
        font=font_style,
        size=25,
        bold=True,
        italic=False,
    )

    for i in range(0, len(meshes)):
        vmeshes.append(trimesh2vtk(meshes[i], alphaPerCell=True))

    doc = Text2D(patient_data, pos=4, c=(0, 113, 197))

    vp.show(doc)
    vp.backgroundRenderer.GetActiveCamera().Zoom(1.3)

    vp.show(vmeshes)

    interactive()
    calvis.assemble_slice_statistics()

    cc = calvis.chest_circumference()
    ccslice_2D, to_3D = cc.to_planar()
    cc_actor = trimesh2vtk(cc).unpack()[0].lw(2)

    wc = calvis.waist_circumference()
    wcslice_2D, to_3D = wc.to_planar()
    wc_actor = trimesh2vtk(wc).unpack()[0].lw(2)

    pc = calvis.pelvis_circumference()
    pcslice_2D, to_3D = pc.to_planar()
    pc_actor = trimesh2vtk(pc).unpack()[0].lw(2)

    text = Text2D("Subject no. %s" % (i + 1))

    # Print info
    #print("Chest circunference length is: %s" % ccslice_2D.length)
    #print("Waist circunference length is: %s" % wcslice_2D.length)
    #print("Pelvis circunference length is: %s" % pcslice_2D.length)

    # View the human dimensions
    slices = []
    slices.append(cc)
    slices.append(wc)
    slices.append(pc)

    human = vp.load(meshpath)

    vp.show(human.alpha(0.4), cc_actor, wc_actor, pc_actor, text, at=i)
Exemple #20
0
'''from vtkplotter import *
for i in range(10):
    Cone().x(i) # no variable assigned!
show(...) # show all sofar created objs
'''
from vtkplotter import Cone, Text2D, show

for i in range(10):
    Cone().x(2 * i).color(i)  # no variable assigned

Text2D(__doc__, font='courier')

# three points, aka ellipsis, retrieves the list of all created objects
show(..., axes=1, viewup='z')
Exemple #21
0
"""Show some text as a corner annotation.
Fonts: arial, courier, times.
"""
from vtkplotter import show, Text2D, Cube

with open("annotations.py") as fname:
    t = fname.read()

txt2d = Text2D(t, pos=3, s=1.2, c='k', bg="lb", font="courier")

show(txt2d, Cube(), verbose=0, axes=0)
Exemple #22
0
"""Generate 3 random sets of points and align
them using Procrustes method.
"""
from __future__ import division, print_function
from random import uniform as u

from vtkplotter import Plotter, alignProcrustes, Text2D, Points

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

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)]

vpts1 = Points(pts1, c="r").legend("set1")
vpts2 = Points(pts2, c="g").legend("set2")
vpts3 = Points(pts3, c="b").legend("set3")

vp.show(vpts1, vpts2, vpts3, Text2D(__doc__), at=0)

# find best alignment among the n sets of Points,
# return an Assembly object formed by the aligned sets
aligned = alignProcrustes([vpts1, vpts2, vpts3])

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

vp.show(aligned, at=1, interactive=1)
Exemple #23
0
"""
Generate the isosurfaces corresponding to a set of thresholds.
(These surfaces are not separate meshes).
"""
from vtk import vtkQuadric, vtkSampleFunction

# Quadric definition. This is a type of implicit function.
quadric = vtkQuadric()
quadric.SetCoefficients(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0)

# the vtkSampleFunction evaluates quadric over a volume
sample = vtkSampleFunction()
sample.SetSampleDimensions(40, 40, 40)
sample.SetImplicitFunction(quadric)
sample.Update()

img = sample.GetOutput()  # vtkImageData
print("Scalar Range", img.GetScalarRange(), "\ntry press shift-x.")

########################
from vtkplotter import show, Text2D, Volume

# generate an isosurface the volume for each thresholds
ts = [0.1, 0.25, 0.4, 0.6, 0.75, 0.9]

# Use c=None to use the default vtk color map. isos is of type Mesh
isos = Volume(img).isosurface(threshold=ts)

show(isos, Text2D(__doc__))
Exemple #24
0
"""Example that shows how to draw very large number of
spheres (same for Points, lines) with different colors
or different radius."""
from vtkplotter import show, Spheres, Text2D
from random import gauss

N = 40000

cols = range(N)  # color numbers
pts = [(gauss(0, 1), gauss(0, 2), gauss(0, 1)) for i in cols]
rads = [abs(pts[i][1]) / 10 for i in cols]  # radius=0 for y=0

# all have same radius but different colors:
s0 = Spheres(pts, c=cols, r=0.1, res=3)  # res= theta-phi resolution

# all have same color but different radius along y:
s1 = Spheres(pts, r=rads, c="lb", res=8)

print("..rendering spheres:", N * 2)
show(s0, at=0, N=2, axes=2, viewup=(-0.7, 0.7, 0))
show(s1, Text2D(__doc__), at=1, zoom=1.5, interactive=1)
Exemple #25
0
pts_actors_eu = vp.actors  # save a copy of the actors list
pts_actors_eu[0].legend = "Euler method"

vp.actors = []  # clean up the list

for i in x:
    vp += Point([i, 0, 0], c="red", r=6)
pts_actors_rk = vp.actors  # save a copy of the actors list
pts_actors_rk[0].legend = "Runge-Kutta4"

# merge the two lists and set it as the current actors
vp.actors = pts_actors_eu + pts_actors_rk

# let's also add a fancy background image from wikipedia
vp.load(datadir+"images/wave_wiki.png", alpha=0.8).scale(0.4).pos(0,-100,-20)
vp += Text2D(__doc__, c='b')

pb = ProgressBar(0, Nsteps, c="red", ETA=1)
for i in pb.range():
    y_eu = positions_eu[i]  # retrieve the list of y positions at step i
    y_rk = positions_rk[i]
    for j, act in enumerate(pts_actors_eu):
        act.pos(j, y_eu[j], 0)
    for j, act in enumerate(pts_actors_rk):
        act.pos(j, y_rk[j], 0)
    if i%10 ==0:
        vp.show()
    pb.print("Moving actors loop")

vp.show(interactive=1)
Exemple #26
0
    s = shape.clone().pos(0, i * 2.2, 0)

    # colorize cells
    scals = range(s.NCells())
    s.cellColors(scals, cmap=cmaps[i])

    # Or
    # colorize vertices:
    #scals = s.points()[:,i]  # define some dummy point scalar
    #s.pointColors(scals, cmap=cmaps[i])

    ms.append(s)

# use flat shading and add a 2D scalar bar to first mesh
ms[0].flat().addScalarBar(title="my scalarbar\nnumber #0", c="k")

# add 3D scalar bars
ms[1].addScalarBar3D(pos=(1.0, 2.2, -2.), c="k")
ms[2].addScalarBar3D(
    pos=(1, 0, -5),
    c="k",
    sy=2.8,  # change y-size
    title="A viridis 3D\nscalarbar to play with",
    titleXOffset=-2,  # offset of labels
    titleSize=1.5).rotateX(90)  # make it vertical

show(ms, Text2D(__doc__), axes=1, viewup='z')

# can save colors to vtk or ply format:
#ms[1].write('lamp.ply', binary=False)
Exemple #27
0
"""A simple scatter plot with plotxy()"""
from vtkplotter import plot, show, Text2D
import numpy as np

x = np.random.randn(100) + 10
y = np.random.randn(100) * 20

plt = plot(
    x,
    y,
    line=False,
    xtitle="variable x",
    ytitle="variable y",
    aspect=4 / 3,  # aspect ratio
    marker="*",  # marker style
    mc="dr",  # marker color
    axes=True,
)

# show Assembly object and lock interaction to 2d:
# (can zoom in a region w/ mouse, press r to reset)
show(plt, Text2D(__doc__), viewup='2d')
Exemple #28
0
"""Closing the Rendering Window

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

mesh = Paraboloid()

vp1 = show(mesh, Text2D(__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
vp2 = Plotter(title='Second Plotter instance', pos=(500,0))
vp2.show(vp1.actors[0].color('red'))
Exemple #29
0
"""
How to share the same color map
across different meshes.
"""
from vtkplotter import load, Text2D, show, datadir


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

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

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

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

show([[man1, Text2D(__doc__)], man2], N=2, elevation=-40)
Exemple #30
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, Text2D

# 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, Text2D(__doc__), axes=1)