Exemplo n.º 1
0
    def visualise_embedding(self, embedding, labels, title=None):
        cprint(
            "Visualising results of UMAP embedding [press q or esc to close]",
            color="green")
        if embedding.shape[1] > 3:
            cprint("cannot plot wiht >3 components, skipping",
                   "red",
                   attrs=['bold'])
            return

        elif embedding.shape[1] == 3:
            # Plot spehres with vtkplotter
            pts = [(embedding[i, 0], embedding[i, 1], embedding[i, 2])
                   for i in range(len(labels))]

            if not self.use_tsne:
                radius = .1
            else:
                radius = 1

            s0 = Spheres(pts, c=labels, r=radius, res=4, alpha=.7)
            show(s0, axes=1, bg='white')
        else:
            umap.plot.points(self.umapper, labels=labels, theme='fire')
            plt.show()
Exemplo n.º 2
0
    def show_one_timestep(self, date):

        # Visualize the exposed zones for one time step

        date_to_vis = datetime.datetime.strptime(date, '%m/%d/%Y %H:%M:%S')
        print("You are visualizing: ",
              date_to_vis.strftime("%b %d %Y %H:%M:%S"))

        ind_date_to_vis = np.where(
            date_to_vis.strftime("%b %d %Y %H:%M:%S") == np.array(
                self.timeline))[0][0]

        ray_directions = self.directions[ind_date_to_vis]

        ray_directions = -np.ones(
            (self.posture.number_faces, 3)) * ray_directions
        ray_origins = self.posture.get_triangles_center - \
        ray_directions*self.posture.get_max_bounds

        inf = self.posture.get_posture.ray.intersects_first(
            ray_origins=ray_origins, ray_directions=ray_directions)

        expo_mask = (inf == np.arange(self.posture.number_faces))

        col = np.zeros((self.posture.number_faces, 3))  # Black color
        col[expo_mask] = [255, 255, 255]  #White color

        vtkmeshes = trimesh2vtk(self.posture.get_posture)
        vtkmeshes.cellColors(col, cmap='Greys_r')
        show(vtkmeshes)
