"""Histogram of 2 variables""" from vedo import * from vedo.pyplot import histogram import numpy as np n = 10000 x = np.random.normal(2, 1, n) * 2 + 3 y = np.random.normal(1, 1, n) * 1 + 7 xm, ym = np.mean(x), np.mean(y) h = histogram( x, y, bins=50, aspect=4 / 3, cmap='Blues', title='2D Gauss histo', scalarbar=True, ) # add some object to the plot h += Marker('*', s=0.3, c='r').pos(xm, ym, 0.1) show(h, interactorStyle="Image").close()
"""Generate a polygonal Mesh from a contour line.""" from vedo import * from vedo.pyplot import histogram shapes = load(dataurl + 'timecourse1d.npy') # list of lines shape = shapes[56].mirror().rotateZ(-90) cmap = "RdYlBu" msh = shape.tomesh() # Generate the Mesh from the line msh.smoothLaplacian() # Make the triangles more uniform msh.addQuality() # Measure triangle quality msh.cmap(cmap, on="cells").addScalarBar3D() contour = Line(shape).c('red4').lw(5) histo = histogram(msh.getCellArray('Quality'), aspect=3 / 4, c=cmap, xtitle='triangle mesh quality') show( [ [contour, contour.labels('id'), msh, __doc__], [histo], ], N=2, sharecam=False, )
"""A uniform distribution on a plane is not uniform on a sphere""" import numpy as np from vedo.pyplot import histogram phi = np.random.rand(1000)*6.28 the = np.random.rand(1000)*3.14 h = histogram(the, phi, mode='spheric') h.show(axes=12, viewup='z').close()
from vedo import * from vedo.pyplot import histogram vp = Plotter() s = vp.load(datadir + "cow.vtk", alpha=0.3) pts1, pts2, vals, cols = [], [], [], [] for i in range(0, s.N(), 10): p = s.points(i) pts = s.closestPoint(p, N=12) # find the N closest points to p sph = fitSphere(pts) # find the fitting sphere if sph is None: continue value = sph.radius * 10 color = colorMap(value, "jet", 0, 1) # map value to a RGB color n = versor(p - sph.center) # unit vector from sphere center to p vals.append(value) cols.append(color) pts1.append(p) pts2.append(p + n / 8) vp += Points(pts1, c=cols) vp += Lines(pts1, pts2, c="black") vp += histogram(vals, xtitle='radius', xlim=[0, 2]).pos(-1, 0.5, -1) vp += Text2D(__doc__, pos=1) vp.show()
) plt += DashedLine(x, y) # Fit points and evaluate, with a boostrap and Monte-Carlo technique, # the correct errors and error bands. Return a Line object: pfit = fit([x, y+noise], deg=deg, # degree of the polynomial niter=500, # nr. of MC iterations to compute error bands nstd=2, # nr. of std deviations to display xerrors=xerrs, # optional array of errors on x yerrors=yerrs, # optional array of errors on y vrange=(-3,15), # specify the domain of fit ) plt += [pfit, pfit.errorBand, *pfit.errorLines] # add these objects to Plot txt = "fit coefficients:\n " + precision(pfit.coefficients, 2) \ + "\n\pm" + precision(pfit.coefficientErrors, 2) \ + "\n\Chi^2_\nu = " + precision(pfit.reducedChi2, 3) plt += Text3D(txt, s=0.42, font='VictorMono').pos(2,-2).c('k') # Create an histo to show the correlation of fit parameters h = histogram(pfit.MonteCarloCoefficients[:,0], pfit.MonteCarloCoefficients[:,1], title="parameters correlation", xtitle='coeff_0', ytitle='coeff_1', cmap='bone_r', scalarbar=True) h.scale(150).shift(-1,11) # make it a lot bigger and move it show(plt, h, zoom=1.3, mode="image").close()
"""Fit a plane to regions of a surface defined by N points that are closest to a given point of the surface. Green histogram is the distribution of residuals from the fitting. """ from vedo import * from vedo.pyplot import histogram plt = Plotter() apple = load(dataurl + "apple.ply").subdivide().pointGaussNoise(1) plt += apple.alpha(0.1) variances = [] for i, p in enumerate(apple.points()): pts = apple.closestPoint(p, N=12) # find the N closest points to p plane = fitPlane(pts) # find the fitting plane variances.append(plane.variance) if i % 400: continue plt += plane plt += Points(pts) plt += Arrow(plane.center, plane.center + plane.normal / 5) plt += histogram(variances, xtitle='variance').scale(6).pos(1.2, .2, -1) plt += __doc__ + "\nNr. of fits performed: " + str(len(variances)) plt.show()
def main(): all_loaded_images = [] x_scale = 1 y_scale = 1 z_scale = 1 res = 10 #read every nth pixel in x,y,z #set path #all_images = "C:/Users/sgat/OneDrive - KADK/03_CITA/59_DataViz/03_data/all/" #all_images = "C:/Users/sgat/OneDrive - KADK/03_CITA/59_DataViz/03_data/zebicon-7a12a3/31853_2020-09-18_Wood_1_Top/" #all_images = "C:/Users/sgat/OneDrive - KADK/Sebastian_after_Sync/06_bones_to_flesh/browsing male/(VKH) CT Images (494 X 281)/" #all_images = "C:/Users/sgat/OneDrive - KADK/03_CITA/59_DataViz/03_data/31853_2020-09-18_Cellulose_2_Top/" #all_images = "C:/Users/sgat/OneDrive - KADK/03_CITA/59_DataViz/03_data/31853_2020-09-18_Cellulose_1_Top/" #all_images = "C:/Users/sgat/OneDrive - KADK/03_CITA/59_DataViz/03_data/zebicon-ccc195/31853_2020-10_02_Fungar_1_Top/" all_images = "C:/Users/sgat/OneDrive - KADK/03_CITA/59_DataViz/03_data/zebicon-ccc195/31853_2020-10_02_Fungar_2_Top/" #all_images = "C:/Users/sgat/OneDrive - KADK/03_CITA/59_DataViz/03_data/zebicon-ccc195/cropped_jpeg/" os.chdir(all_images) #load all images types = ('*.gif', '*.png', '*.jpg', "*bmp", "*tif") files = [] for f in types: files.extend(glob.glob(f)) print (len(files)) files = natsorted(files, key=lambda y: y.lower()) #create image stack img_stack = 0 for i in range(0,len(files),res): if i % 100 == 0: print ("img loaded: ", i) img = cv2.imread(files[i],0) if res > 1: img = cv2.resize(img, (0,0), fx=1/res, fy=1/res) if i == 0: img.fill(0) img_stack = img else: img_stack = np.dstack((img_stack,img)) img = cv2.imread(files[0],0) img = cv2.resize(img, (0,0), fx=1/res, fy=1/res) img.fill(0) img_stack = np.dstack((img_stack,img)) print ("image stack created. shape:", img_stack.shape) #prepare data for historgam data = img_stack.copy() data = data.flatten() data = data [data > 5] #only data highe than 5 #create historgam hist = histogram(data, bins=25, errors=False, c = "white", bc = "white", ytitle= "Voxel Counts", xtitle= "Density" ) #create volume vol = Volume(img_stack, spacing=(x_scale,y_scale,z_scale), mapper="smart", mode=1, alpha= [0.0, 0.9, 1.0], c= "coolwarm") #render and show vp = Plotter(N=2, axes=False, bg="black", size="fullscreen", sharecam=False) #(1000,1000)) vp.show(vol, "Voxel Render", axes=0, at=0) vp.show(hist,"Density Historgam", axes=0, at=1) vp.show(interactive=True)
"""Metrics of quality for the cells of a triangular mesh """ from vedo import * from vedo.pyplot import histogram mesh = load(datadir + "bunny.obj").scale(100).computeNormals() mesh.lineWidth(0.1) # generate an array for mesh quality arr = mesh.quality(cmap='RdYlBu') #printHistogram(arr, title='mesh quality', c='w') hist = histogram(arr, xtitle='mesh quality', bc='w') hist.scale(.2).pos(-8, 4, -9) # make it bigger and place it # add a scalar bar for the active scalars mesh.addScalarBar() # create numeric labels of active scalar on top of cells labs = mesh.labels(cells=True, precision=3).color('k') show(mesh, labs, hist, __doc__, bg='bb', zoom=2)
"""Superimpose histograms and curves""" import numpy as np from vedo.pyplot import histogram, plot, settings settings.defaultFont = "Bongas" mu, sigma, n, bins = 100.0, 15.0, 600, 50 samples = np.random.normal(loc=mu, scale=sigma, size=n) x = np.linspace(min(samples), max(samples), num=50) y = 1/(sigma*np.sqrt(2*np.pi)) * np.exp( -(x-mu)**2 /(2*sigma**2)) dy = 1/np.sqrt(n) plt = histogram(samples, title=__doc__, bins=bins, density=True, c='cyan3', aspect=8/7) plt += plot(x, y, "-", lc='orange5') plt += plot(x, y*(1+dy), "--", lc='orange5', lw=2) plt += plot(x, y*(1-dy), "--", lc='orange5', lw=2) plt.show(size=(800,700), zoom=1.2, interactorStyle="Image").close()
"""Metrics of quality for the cells of a triangular mesh (zoom to see cell label values)""" from vedo import * from vedo.pyplot import histogram mesh = Mesh(dataurl + "panther.stl").computeNormals().lineWidth(0.1).flat() # generate a numpy array for mesh quality mesh.addQuality(measure=6).cmap('RdYlBu', on='cells').print() hist = histogram(mesh.celldata["Quality"], xtitle='mesh quality', bc='w') # make it smaller and position it, useBounds makes the cam # ignore the object when resetting the 3d qscene hist.scale(0.6).pos(40, -53, 0).useBounds(False) # add a scalar bar for the active scalars mesh.addScalarBar3D(c='w', title='triangle quality by min(\alpha_i )') # create numeric labels of active scalar on top of cells labs = mesh.labels( cells=True, precision=3, scale=0.4, font='Quikhand', c='black', ) cam = dict(pos=(59.8, -191, 78.9), focalPoint=(27.9, -2.94, 3.33), viewup=(-0.0170, 0.370, 0.929),
data_g = np.zeros(msh.N()) data_r = np.zeros(msh.N()) data_w = np.zeros(msh.N()) data_r[ids_r] = 1.0 data_g[ids_g] = 1.0 data_w[ids_w] = 1.0 ngreen = len(ids_g[0]) total = len(rgb) - len(ids_r[0]) - len(ids_w[0]) gvalue = int(ngreen / total * 100 + 0.5) show( [ [pic, pic.box().lw(3), "Original image. How much grass is there?"], histogram(ratio_g, logscale=True, xtitle='ratio of green'), [ msh.clone().cmap('Greens', data_g), f'Ratio of green is \approx {gvalue}%' ], [msh.clone().cmap('Reds', data_r), 'Masking the vase region'], [msh.clone().cmap('Greys', data_w), 'Masking bright areas'], ], shape="2|3", size=(1370, 1130), sharecam=False, bg='aliceblue', mode='image', zoom=1.5, interactive=True, )
from vedo import * from vedo.pyplot import histogram import numpy as np N = 2000 x = np.random.randn(N) * 1.0 y = np.random.randn(N) * 1.5 # hexagonal binned histogram: histo = histogram( x, y, bins=10, mode='hexbin', xtitle="x gaussian, s=1.0", ytitle="y gaussian, s=1.5", fill=True, cmap='terrain', ) # add a formula: f = r'f(x, y)=A \exp \left(-\left(\frac{\left(x-x_{o}\right)^{2}}' f += r'{2 \sigma_{x}^{2}}+\frac{\left(y-y_{o}\right)^{2}}' f += r'{2 \sigma_{y}^{2}}\right)\right)' formula = Latex(f, c='k', s=1.5).rotateX(90).rotateZ(90).pos(1.5, -2, 1) show(histo, formula, axes=1, viewup='z')
ln = lns.split(delimiter) vals = [float(x) for x in ln] data.append(vals) data = np.array(data) print("Print first 5 rows:\n", names) print(data[:5]) print("Number of rows:", len(data)) ################################################## # extract the columns into separate vectors: g0, g1, g2, g3, g4 = data.T # unpack genes n0, n1, n2, n3, n4 = names # now create and show histograms of the gene expressions h0 = histogram(g0, xtitle=n0, c=0) h1 = histogram(g1, xtitle=n1, c=1) h2 = histogram(g2, xtitle=n2, c=2) h3 = histogram(g3, xtitle=n3, c=3, logscale=True) h4 = histogram(g4, xtitle=n4, c=4) # this is where you choose what variables to show as 3D points pts = np.c_[g4, g2, g3] # form an array of 3d points from the columns pts_1 = pts[g0 > 0] # select only points that have g0>0 p1 = Points(pts_1, r=4, c='red') # create the vedo object print("after selection nr. of points is", len(pts_1)) pts_2 = pts[(g0 < 0) & (g1 > .5)] # select excluded points that have g1>0.5 p2 = Points(pts_2, r=8, c='green') # create the vedo object
"""Probe a voxel dataset at specified points and plot a histogram of the values """ from vedo import * from vedo.pyplot import histogram import numpy as np vol = load(datadir+'embryo.slc') pts = np.random.rand(4000, 3)*256 mpts = probePoints(vol, pts).pointSize(3).printInfo() scals = mpts.getPointArray() h = histogram(scals, xlim=(5,120), xtitle='voxel value') h.scale(2.2) show(vol, mpts, h, __doc__)
from vedo import * from vedo.pyplot import histogram import numpy as np N = 2000 x = np.random.randn(N) * 1.0 y = np.random.randn(N) * 1.5 # hexagonal binned histogram: histo = histogram( x, y, bins=10, mode='hexbin', xtitle="\sigma_x =1.0", ytitle="\sigma_y =1.5", ztitle="counts", fill=True, cmap='terrain', ) # add a formula: f = r'f(x, y)=A \exp \left(-\left(\frac{\left(x-x_{o}\right)^{2}}' f += r'{2 \sigma_{x}^{2}}+\frac{\left(y-y_{o}\right)^{2}}' f += r'{2 \sigma_{y}^{2}}\right)\right)' formula = Latex(f, c='k', s=1.5).rotateX(90).rotateZ(90).pos(1.5, -2, 1) show(histo, formula, axes=1, viewup='z')
"""Generate a polygonal Mesh from a contour line""" from vedo import * from vedo.pyplot import histogram shapes = load(dataurl + 'timecourse1d.npy') # list of lines shape = shapes[56].mirror().rotateZ(-90) cmap = "RdYlBu" msh = shape.tomesh() # Generate the Mesh from the line msh.smooth() # make the triangles more uniform msh.addQuality() # add a measure of triangle quality msh.cmap(cmap, on="cells").addScalarBar3D() contour = Line(shape).c('red4').lw(5) histo = histogram(msh.celldata['Quality'], aspect=3 / 4, c=cmap, xtitle='triangle mesh quality') show( [ (contour, contour.labels('id'), msh, __doc__), histo, ], N=2, sharecam=False, ).close()
import numpy as np from vedo import * from vedo.pyplot import histogram, plot cmap = 'nipy_spectral' alpha = np.array([0, 0, 0.05, 0.2, 0.8, 1]) vol = Volume(dataurl + "embryo.slc") vol.cmap(cmap).alpha(alpha).addScalarBar3D(c='w') xvals = np.linspace(*vol.scalarRange(), len(alpha)) p = histogram(vol, logscale=True, c=cmap, bc='white') p += plot(xvals, alpha * p.ybounds()[1], '--ow').z(1) show( [(vol, Axes(vol, c='w'), f"Original Volume\ncolor map: {cmap}"), (p, "Voxel scalar histogram\nand opacity transfer function")], N=2, sharecam=False, bg=(82, 87, 110), ).close()
import numpy as np from vedo.pyplot import histogram from vedo import * np.random.seed(3) data1 = np.random.randn(250) data2 = (np.random.rand(250) - 0.5) * 12 hst1 = histogram( data1, bins=30, errors=True, aspect=4 / 3, title='My distributions', xtitle='some stochastic x_\mu^0', c='red', marker='o', ) # pick the 16th bin and color it violet hst1.unpack(15).c('violet') hst1 += Text3D('Highlight a\nspecial bin', pos=(0.5, 20), c='v') # A second histogram: # make it in same format as hst1 so it can be superimposed hst2 = histogram(data2, format=hst1, alpha=0.5) # Show both: show(hst1, hst2, mode="image").close()
"""Probe a voxel dataset at specified points and plot a histogram of the values""" from vedo import * from vedo.pyplot import histogram import numpy as np vol = Volume(dataurl + 'embryo.slc') pts = np.random.rand(5000, 3) * 256 mpts = probePoints(vol, pts).pointSize(3) mpts.print() # valid = mpts.pointdata['vtkValidPointMask'] scals = mpts.pointdata['SLCImage'] his = histogram(scals, xtitle='probed voxel value', xlim=(5, 100)) show([(vol, Axes(vol), mpts, __doc__), his], N=2, sharecam=False).close()
"""Create an animated logo""" from vedo import * from vedo.pyplot import histogram exa = Polygon().scale(4.1).pos(5.25, 4.8, 0).off() his = histogram([-1, 1], [-1, 1], mode='hex').unpack() exah, cmh = [], [] for h in his: cm = h.centerOfMass() if exa.isInside(cm): h.c('green').shrink(0.9).addShadow(z=-.4) exah.append(h) cmh.append(cm) v1 = vector(9.4, 5.2, 0) v2 = vector(9.4, 2.7, 0) t1 = Text("EMBL", v1, c="k", s=1.5, depth=0) t2 = Text("European Molecular\nBiology Laboratory", v2, c="dg", s=0.6, depth=0) show(exa, exah, t1, t2, axes=0, interactive=0, elevation=-50) for ti in reversed(range(100)): t = ti / 100. for j, h in enumerate(exah): cx, cy, _ = cmh[j] - [4, 5, 0] x = t * -4 + (1 - t) * 6 g = exp(-(cx - x)**2 / .5) * 2 h.z(g) t1.pos([sin(t) * -10, 0, -0.41] + v1).alpha((1 - t)**2) t2.pos([sin(t) * -15, 0, -0.41] + v2).alpha((1 - t)**4) exah[13].c('red')
"""Metrics of quality for the cells of a triangular mesh (zoom to see cell label values)""" from vedo import * from vedo.pyplot import histogram mesh = load(dataurl + "panther.stl").computeNormals().lineWidth(0.1) # generate a numpy array for mesh quality mesh.addQuality(measure=6).printInfo().cmap('RdYlBu', on='cells') hist = histogram(mesh.getCellArray("Quality"), xtitle='mesh quality', bc='w') # make it smaller and position it, useBounds makes the cam # ignore the object when resetting the 3d qscene hist.scale(0.6).pos(40, -53, 0).useBounds(False) # add a scalar bar for the active scalars mesh.addScalarBar3D(c='w', title='triangle quality by min(\alpha_i )') # create numeric labels of active scalar on top of cells labs = mesh.labels( cells=True, precision=3, scale=0.4, font='Quikhand', c='black', ) cam = dict(pos=(59.8, -191, 78.9), focalPoint=(27.9, -2.94, 3.33), viewup=(-0.0170, 0.370, 0.929),
from vedo import Hyperboloid, show from vedo.pyplot import histogram import numpy as np np.random.seed(1) ################################################################## radhisto = histogram( np.random.rand(200) * 6.28, mode='polar', title="random orientations", bins=10, c=range(10), #'orange', #uniform color alpha=0.8, labels=["label" + str(i) for i in range(10)], ) show(radhisto, at=0, N=2, axes=0, sharecam=False) ################################################################## hyp = Hyperboloid(res=20).cutWithPlane().rotateY(-90) hyp.color('grey').alpha(0.3) # select 10 random indices of points on the surface idx = np.random.randint(0, hyp.NPoints(), size=10) radhistos = [] for i in idx: #generate a random histogram rh = histogram( np.random.randn(100),
"""Histogram of 2 variables""" from vedo import * from vedo.pyplot import histogram import numpy as np n = 10000 x = np.random.normal(2, 1, n) * 2 + 3 y = np.random.normal(1, 1, n) * 1 + 7 xm, ym = np.mean(x), np.mean(y) h = histogram( x, y, bins=50, aspect=4 / 3, # cmap='Blues', cmap='PuBu', title='2D Gauss histo', ) # add some object to the plot h += Marker('*', s=0.3, c='r').pos(xm, ym, 0.1) show(h)