def visualize_sampling3D(self, data_dict, only_pc=False): import vtkplotter from matplotlib import cm cmap = cm.get_cmap('jet') samples = data_dict[f'samples_geo'] labels = data_dict[f'labels_geo'] colors = cmap(labels / labels.max())[:, :3] # [-1, 1] points = samples # create plot vp = vtkplotter.Plotter(title="", size=(1500, 1500)) vis_list = [] if not only_pc: # create a mesh mesh = data_dict['mesh'] faces = mesh.faces verts = mesh.verts mesh = trimesh.Trimesh(verts, faces) mesh.visual.face_colors = [200, 200, 250, 255] vis_list.append(mesh) # create a pointcloud pc = vtkplotter.Points(points, r=12, c=np.float32(colors)) vis_list.append(pc) vp.show(*vis_list, bg="white", axes=1, interactive=True)
def visualize_sampling3D(self, data_dict): import vtkplotter samples = data_dict[f'samples_geo'] labels = data_dict[f'labels_geo'] colors = np.stack([labels, labels, labels], axis=1) mesh = data_dict['mesh'] faces = mesh.faces # [-1, 1] points = samples verts = mesh.verts # create plot vp = vtkplotter.Plotter(title="", size=(1500, 1500)) vis_list = [] # create a mesh mesh = trimesh.Trimesh(verts, faces) mesh.visual.face_colors = [200, 200, 250, 255] vis_list.append(mesh) # create a pointcloud pc = vtkplotter.Points(points, r=12, c=np.float32(colors)) vis_list.append(pc) vp.show(*vis_list, bg="white", axes=1, interactive=True)
def main(): vp = vtk.Plotter(size=(800, 800), axes=0, interactive=0) vp += vtk.Grid(sx=2, sy=2) origin = [0, 0, 0] #Define hypercube (shown in red in visualization) A = np.array([[p, p, 0], [p, -p, 0], [-p, p, 0], [-p, -p, 0]]).astype("float").T """ Conceptually: How much a vector is allowed to go in the direction of the corresponding hypercube axis """ b = np.array([[2], [4], [9], [1]]) #add a bunch of x vectors with 0 in z direction xs = np.random.normal(size=(num_vecs, 2)) z = np.zeros((num_vecs, 1)) xs = np.block([xs, z]) #all the vectors that obey the constrains s = np.array( [x for x in xs if np.all(np.greater(np.ravel(b), np.ravel(x @ A)))]) #add the constrain obeying vectors to the visualization vp += [vtk.shapes.Tube([origin, np.ravel(x)], r=0.001, c="b") for x in s] #add the hypercube defining vectors to the visualization vp += [vtk.shapes.Tube([origin, np.ravel(a)], r=0.01, c="r") for a in A.T] #show visualization vp.show(interactive=1)
def build_keyboard(self): print('Building Keyboard..') nts = ("C","D","E","F","G","A","B") tol = 0.12 keybsize = 16.5 #cm, span of one octave wb = keybsize/7. nr_octaves = 7 span = nr_octaves*wb*7. self.vp = vtkplotter.Plotter(title='Piano Keyboard', axes=0, size=(1200,600), bg='lb', verbose=0) #wooden top and base self.vp.box(pos=(span/2+keybsize, 6, 1), length=span+1, height=3, width= 5, texture='wood5') #top self.vp.box(pos=(span/2+keybsize, 0, -1), length=span+1, height=1, width=17, texture='wood5') self.vp.text(version, pos=(18,5.5,2.), depth=.7) #leggio leggio = self.vp.box(pos=(span/1.6,8,10), length=span/2, height=span/8, width=0.08, c=(1,1,0.9)) leggio.rotateX(angle=-20) for ioct in range(nr_octaves): for ik in range(7): #white keys x = ik * wb + (ioct+1.)*keybsize +wb/2. tb = self.vp.box(pos=(x,-2,0), length=wb-tol, height=1, width=12, c=(1,1,1)) self.KB.update({nts[ik]+str(ioct+1) : tb}) if not nts[ik] in ("E","B"): #black keys tn=self.vp.box(pos=(x+wb/2,-0, 1), length=wb*.6, height=1, width=8, c=(0,0,0)) self.KB.update({nts[ik]+"#"+str(ioct+1) : tn})
def main(): vp = vtk.Plotter(size=(1080, 720), axes=0, interactive=0) map = Map(vp) #follow_path(vp, map) #go_around_box(vp, map) go_around_moving_box(vp, map) vp.show(interactive=1)
def plot_mask3D(mask=None, title="", point_coords=None, figsize=1500, point_marker_size=8, interactive=True): ''' Simple plotting tool to show intermediate mask predictions and points where PointRend is applied. Args: mask (Tensor): mask prediction of shape DxHxW title (str): title for the plot point_coords ((Tensor, Tensor, Tensor)): x and y and z point coordinates figsize (int): size of the figure to plot point_marker_size (int): marker size for points ''' import trimesh import vtkplotter from skimage import measure vp = vtkplotter.Plotter(title=title, size=(figsize, figsize)) vis_list = [] if mask is not None: mask = mask.detach().to("cpu").numpy() mask = mask.transpose(2, 1, 0) # marching cube to find surface verts, faces, normals, values = measure.marching_cubes_lewiner( mask, 0.5, gradient_direction='ascent') # create a mesh mesh = trimesh.Trimesh(verts, faces) mesh.visual.face_colors = [200, 200, 250, 100] vis_list.append(mesh) if point_coords is not None: point_coords = torch.stack(point_coords, 1).to("cpu").numpy() # import numpy as np # select_x = np.logical_and(point_coords[:, 0] >= 16, point_coords[:, 0] <= 112) # select_y = np.logical_and(point_coords[:, 1] >= 48, point_coords[:, 1] <= 272) # select_z = np.logical_and(point_coords[:, 2] >= 16, point_coords[:, 2] <= 112) # select = np.logical_and(np.logical_and(select_x, select_y), select_z) # point_coords = point_coords[select, :] pc = vtkplotter.Points(point_coords, r=point_marker_size, c='red') vis_list.append(pc) vp.show(*vis_list, bg="white", axes=1, interactive=interactive, azimuth=30, elevation=30)
def __init__(self): self.lexus = vplt.load(absfilepath("data/lexus_hs.obj")).scale([ 0.01, 0.01, 0.01 ]).texture(absfilepath("data/lexus_hs_diffuse.jpg")).rotateZ(180) self.plotter = vplt.Plotter(bg='white', axes={ 'xyGrid': True, 'zxGrid2': True, 'showTicks': True }) self.goal = vplt.Sphere(pos=(0, 0, 0.2), r=0.2, c="gold", alpha=0.3) self.obstacles = []
def __init__(self): self.wall = vplt.load( absfilepath("data/walls.stl")).c("green").alpha(0.2).addShadow( z=-0.5) self.obs = vplt.load( absfilepath("data/obs.stl")).c("red").addShadow(z=-0.5) self.lexus = vplt.load(absfilepath("data/lexus_hs.obj")).scale([ 0.01, 0.01, 0.01 ]).texture(absfilepath("data/lexus_hs_diffuse.jpg")).rotateZ(180) self.plotter = vplt.Plotter(bg='white', axes={ 'xyGrid': True, 'zxGrid2': True, 'showTicks': True })
def animation(coord, connect, amp, disp_vector): ''' Plot deformed mesh animation. Args: coord (:obj:`numpy.array`): Coordinates of the element. connect (:obj:`numpy.array`): Element connectivity. amp (:obj:`int`): Amplitude. disp_vector (:obj:`numpy.array`): Displacement. ''' vt.printc("Press F1 to exit.", c="red", invert=1) vp = vt.Plotter(axes=0, interactive=0) vp += __doc__ ind_faces_U = free_faces(coord, connect) aux = np.linspace(-1, 1, num=400) factor = amp * np.sin(aux * 2 * np.pi) while True: for f in factor: coord3D_U = fc.apply_U(disp_vector, coord, factor=f) verts_U = coord3D_U[:, 1:] mesh = build_mesh(verts_U, ind_faces_U) vp.clear() vp.add(mesh) vp.show()
There is another ipynb file which shows how to visualize such models in a jupyter notebook """ import pynoddy import pynoddy.output import vtkplotter as vtkP # Determine the path to the noddy file #(comment the first line and uncomment the second line to see the second model # The second model takes around a minute to generate) modelfile = 'examples/strike_slip.his' #modelfile = 'examples/Scenario3_MedResolution.his' # Determine the path to the noddy executable noddy_path = 'noddyapp/noddy_win64.exe' # Where you would like to place all your output files outputfolder = 'sandbox/' # create a plot in vtkplotter plot = vtkP.Plotter(axes=1, bg='white', interactive=1) # call the plotting function points = pynoddy.output.CalculatePlotStructure(modelfile, plot, noddy_path, outputfolder=outputfolder, LithologyOpacity=0.2, outputOption=0) plot.show(viewup='z')
import vtkplotter vp = vtkplotter.Plotter() # alpha value (opacity) can be put in color string separated by space,/ car = vp.load('data/shapes/porsche.ply', c='gold, 0.1') s = vp.sphere(r=4, c='v/0.1', wire=1) # color is violet with alpha=0.1 # Intersect car with sphere, c=black, lw=line width contour = vtkplotter.analysis.surfaceIntersection(car, s, c='k', lw=4) vp.show([car, contour, s], zoom=1.3)
def view_3d(path): p = vp.Plotter(title='3D Model viewer') # .color('blue').wireframe(True).alpha(0.05).normalize().print() p.load(path) # p.load(output_model).color('red').wireframe(True).alpha(0.05)#.print() p.show()
# # Normal jpg/png images can be loaded and rendered as any vtkImageActor # import vtkplotter vp = vtkplotter.Plotter(axes=3) for i in range(5): a = vp.load('data/images/dog.jpg') a.scale(1 - i / 10.) # image can be scaled in size a.rotateX(20 * i).pos([0, 0, 30 * i]) # can concatenate methods vp.show()
## Example # make a textured floor, a lamp post, and load a mesh of a car # make copies of the car, rotate and move them in a loop # vp.render() is used inside the loop, itadds the actor to list vp.actors, # rate=10 limits the speed of the loop to maximum 10 fps from __future__ import division, print_function import vtkplotter vp = vtkplotter.Plotter(verbose=0, axes=0) vp.plane(pos=(4, 0, -.45), sx=12, texture='metalfloor1') # load and set its position (methods can be concatenated) vp.load('data/shapes/lamp.vtk').pos([1.7, -0.4, 2]) a = vp.load('data/shapes/porsche.ply', c='r').rotateX(90) a.normalize() # set actor at origin and scale size to 1 print('Scene is ready, press q to continue') vp.show() for i in range(1, 10): b = a.clone(c='aqua', alpha=.04 * i) b.rotateX(-20 * i).rotateY(-10 * i).pos([i, i / 2, i / 2]) vp.render(b, rate=10) # add actor b, maximum frame rate in hertz print(i, 'time:', vp.clock, 's') vp.show()
# In this example we fit spheres to a region 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 sphere. # Red lines join the center of the sphere to the surface point. # 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 import vtkplotter from vtkplotter.analysis import fitSphere vp = vtkplotter.Plotter(verbose=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.actors.append(sph) vp.points(pts) vp.line(sph.center, p, lw=2) reds.append(sph.residue) invr.append(1 / sph.radius**2)
vp, grid, constraints, OPEN, CLOSED, closed_disc, open_disc, OPEN_l, curr, start_pos, goal_pos) print("No path found!") return None ### TASKS ### #1) given a node, check if it is in the closed set #2) check if grid position is an obstacle (DO LAST) #3) given a node's discrete position, check if this discrete position is in the open set #4) replace item in set #5) remove node with smallest f if __name__ == "__main__": vp = vtk.Plotter(size=(1080, 720), axes=0, interactive=0) start = [10, 10, 0, 0] goal = [15, 15, 1, 0] vp += [vtk.shapes.Circle(start[:2] + [0], c="blue", alpha=1, r=.1)] vp += [vtk.shapes.Circle(goal[:2] + [0], c="blue", alpha=1, r=.1)] path = hybrid_a_star(vp, None, None, start, goal) #<- [[x,y,t,p], [x,...]...] for p in path: x = p[:2] + [0] vp += [vtk.shapes.Circle(x, c="blue", alpha=1, r=.08)] vp.show(interactive=1)
# Example for function() method. # Draw a surface representing the 3D function specified as a string # or as a reference to an external already existing function. # Red points indicate where the function does not exist. # import math import vtkplotter def my_z(x,y): return math.sin(2*x*y) * math.cos(3*y)/2 vp = vtkplotter.Plotter(shape=(2,2), axes=2, sharecam=False) # draw at renderer nr.0 the first actor, show it with a texture # an existing function z(x,y) can be passed: f1 = vp.fxy(my_z, texture='paper') vp.show(f1, at=0) # c=None shows the original z-scalar color scale. No z-level lines. f2 = vp.fxy(lambda x,y: math.sin(x*y), c=None, zlevels=None, texture=None, wire=1) vp.show(f2, at=1) # red dots are shown where the function does not exist (y>x): # if vp is set to verbose, sympy calculates derivatives and prints them: f3 = vp.fxy('sin(3*x)*log(x-y)/3') vp.show(f3, at=2) # specify x and y ranges and z vertical limits: f4 = vp.fxy('log(x**2+y**2 - 1)', x=[-2,2], y=[-2,2], zlimits=[-1,1.5])
# Text jutification and positioning. # (center, top-left, top-right, bottom-left, bottom-right) import vtkplotter vp = vtkplotter.Plotter(axes=8, verbose=0) txt = 'I like\nto play\nguitar' vp.text(txt, pos=[1, 2, 0], s=0.2, c=3, bc=1, depth=0.2, justify='top-left') vp.point([1, 2, 0], c='r') # mark text origin vp.point([0, 0, 0]) # mark axes origin vp.show()
# Find the postsynaptic cell ID with the most synapses that are manually annotated. all_man_syn["syn_num"] = all_man_syn.groupby( "post_pt_root_id")["id"].transform(len) cellid = all_man_syn[all_man_syn.syn_num == 34]["post_pt_root_id"].values[0] print(cellid) # Visualize the cell. mm = trimesh_io.MeshMeta(disk_cache_path="test/test_files") mesh = mm.mesh( filename= "/data/dynamic_brain_workshop/electron_microscopy/2019/meshes/%d.h5" % cellid) mesh_poly = trimesh_vtk.trimesh_to_vtk(mesh.vertices, mesh.faces, None) plt_actor = vtkplotter.Actor(mesh_poly) vtkplotter.embedWindow(backend="k3d") vp = vtkplotter.Plotter(bg="b") myactor = vtkplotter.Actor(plt_actor, c="r") myactor.GetMapper().Update() vp += myactor vp.show() # Find 10 largest synapses automatically extracted on this cell. post_synapse_df = dl.query_synapses("pni_synapses_i3", post_ids=np.array([cellid])) biggest_synapses = post_synapse_df.sort_values(by=["size"], ascending=False).head(10) print(biggest_synapses) # Visualize. mm = trimesh_io.MeshMeta(disk_cache_path="test/test_files") mesh = mm.mesh(
import vtkplotter vp = vtkplotter.Plotter(bg='black', axes=0, verbose=0) # moon to real scale: e = vtkplotter.shapes.earth(r=6371) # km m = vtkplotter.shapes.sphere(pos=[384402, 0, 0], r=1737, c='gray') vp.show([e, m], zoom=0.8)
# Example for delaunay2D() and cellCenters() # import vtkplotter from vtkplotter.analysis import delaunay2D vp = vtkplotter.Plotter(shape=(1, 2), interactive=0) d0 = vp.load('data/250.vtk', edges=1, 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)
import matplotlib.pylab as plt import matplotlib.patches as mpatches from itertools import cycle import vtkplotter as vtk from usefull_features import group_by import numpy as np import scipy.optimize as opt p = vtk.Plotter(shape=(1, 2), bg='white', axes=1) a = vtk.load('tayl.stl') sc = [c[1] for c in a.getPoints()] a.pointColors(sc) b = a.ybounds() i = a.isolines(200, b[0], b[1]) i2 = a.isolines(50, b[1]*0.7, b[1]).clean() ii = i.clean() ii2 = i2.clean() pnts1 = np.array([tuple(p) for p in ii.getPoints()], dtype=[ ('x', float), ('y', float), ('z', float)]) pnts2 = np.array([tuple(p) for p in ii2.getPoints()], dtype=[ ('x', float), ('y', float), ('z', float)]) g1 = group_by(pnts1, by='y', crit=1e-3) g2 = group_by(pnts2, by='y', crit=1e-3) p.show(a, i, i2, at=0, N=2) p.show(vtk.Points(ii.getPoints()), vtk.Points(i2.getPoints()), vtk.Points(g1[10].tolist(), c='green'), vtk.Points(g1[0].tolist(), c='red'), at=1, interactive=True) N = 10 z = []
""" Script for visualizing subject's cortical surface and the implanted electrodes. """ import vtkplotter as vp from util.surface import Surface from util.contacts import Contacts subject = "id001" surf = Surface.from_npz_file(f"data/Geometry/{subject}/surface.npz") contacts = Contacts(f"data/Geometry/{subject}/seeg.txt") mesh = vp.Mesh([surf.vertices, surf.triangles], alpha=0.1) points = vp.Points(contacts.xyz, r=20, c=(1, 1, 0)) vplotter = vp.Plotter(axes=0) vplotter.show([mesh, points])
#dmc.GenerateValues(1, 3, 3) # To get the tibia bone #dmc.GenerateValues(1, 4, 4) # To get the tibia cartilage #dmc.GenerateValues(4, 1, 4) # To get the full assembly dmc.Update() # Create the stl file os.chdir(rough_stls) # Set directory writer = vtk.vtkSTLWriter() writer.SetInputConnection(dmc.GetOutputPort()) writer.SetFileTypeToBinary() writer.SetFileName(name + ID + ".stl") writer.Write() # Load a mesh and show it a0 = vtkplotter.Plotter().load(name + ID + ".stl", threshold=True, c="v") #vp.show(a0, at=5) # Adjust mesh using Laplacian smoothing a0_lap = a0.smoothLaplacian( niter=50, relaxfact=0.1, edgeAngle=60, featureAngle=150).color( "seagreen").alpha(1).legend("window sinc") # Adjust mesh using a windowed sinc function interpolation kernel a0_smooth = a0_lap.clone().smoothWSinc( niter=50, passBand=0.1, edgeAngle=15, featureAngle=90).color("crimson").alpha(1).legend("femur bone") os.chdir(smooth_stls) #Save smoothened mesh vtkplotter.save(a0_smooth, name + "smooth_" + ID + ".stl",
nh_dist = np.sum(A[:Ni, :Ni], axis=1) # Load the mesh. mesh_file = os.path.join(mesh_folder + str(inh_id)+".h5") print(mesh_file) mm = trimesh_io.MeshMeta(disk_cache_path="test/test_files") mesh = mm.mesh(filename =mesh_file) # Extract vertices and faces to make an "Actor" for vtkplotter. mesh_poly = trimesh_vtk.trimesh_to_vtk(mesh.vertices, mesh.faces, None) plt_actor = vtkp.Actor(mesh_poly, c="m") # Create a window to show the mesh. vtkp.embedWindow(backend="k3d") # Setup a plot that you can add actors to vp = vtkp.Plotter(bg="w") # add it to your plotter. vp+=plt_actor vp.show() # Visualize mesh for inhibitory neuron connecting # to at least 10 excitatory neurons. inh_10conn = np.where(K >= 10)[0] print(inh_10conn) inh_ind = np.random.choice(inh_10conn) inh_id = inh_ids[0] mesh_file = os.path.join(mesh_folder + str(inh_id)+".h5") print(mesh_file) mm = trimesh_io.MeshMeta(disk_cache_path="test/test_files") mesh = mm.mesh(filename =mesh_file) mesh_poly = trimesh_vtk.trimesh_to_vtk(mesh.vertices, mesh.faces, None)