Exemplo n.º 3
0
def showSolution3D(S, start, goal):
    from vtkplotter import Text, Cube, Line, Grid, mergeActors, 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 = mergeActors(cubes).clean().texture('metal2')

    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.wireframe(False).cellColors(gradient, cmap='gist_earth_r')
    grd.addScalarBar(title='Gradient', horizontal=True)

    txts.append(Text(__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, bg='white', axes=0, zoom=1.2)
Exemplo n.º 4
0
 def show(self):
     vplt.show(self.wall,
               self.obs,
               self.lexus,
               interactive=0,
               camera={
                   'pos': [-0.114, -21.332, 35.687],
                   'focalPoint': [9.611, 2.363, 0.07],
                   'viewup': [0.267, 0.767, 0.583],
                   'distance': 43.871,
                   'clippingRange': [33.465, 57.074]
               })
def plot_stl_vertices_klast(struct_seg, num_segments, color_segmetns,
                            surface_seg, vertices, y_kmeans, title):
    """Функция для прорисовки вершин stl объекта, основанных на цвете по кривизне"""
    for j in range(struct_seg.shape[0]):
        for i in range(num_segments.shape[0]):
            faces = copy.deepcopy(surface_seg[j][i][0])
            mesh = trimesh.Trimesh(vertices=vertices,
                                   faces=faces,
                                   process=False)

            vtkmeshes = trimesh2vtk(mesh)

            vtkmeshes.pointColors(y_kmeans, cmap='jet')

            vtkmeshes.addScalarBar(title="Cmin-Cmax_k_means")
            show(vtkmeshes)
Exemplo n.º 6
0
	def render(self, interactive=True, video=False, camera=None, zoom=None, **kwargs):
		"""
		Takes care of rendering the scene
		"""
		self.apply_render_style()

		if not video:
			if not self.jupyter: # cameras work differently in jupyter notebooks?
				if camera is None:
					camera = self.camera
				
				if isinstance(camera, (str, dict)): # otherwise assume that it's vtk.camera
					camera = check_camera_param(camera)
					
				set_camera(self, camera)

			if interactive:
				if self.verbose and not self.jupyter:
					print(brainrender.INTERACTIVE_MSG)
				elif self.jupyter:
					print("The scene is ready to render in your jupyter notebook")
				else:
					print("\n\nRendering scene.\n   Press 'q' to Quit")

			self._get_inset()

		if zoom is None and not video:
			if brainrender.WHOLE_SCREEN:
				zoom = 1.85
			else:
				zoom = 1.5
		
		# Make mesh labels follow the camera
		if not self.jupyter:
			for txt in self.actors['labels']:
				txt.followCamera(self.plotter.camera)
			


		self.is_rendered = True
		if not self.jupyter:
			if interactive and not video:
				show(*self.get_actors(), interactive=False, zoom=zoom, 
							bg=brainrender.BACKGROUND_COLOR, axes=self.plotter.axes)
			elif video:
				show(*self.get_actors(), interactive=False, 
							bg=brainrender.BACKGROUND_COLOR,
							offscreen=True, zoom=zoom, axes=self.plotter.axes)
			else:
				show(*self.get_actors(), interactive=False,  offscreen=True, zoom=zoom, 
							bg=brainrender.BACKGROUND_COLOR, axes=self.plotter.axes)

			if interactive and not video:
				show(*self.get_actors(), interactive=True, bg=brainrender.BACKGROUND_COLOR,
							axes=self.plotter.axes)
Exemplo n.º 7
0
    def show_beta_coefficients(self, beta_coeff):
        """
		beta_coeff can be diff or refl
		"""
        if (beta_coeff == 'diff'):
            this_beta = self.beta_coeff[:, 0]
        elif (beta_coeff == 'refl'):
            this_beta = self.beta_coeff[:, 1]
        else:
            raise TypeErro("Value not recognise! It can be 'diff' or 'refl'")

        this_beta = this_beta / pi

        vtkmeshes = trimesh2vtk(self.my_file)
        vtkmeshes.cellColors(this_beta, cmap='jet', vmin=0., vmax=1.)
        vtkmeshes.addScalarBar(title="Beta coefficients")

        show(vtkmeshes)
Exemplo n.º 8
0
    def learn(self, n_epoch=10000, sigma=(0.25, 0.01), lrate=(0.5, 0.01)):

        t = np.linspace(0, 1, n_epoch)
        lrate = lrate[0] * (lrate[1] / lrate[0])**t
        sigma = sigma[0] * (sigma[1] / sigma[0])**t
        I = np.random.randint(0, len(self.samples), n_epoch)
        self.samples = self.samples[I]
        pts = Points(self.samples, r=2)
        doc = Text(__doc__)

        pb = ProgressBar(0, n_epoch)
        for i in pb.range():
            pb.print("epochs")
            # Get random sample
            data = self.samples[i]

            # Get index of nearest node (minimum distance)
            winner = np.argmin(((self.codebook - data)**2).sum(axis=-1))

            # Gaussian centered on winner
            G = np.exp(-self.distance[winner]**2 / sigma[i]**2)

            # Move nodes towards sample according to Gaussian
            self.codebook -= lrate[i] * G[...,
                                          np.newaxis] * (self.codebook - data)

            # Draw network
            if i > 500 and not i % 20 or i == n_epoch - 1:
                x, y, z = [self.codebook[:, i].reshape(n, n) for i in range(3)]
                grd = Grid(resx=n - 1,
                           resy=n - 1).wire(False).lw(0.5).bc('lightblue')
                for i in range(n):
                    for j in range(n):
                        grd.setPoint(i * n + j, (x[i, j], y[i, j], z[i, j]))
                show(doc,
                     pts,
                     grd,
                     axes=6,
                     bg='w',
                     azimuth=2,
                     interactive=False)

        return [self.codebook[:, i].reshape(n, n) for i in range(3)]
Exemplo n.º 9
0
    def show_one_timestep_received(self, one_timestep):

        #row is timestep
        #column is triangle
        file_out_full = "output/{}_fullBody.txt".format(self.output_name)

        total_body_output = np.loadtxt(file_out_full)

        if (one_timestep < 0 or one_timestep > np.shape(total_body_output)[0]):
            raise TypeError("Timestep must be smaller than {}".format(
                np.shape(total_body_output)[0]))

        col = total_body_output[one_timestep - 1, :]

        vtkmeshes = trimesh2vtk(self.posture.get_posture)
        vtkmeshes.cellColors(col, cmap='jet')
        vtkmeshes.addScalarBar(title="J/m^2")

        show(vtkmeshes)
def plot_stl_faces_color_curvature(struct_seg, num_segments, surface_seg,
                                   vertices, curvature_face_klast, title):
    """Функция для прорисовки фасет stl объекта, основанных на цвете по кривизне для каждой фасеты"""
    for j in range(struct_seg.shape[0]):
        for i in range(num_segments.shape[0]):
            faces = copy.deepcopy(surface_seg[j][i][0])
            meshes = [
                trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
                for i in range(2)
            ]

            Cmin1, Cmax1 = copy.deepcopy(
                curvature_face_klast[:, 0]), copy.deepcopy(
                    curvature_face_klast[:, 1])
            #np.max(Cmin1)-np.min(Cmin1)
            meshes[0].visual.face_colors = trimesh.visual.interpolate(
                curvature_face_klast[:, 0], color_map='jet')
            meshes[1].visual.face_colors = trimesh.visual.interpolate(
                curvature_face_klast[:, 1], color_map='jet')
            # create a scene containing the mesh and colorbar
            # pyplot.pcolor(Cmin1)
            #pyplot.colorbar()
            #scene = trimesh.Scene([mesh])
            # setup the normalization and the colormap
            normalize = mcolors.Normalize(vmin=np.min(Cmin1),
                                          vmax=np.max(Cmin1))
            colormap = cm.jet
            scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=colormap)
            scalarmappaple.set_array(Cmin1)
            pyplot.colorbar(scalarmappaple)
            vtkmeshes = [trimesh2vtk(m) for m in meshes]
            vtkmeshes[0].addScalarBar(title="Cmin")
            vtkmeshes[1].addScalarBar(title="Cmax")
            #vp = Plotter(title="Cmin", interactive=0, axes=3)
            #vp +=vtkmeshes
            #vp.show(resetcam=0)
            #vp.show()
            show([vtkmeshes[0], vtkmeshes[1]],
                 interactive=0,
                 N=2,
                 bg='w',
                 axes=1)  #bg2='wheat',
