def plot_nii_gz(file_path: Path): vp = Plotter() image = vp.load(str(file_path)) print(np.max(image.getDataArray()), np.sum(image.getDataArray() == 3), np.sum(image.getDataArray() == 2), np.sum(image.getDataArray() == 1), np.sum(image.getDataArray() == 0), np.sum(image.getDataArray() == 255), np.mean(image.getDataArray()[image.getDataArray() > 0]))
color and transparency of a mesh""" from vedo import Plotter, dataurl 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(dataurl + "magnolia.vtk").flat().lw(0.1) vp.addSlider2D(slider1, -9, 9, value=0, pos="bottom-right", title="color number") vp.addSlider2D(slider2, xmin=0.01, xmax=0.99, value=0.5, c="blue", pos="bottom-right-vertical", title="alpha value (opacity)")
"""Setting illumination properties: ambient, diffuse specular, specularPower, specularColor. """ #https://lorensen.github.io/VTKExamples/site/Python/Rendering/SpecularSpheres from vedo import Plotter, Arrow, datadir vp = Plotter(axes=1) ambient, diffuse, specular = 0.1, 0., 0. specularPower, specularColor = 20, 'white' for i in range(8): s = vp.load(datadir + 'apple.ply', c='gold') s.normalize().pos((i % 4) * 2.2, int(i < 4) * 3, 0) #s.phong() s.flat() # modify the default with specific values s.lighting('default', ambient, diffuse, specular, specularPower, specularColor) #ambient += 0.125 diffuse += 0.125 specular += 0.125 vp += __doc__ vp.show() print('Adding a light source..') p = (3, 1.5, 3)
for i, longs in enumerate(agrid_reco): ilat = grid_reco.lats()[i] for j, value in enumerate(longs): ilong = grid_reco.lons()[j] th = np.deg2rad(90 - ilat) ph = np.deg2rad(ilong) r = value + rbias p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * r pts.append(p) return pts plt = Plotter(shape=[2, 2], axes=3, interactive=0) shape1 = Sphere(alpha=0.2) shape2 = plt.load(dataurl + "icosahedron.vtk").normalize().lineWidth(1) agrid1, actorpts1 = makeGrid(shape1, N) plt.show(shape1, actorpts1, at=0) agrid2, actorpts2 = makeGrid(shape2, N) plt.show(shape2, actorpts2, at=1) plt.camera.Zoom(1.2) clm1 = pyshtools.SHGrid.from_array(agrid1).expand() clm2 = pyshtools.SHGrid.from_array(agrid2).expand() # clm1.plot_spectrum2d() # plot the value of the sph harm. coefficients # clm2.plot_spectrum2d()
"""Mesh smoothing with two different methods""" from vedo import Plotter, dataurl plt = Plotter(N=2) # Load a mesh and show it vol = plt.load(dataurl + "embryo.tif") m0 = vol.isosurface().normalize().lw(0.1).c("violet") plt.show(m0, __doc__ + "\nOriginal Mesh:", at=0) plt.background([0.8, 1, 1], at=0) # set first renderer color # Smooth the mesh m1 = m0.clone().smooth(niter=20).color("lg") plt.show(m1, "Polygons are smoothed:", at=1, viewup='z', zoom=1.5, interactive=True).close()
"""Setting illumination properties: ambient, diffuse specular, specularPower, specularColor. """ #https://lorensen.github.io/VTKExamples/site/Python/Rendering/SpecularSpheres from vedo import Plotter, Arrow, Light, datadir vp = Plotter(axes=1) ambient, diffuse, specular = 0.1, 0., 0. specularPower, specularColor= 20, 'white' for i in range(8): s = vp.load(datadir+'apple.ply').c('gold') s.normalize().pos((i%4)*2.2, int(i<4)*3, 0) #s.phong() s.flat() # modify the default with specific values s.lighting('default', ambient, diffuse, specular, specularPower, specularColor) #ambient += 0.125 diffuse += 0.125 specular += 0.125 vp += __doc__ vp.show() print('Adding a light source..') p = (3, 1.5, 3)
"""Mesh smoothing with two different methods""" from vedo import Plotter, dataurl vp = Plotter(N=3) # Load a mesh and show it vol = vp.load(dataurl + "embryo.tif") m0 = vol.isosurface().normalize().lw(0.1).c("violet") vp.show(m0, __doc__, at=0) # Adjust mesh using Laplacian smoothing m1 = m0.clone().smoothLaplacian(niter=20, relaxfact=0.1, edgeAngle=15, featureAngle=60) m1.color("pink").legend("laplacian") vp.show(m1, at=1) # Adjust mesh using a windowed sinc function interpolation kernel m2 = m0.clone().smoothWSinc(niter=15, passBand=0.1, edgeAngle=15, featureAngle=60) m2.color("lg").legend("window sinc") vp.show(m2, at=2) vp.backgroundColor([0.8, 1, 1], at=0) # set first renderer color vp.show(zoom=1.4, interactive=True)
""" 3D slider to move a mesh interactively """ from vedo import Plotter, datadir vp = Plotter() mesh = vp.load(datadir + "spider.ply") mesh.normalize().rotateZ(190).scale(0.8) def slider_y(widget, event): value = widget.GetRepresentation().GetValue() mesh.y(value) # set y coordinate position vp.addSlider3D( slider_y, pos1=[2, -1, -1], pos2=[2, 1, -1], xmin=-1, xmax=1, value=0, s=0.04, c="r", rotation=45, title="y position", ) vp.show(viewup="z", axes=1)
for i, longs in enumerate(agrid_reco): ilat = grid_reco.lats()[i] for j, value in enumerate(longs): ilong = grid_reco.lons()[j] th = np.deg2rad(90 - ilat) ph = np.deg2rad(ilong) r = value + rbias p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * r pts.append(p) return pts vp = Plotter(shape=[2, 2], axes=3, interactive=0) shape1 = Sphere(alpha=0.2) shape2 = vp.load(datadir + "icosahedron.vtk").normalize().lineWidth(1) agrid1, actorpts1 = makeGrid(shape1, N) vp.show(shape1, actorpts1, at=0) agrid2, actorpts2 = makeGrid(shape2, N) vp.show(shape2, actorpts2, at=1) vp.camera.Zoom(1.2) vp.interactive = False clm1 = pyshtools.SHGrid.from_array(agrid1).expand() clm2 = pyshtools.SHGrid.from_array(agrid2).expand() # clm1.plot_spectrum2d() # plot the value of the sph harm. coefficients # clm2.plot_spectrum2d()
""" 3D slider to move a mesh interactively """ from vedo import Plotter, dataurl vp = Plotter() mesh = vp.load(dataurl+"spider.ply") mesh.normalize().rotateZ(190) def slider_y(widget, event): value = widget.GetRepresentation().GetValue() mesh.y(value) # set y coordinate position vp.addSlider3D( slider_y, pos1=[.5, -3.5, .35], pos2=[.5, -1.0, .35], xmin=-1, xmax=1, value=0, s=0.04, c="r", rotation=45, title="y position", ) vp.show(viewup="z", axes=11, bg='bb', bg2='navy')
) # this is the RH of Schroedinger equation! def d_dt(psi): # find Psi(t+dt)-Psi(t) /dt with 4th order Runge-Kutta method k1 = f(psi) k2 = f(psi + dt / 2 * k1) k3 = f(psi + dt / 2 * k2) k4 = f(psi + dt * k3) return (k1 + 2 * k2 + 2 * k3 + k4) / 6 plt = Plotter(interactive=False, axes=2, size=(1000, 500)) plt.xtitle = "" plt.ytitle = "|\Psi(x,t)|\^2" bck = plt.load(dataurl + "images/schrod.png").scale(0.015).pos([0, 0, -0.5]) barrier = Line(np.stack((x, V * 15), axis=1), c="dr", lw=3) lines = [] for j in range(150): for i in range(500): Psi += d_dt(Psi) * dt # integrate for a while A = np.real(Psi * np.conj(Psi)) * 1.5 # psi squared, probability(x) coords = np.stack((x, A, np.zeros_like(x)), axis=1) Aline = Tube(coords, c="db", r=0.08) plt.show(Aline, barrier, bck, zoom=2) lines.append(Aline) if plt.escaped: break # if ESC is hit during the loop interactive().close()
plt += Point([i, 0, 0], c="green", r=6) pts_actors_eu = plt.actors # save a copy of the actors list pts_actors_eu[0].legend = "Euler method" plt.actors = [] # clean up the list for i in x: plt += Point([i, 0, 0], c="red", r=6) pts_actors_rk = plt.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 plt.actors = pts_actors_eu + pts_actors_rk # let's also add a fancy background image from wikipedia plt.load(dataurl + "images/wave_wiki.png").alpha(0.8).scale(0.4).pos( 0, -100, -20) plt += __doc__ 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: plt.show() if plt.escaped: break # if ESC is hit during the loop pb.print("Moving actors loop")
"""3D slider to move a mesh interactively""" from vedo import Plotter, dataurl plt = Plotter(title=__doc__) mesh = plt.load(dataurl + "spider.ply") mesh.normalize().rotateZ(190) def slider_y(widget, event): value = widget.GetRepresentation().GetValue() mesh.y(value) # set y coordinate position plt.addSlider3D( slider_y, pos1=[.5, -3.5, .35], pos2=[.5, -1.0, .35], xmin=-1, xmax=1, value=0, s=0.04, c="r", rotation=45, title="y position", ) plt.show(viewup="z", axes=11, bg='bb', bg2='navy').close()
"""Normal jpg/png pictures can be loaded, cropped, rotated and positioned in 3D """ from vedo import Plotter, dataurl vp = Plotter(axes=3) for i in range(5): p = vp.load(dataurl + "images/dog.jpg") # returns Picture p.crop(bottom=0.2) # crop 20% p.scale(1 - i / 10.0).alpha(0.8) # picture can be scaled in size p.rotateX(20 * i).pos(0, 0, 30 * i) # (can concatenate methods) vp += __doc__ vp.show()
points = Points(cpoints).c('violet') spline = None if len(cpoints) > 1: spline = KSpline(cpoints).c('yellow').alpha(0.5) plt.add([spline, points]) def keyfunc(key): global spline, points, cpoints if key == 'c': plt.remove([spline, points]) cpoints, points, spline = [], None, None ############################################################################## plt = Plotter() plt.keyPressFunction = keyfunc plt.mouseLeftClickFunction = onLeftClick plt.mouseRightClickFunction = onRightClick t = """Click to add a point Right-click to remove it Press c to clear points""" msg = Text2D(t, pos="bottom-left", c='k', bg='green', font='Quikhand', s=0.9) pic = plt.load(datadir + "images/dog.jpg") # make a transparent box around the picture for clicking box = pic.box(pad=1).wireframe(False).alpha(0.01) plt.show(__doc__, pic, box, msg, axes=True, interactorStyle=6, bg='w')
"""Setting illumination properties: ambient, diffuse specular, specularPower, specularColor. """ #https://lorensen.github.io/VTKExamples/site/Python/Rendering/SpecularSpheres from vedo import Plotter, Arrow, Light, dataurl vp = Plotter(axes=1) ambient, diffuse, specular = 0.1, 0., 0. specularPower, specularColor = 20, 'white' for i in range(8): s = vp.load(dataurl + 'apple.ply').c('gold') s.normalize().pos((i % 4) * 2.2, int(i < 4) * 3, 0) #s.phong() s.flat() # modify the default with specific values s.lighting('default', ambient, diffuse, specular, specularPower, specularColor) #ambient += 0.125 diffuse += 0.125 specular += 0.125 vp += __doc__ vp.show() print('Adding a light source..') p = (3, 1.5, 3)
) # this is the RH of Schroedinger equation! def d_dt(psi): # find Psi(t+dt)-Psi(t) /dt with 4th order Runge-Kutta method k1 = f(psi) k2 = f(psi + dt / 2 * k1) k3 = f(psi + dt / 2 * k2) k4 = f(psi + dt * k3) return (k1 + 2 * k2 + 2 * k3 + k4) / 6 vp = Plotter(interactive=0, axes=2, bg=(0.95, 0.95, 1)) vp.xtitle = "" vp.ytitle = "|\Psi(x,t)|\^2" bck = vp.load(datadir + "images/schrod.png").alpha(.3).scale(.0255).pos( [0, -5, -.1]) barrier = Line(np.stack((x, V * 15, np.zeros_like(x)), axis=1), c="black", lw=2) lines = [] for i in range(0, Nsteps): for j in range(500): Psi += d_dt(Psi) * dt # integrate for a while before showing things A = np.real(Psi * np.conj(Psi)) * 1.5 # psi squared, probability(x) coords = np.stack((x, A, np.zeros_like(x)), axis=1) Aline = Line(coords, c="db", lw=3) vp.show([Aline, barrier, bck]) lines.append([Aline, A]) # store objects # now show the same lines along z representing time
vp += Point([i, 0, 0], c="green", r=6) 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 += __doc__ 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)
from vedo import Plotter, datadir # these are the some matplotlib color maps mapkeys = [ "afmhot", "binary", "bone", "cool", "coolwarm", "copper", "gist_earth", "gray", "hot", "jet", "rainbow", "winter", ] vp = Plotter(N=len(mapkeys)) vp.legendSize = 0.4 mug = vp.load(datadir + "mug.ply") scalars = mug.points()[:, 1] # let y-coord be the scalar for i, key in enumerate(mapkeys): # for each available color map name imug = mug.clone().cmap(key, scalars, n=5) vp.show(imug, key, at=i) vp.show(interactive=1)
""" Mesh smoothing with two different methods. """ print(__doc__) from vedo import Plotter, datadir vp = Plotter(shape=(1, 3)) # Load a mesh and show it m0 = vp.load(datadir + "embryo.tif", threshold=True, c="v").normalize().lw(0.1) vp.show(m0, at=0) # Adjust mesh using Laplacian smoothing m1 = m0.clone().smoothLaplacian(niter=20, relaxfact=0.1, edgeAngle=15, featureAngle=60) m1.color("crimson").legend("laplacian") vp.show(m1, at=1) # Adjust mesh using a windowed sinc function interpolation kernel m2 = m0.clone().smoothWSinc(niter=15, passBand=0.1, edgeAngle=15, featureAngle=60) m2.color("seagreen").legend("window sinc") vp.show(m2, at=2) vp.renderers[0].SetBackground(0.8, 1, 1) # set first renderer color vp.show(zoom=1.4, interactive=True)
def f(psi): # a smart numpy way to calculate the second derivative in x: nabla2psi[1 : N+1] = (psi[0:N] + psi[2 : N+2] - 2 * psi[1 : N+1]) / dx2 return 1j * (nabla2psi - V*psi) # this is the RH of Schroedinger equation! def d_dt(psi): # find Psi(t+dt)-Psi(t) /dt with 4th order Runge-Kutta method k1 = f(psi) k2 = f(psi + dt / 2 * k1) k3 = f(psi + dt / 2 * k2) k4 = f(psi + dt * k3) return (k1 + 2 * k2 + 2 * k3 + k4) / 6 plt = Plotter(interactive=False) bck = plt.load(dataurl+"images/schrod.png").alpha(.3).scale(.0256).pos([0,-5,-.1]) barrier = Line(np.stack((x, V*15, np.zeros_like(x)), axis=1), c="black", lw=2) box = bck.box().c('black') lines = [] for i in range(0, Nsteps): for j in range(500): Psi += d_dt(Psi) * dt # integrate for a while before showing things A = np.real(Psi * np.conj(Psi)) * 1.5 # psi squared, probability(x) coords = np.stack((x, A), axis=1) Aline = Line(coords, c="db", lw=3) plt.show(barrier, bck, Aline, box).remove(Aline) lines.append([Aline, A]) # store objects # now show the same lines along z representing time plt.actors= [] # clean up internal list of objects to show
"""Mesh smoothing with two different methods""" from vedo import Plotter, datadir vp = Plotter(N=3) # Load a mesh and show it vol = vp.load(datadir + "embryo.tif") m0 = vol.isosurface().normalize().lw(0.1).c("violet") vp.show(m0, __doc__, at=0) # Adjust mesh using Laplacian smoothing m1 = m0.clone().smoothLaplacian(niter=20, relaxfact=0.1, edgeAngle=15, featureAngle=60) m1.color("pink").legend("laplacian") vp.show(m1, at=1) # Adjust mesh using a windowed sinc function interpolation kernel m2 = m0.clone().smoothWSinc(niter=15, passBand=0.1, edgeAngle=15, featureAngle=60) m2.color("lg").legend("window sinc") vp.show(m2, at=2) vp.backgroundColor([0.8, 1, 1], at=0) # set first renderer color vp.show(zoom=1.4, interactive=True)
from vedo import Plotter, Plane, datadir vp = Plotter() cow = vp.load(datadir + "cow.vtk", c="grey").scale(4).rotateX(-90) vp += Plane(pos=[0, -3.6, 0], normal=[0, 1, 0], sx=20).texture("grass") vp.show(viewup='y', interactive=0) # vp.light() returns a vtkLight object with focal Point, fp, to mesh cow # fp can also be explicitly set as fp=[x,y,z] l = vp.addLight(pos=[-6, 6, 6], focalPoint=cow, deg=12, showsource=1) # can be switched on/off this way #l.SwitchOff() vp.show(interactive=1)
) # this is the RH of Schroedinger equation! def d_dt(psi): # find Psi(t+dt)-Psi(t) /dt with 4th order Runge-Kutta method k1 = f(psi) k2 = f(psi + dt / 2 * k1) k3 = f(psi + dt / 2 * k2) k4 = f(psi + dt * k3) return (k1 + 2 * k2 + 2 * k3 + k4) / 6 vp = Plotter(interactive=0, axes=2, size=(1000, 500)) vp.xtitle = "" vp.ytitle = "|\Psi(x,t)|\^2" bck = vp.load(datadir + "images/schrod.png").scale(0.015).pos([0, 0, -0.5]) barrier = Line(np.stack((x, V * 15), axis=1), c="dr", lw=3) lines = [] for j in range(150): for i in range(500): Psi += d_dt(Psi) * dt # integrate for a while A = np.real(Psi * np.conj(Psi)) * 1.5 # psi squared, probability(x) coords = np.stack((x, A, np.zeros_like(x)), axis=1) Aline = Tube(coords, c="db", r=0.08) vp.show(Aline, barrier, bck, zoom=2) lines.append(Aline) interactive()
"""delaunay2D() and cellCenters() functions""" from vedo import Plotter, delaunay2D, Points, datadir vp = Plotter(shape=(1, 2), interactive=0) d0 = vp.load(datadir + "250.vtk").rotateY(-90).legend("original mesh") coords = d0.points() # 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, mode='fit') d1.color("r").wireframe(True).legend("delaunay mesh") cents = d1.cellCenters() ap = Points(cents).legend("cell centers") vp.show(d0, d1, __doc__, at=0) # NB: d0 and d1 are slightly different vp.show(d1, ap, at=1, interactive=1)
from vedo import Plotter, dataurl # these are the some matplotlib color maps mapkeys = [ "afmhot", "binary", "bone", "cool", "coolwarm", "copper", "gist_earth", "gray", "hot", "jet", "rainbow", "winter", ] vp = Plotter(N=len(mapkeys)) vp.legendSize = 0.4 mug = vp.load(dataurl + "mug.ply") scalars = mug.points()[:, 1] # let y-coord be the scalar for i, key in enumerate(mapkeys): # for each available color map name imug = mug.clone(deep=False).cmap(key, scalars, n=5) vp.show(imug, key, at=i) vp.show(interactive=1)