def plot_stl_vertices_curvature(struct_seg, num_segments, color_segmetns,
                                surface_seg, vertices, Cmin, Cmax, title):
    """Функция для прорисовки вершин stl объекта, основанных на цвете по кривизне"""
    for j in range(struct_seg.shape[0]):
        for i in range(num_segments.shape[0]):
            faces = copy.deepcopy(surface_seg[j][i][0])
            mesh = trimesh.Trimesh(vertices=vertices,
                                   faces=faces,
                                   process=False)

            vtkmeshes = trimesh2vtk(mesh)
            vtkmeshes1 = trimesh2vtk(mesh)

            # vtkmeshes.pointColors(Cmin, cmap='jet')
            Cmin1, Cmax1 = copy.deepcopy(Cmin), copy.deepcopy(Cmax)
            min_max_Cmin = np.array(
                [np.mean(Cmin) - np.std(Cmin),
                 np.mean(Cmin) + np.std(Cmin)])
            min_max_Cmax = np.array(
                [np.mean(Cmax) - np.std(Cmax),
                 np.mean(Cmax) + np.std(Cmax)])
            for i in range(Cmin.shape[0]):
                if Cmin1[i] > min_max_Cmin[1]:
                    Cmin1[i] = min_max_Cmin[1]
                elif Cmin1[i] < min_max_Cmin[0]:
                    Cmin1[i] = min_max_Cmin[0]
                if Cmax1[i] > min_max_Cmax[1]:
                    Cmax1[i] = min_max_Cmax[1]
                elif Cmax1[i] < min_max_Cmax[0]:
                    Cmax1[i] = min_max_Cmax[0]

            vtkmeshes.pointColors(Cmin1, cmap='jet')

            vtkmeshes1.pointColors(Cmax1, cmap='jet')

            vtkmeshes.addScalarBar(title="Cmin")
            vtkmeshes1.addScalarBar(title="Cmax")
            show([vtkmeshes, vtkmeshes1], N=2, bg='w', axes=1)
Exemplo n.º 12
0
def visualize_grasp(mesh, vertices, pose):
    """Visualizes a grasp on an object. Object specified by a mesh, as
    loaded by trimesh. vertices is a pair of (x, y, z) contact points.
    pose is the pose of the gripper tip.
    """
    p1, p2 = vertices
    center = (p1 + p2) / 2
    approach = pose[:3, 2]
    tail = center - GRIPPER_LENGTH * approach

    contact_points = []
    for v in vertices:
        contact_points.append(vtkplotter.shapes.Point(pos=v, r=30))

    vec = (p1 - p2) / np.linalg.norm(p1 - p2)
    line = vtkplotter.shapes.Tube([
        center + 0.5 * MAX_GRIPPER_DIST * vec,
        center - 0.5 * MAX_GRIPPER_DIST * vec
    ],
                                  r=0.001,
                                  c='g')
    approach = vtkplotter.shapes.Tube([center, tail], r=0.001, c='g')
    vtkplotter.show([mesh, line, approach] + contact_points, newPlotter=True)
Exemplo n.º 13
0
def plot_mesh(mesh, arrows, cones, complete=True, mesh2=None):
    """ Plot mesh.

    Args:
        mesh (vedo.pointcloud.Points): Mesh object.
        arrows (vedo.shapes.Arrows): Load arrows.
        cones (vedo.shapes.Cones): Cones to represent constrain nodes.
        complete (:obj:`bool`, optional): If true plot mesh with loads and constrain nodes. Defaults to True.
        mesh2 (:obj:`vedo.pointcloud.Points`, optional): Mesh without faces. Defaults to None.
    """
    if mesh2 is not None:
        if complete:
            vt.show(mesh, arrows, cones, mesh2, __doc__, viewup='z', axes=4)
        else:
            vt.show(mesh, mesh2, __doc__, viewup='z', axes=4)
    else:
        if complete:
            vt.show(mesh, arrows, cones, __doc__, viewup='z', axes=4)
        else:
            vt.show(mesh, __doc__, viewup='z', axes=4)
Exemplo n.º 14
0
#g = Graph(layout='2d', zrange=7)
g = DirectedGraph(layout='cone')
#g = DirectedGraph(layout='circular3d', height=1, radius=1.5)
#g = DirectedGraph(layout='force')

# Vertex generation is automatic,
#  add a child to vertex0, so that now vertex1 exists
g.addChild(0, edgeLabel="Mother giving birth\nto her little baby cell")
g.addChild(1)
g.addChild(1)
g.addChild(2)
g.addChild(2)
g.addChild(2)
g.addChild(3)
g.addChild(3, edgeLabel="It's a male!")
g.addChild(4)
g.addChild(4)
for i in range(7):
    g.addChild(5, vertexLabel="cell5_" + str(i))
g.addChild(7)
g.addChild(7)
g.addChild(7)

g.build()  # optimize layout

g.unpack(0).color('dg').lineWidth(
    3)  #0=graph, 1=vertexLabels, 2=edgeLabels, 3=arrows
g.unpack(2).color('dr')

show(g, __doc__, axes=9, elevation=-40)
Exemplo n.º 15
0
    acts = []
    acts.append(table1Actor)
    acts.append(table2Actor)
    acts.append(FilingCabinet1Actor)
    acts.append(FilingCabinet2Actor)
    acts.append(bookshelf1TopActor)
    acts.append(bookshelf1BottomActor)
    acts.append(bookshelf1FrontActor)
    acts.append(bookshelf1BackActor)
    acts.append(bookshelf1LHSActor)
    acts.append(bookshelf1RHSActor)
    acts.append(bookshelf2TopActor)
    acts.append(bookshelf2BottomActor)
    acts.append(bookshelf2FrontActor)
    acts.append(bookshelf2BackActor)
    acts.append(bookshelf2LHSActor)
    acts.append(bookshelf2RHSActor)
    acts.append(windowActor)
    acts.append(outletActor)
    acts.append(inletActor)
    acts.append(outlineActor)

    return acts


if __name__ == "__main__":

    from vtkplotter import show

    show(furniture())
Exemplo n.º 16
0
'''
for i in range(10):
    Cone().x(i) # no variable assigned!
show(...) # show all sofar created objs
'''
from vtkplotter import Cone, collection, Text, show

for i in range(10):
    Cone(pos=[2 * i, 0, 0]).color(i)  # no variable assigned

Text(__doc__)

# three points, aka ellipsis, retrieves the list of all created objects
# in python 2 use collection() instead
show(..., axes=1, viewup='z')
Exemplo n.º 17
0
# 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 = 'cross section of the mesh'
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],
                                   heights=z_levels)
N = len(sections)
printc("nr. of sections:", N, c='green')
Exemplo n.º 18
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)
Exemplo n.º 19
0
# test on a sphere mesh
mesh = trimesh.creation.icosphere()

# create some rays
ray_origins = np.array([[0, 0, -3], [1, 2, -3]])
ray_directions = np.array([[0, 0, 1], [0, -1, 1]])

# run the mesh-ray query
locations, index_ray, index_tri = mesh.ray.intersects_location(
    ray_origins=ray_origins, ray_directions=ray_directions)
locs = trimesh.points.PointCloud(locations)

# stack rays into line segments for visualization as Path3D
ray_visualize = trimesh.load_path(
    np.hstack((ray_origins, ray_origins + ray_directions)).reshape(-1, 2, 3))

print("The rays hit the mesh at coordinates:\n", locations)
print("The rays with index: {} hit triangles stored at mesh.faces[{}]".format(
    index_ray, index_tri))

# stack rays into line segments for visualization as Path3D
ray_visualize = trimesh.load_path(
    np.hstack(
        (ray_origins, ray_origins + ray_directions * 5.0)).reshape(-1, 2, 3))

# make mesh white-ish
mesh.visual.face_colors = [200, 200, 250, 100]
mesh.visual.face_colors[index_tri] = [255, 0, 0, 255]

show(mesh, ray_visualize, locs)
Exemplo n.º 20
0
'''
Voronoi in 3D with Voro++ library.
'''
from vtkplotter import voronoi3D, Points, show
import numpy as np

#from vtkplotter import settings
#settings.voro_path = '/g/sharpeba/software/bin'

N = 2000
nuclei = np.random.rand(N, 3) - (0.5, 0.5, 0.5)
ncl = Points(nuclei).clean(0.1)  # clean makes points evenly spaced
nuclei = ncl.points()

mesh = voronoi3D(nuclei, tol=.001)
#print(len(mesh.info['cells']), mesh.info['volumes'])

pts_inside = mesh.insidePoints(nuclei)
inpts = Points(pts_inside, r=50, c='r', alpha=0.2)

show(mesh, inpts)
#        sources.append(p)    # will become much smaller.
#        deltas.append(np.zeros(3))
sources = np.array(sources)
deltas = np.array(deltas)

src = Points(sources, c='r', r=12)
trs = Points(sources + deltas, c='v', r=12)
arr = Arrows(sources, sources + deltas)

################################################# Thin Plate Splines
warped = thinPlateSpline(apos, sources, sources + deltas)
warped.alpha(0.4).color('lg').pointSize(10)
allarr = Arrows(apos.coordinates(), warped.coordinates())

set1 = [apos, warped, src, trs, arr, Text(__doc__, s=1.2)]
vp = show([set1, allarr], N=2, verbose=0)  # returns the Plotter class

################################################# RBF
from scipy.interpolate import Rbf

x, y, z = sources[:, 0], sources[:, 1], sources[:, 2]
dx, dy, dz = deltas[:, 0], deltas[:, 1], deltas[:, 2]

itrx = Rbf(x, y, z, dx)  # Radial Basis Function interpolator:
itry = Rbf(x, y, z, dy)  #  interoplate the deltas in each separate
itrz = Rbf(x, y, z, dz)  #  cartesian dimension

positions_x = itrx(xr, yr, zr) + xr
positions_y = itry(xr, yr, zr) + yr
positions_z = itrz(xr, yr, zr) + zr
positions_rbf = np.vstack([positions_x, positions_y, positions_z])
Exemplo n.º 22
0
"""
Mark a specific point 
on a mesh with some text.
"""
from vtkplotter import Sphere, Point, show, Text

sp = Sphere().wire(True)

pcoords = sp.getPoint(144)

pt = Point(pcoords, r=12, c="white")

tx = Text("my fave\npoint",
          pcoords,
          s=0.1,
          c="lightblue",
          bc="green",
          followcam=False)

show(sp, pt, tx, Text(__doc__), axes=1)
Exemplo n.º 23
0
'''
Split a mesh by connectivity and order the pieces 
by increasing area.
'''
print(__doc__)
from vtkplotter import splitByConnectivity, load, show

blobs = load('data/embryo.tif')

# search up to the 40th subunit of mesh, return a list
# of length 40, but only keep the largest 10:
sblobs = splitByConnectivity(blobs, maxdepth=40)[0:9]

sblobs[0].alpha(0.05)  # make the largest part transparent

show([blobs, sblobs], N=2, zoom=1.2)
Exemplo n.º 24
0
"""
Extracts the cells where scalar value 
satisfies a threshold criterion.
"""
from vtkplotter import load, Text, show, datadir

doc = Text(__doc__)

man = load(datadir+"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, axes=0)
A tiff stack is a set of image slices in z. The scalar value
(intensity of white) is used to create an isosurface by fixing a threshold.
In this example the level of white is in the range 0=black -> 150=white
If threshold=None this is set to 1/3 of the scalar range.

- Setting connectivity to True discards the small isolated pieces of
surface and only keeps the largest connected surface.

- Smoothing applies a gaussian smoothing with a standard deviation
which is expressed in units of pixels.

- If the spacing of the tiff stack is uneven in xyz, this can be
fixed by setting scaling factors with scaling=[xfac,yfac,zfac]
'''
print(__doc__)
from vtkplotter import show, load

# Read volume data from a tif file:
f = 'data/embryo.tif'
a0 = load(f, threshold=80, connectivity=1)
a1 = load(f, threshold=80, connectivity=0)
a2 = load(f, smoothing=2)

vp1 = show([a0, a1, a2], shape=(1, 3), axes=0, interactive=1)

# Can also read SLC files
a3 = load('data/embryo.slc', c='g', smoothing=1, connectivity=1)

# newPlotter triggers the instantiation of a new Plotter object
vp2 = show(a3, verbose=0, pos=(300, 300), newPlotter=True)
Exemplo n.º 26
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')
Exemplo n.º 27
0
'''
Create a set of transparencies which can be passed to method pointColors()
'''
from vtkplotter import load, show, Text

mesh = load('data/beethoven.ply')

# pick y coordinates of vertices and use them as scalars
scals = mesh.coordinates()[:,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)
Exemplo n.º 28
0
"""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)
Exemplo n.º 29
0
"""
Use a scalar to paint colored bands on a mesh,
this can be combined with opacities values for each vertex of the mesh.
Keyword depthpeeling improves the rendering of translucent objects.
"""
from vtkplotter import show, Hyperboloid, Torus, Text
from numpy import linspace

doc = Text(__doc__, c="k", bg="lg")

hyp = Hyperboloid()
scalars = hyp.coordinates()[:, 2]  # let z-coord be the scalar
hyp.pointColors(scalars, bands=5, cmap="rainbow")  # make color bands

tor = Torus(thickness=0.3)
scalars = tor.coordinates()[:, 2]  # let z-coord be the scalar
transp = linspace(1, 0.5, len(scalars))  # set transparencies from 1 -> .5
tor.pointColors(scalars, alpha=transp, bands=3, cmap="winter")

show(hyp, tor, doc, viewup="z", depthpeeling=1, axes=2)
Exemplo n.º 30
0
model = Sequential()
model.add(Dense(neurons, activation="relu", input_dim=3))
model.add(Dense(neurons, activation="relu"))
model.add(Dense(neurons, activation="relu"))
model.add(Dense(1, activation="sigmoid"))

model.compile(optimizer="rmsprop", loss="mse", metrics=["mae"])

model.fit(shuffled_datalist,
          shuffled_scalars,
          epochs=epochs,
          batch_size=max(nx, ny, nz))

predicted_scalars = model.predict(datalist)
model.summary()

idx = 0
vispred = np.zeros([nx, ny, nz])
for i, x in enumerate(lsx):
    for j, y in enumerate(lsy):
        for k, z in enumerate(lsz):
            vispred[i, j, k] = predicted_scalars[idx]
            idx += 1

v1 = Volume(visdata)
v2 = Volume(vispred)
s1 = isosurface(v1, threshold=0).alpha(0.8)
s2 = isosurface(v2, threshold=0).alpha(0.8)

show([v1, v2, s1, s2], N=4, axes=8, bg="w")