def _Plot2(self): vv.figure(self.fig.nr) vv.clf() ax1f2 = vv.cla() ax1f2.daspect = 1,-1,1 vv.surf(self.z) vv.axis('off') ax1f1 = self.fig2.add_subplot(221) ax1f1.imshow(self.Nx) ax1f1.axis('off') ax2f1 = self.fig2.add_subplot(222) ax2f1.imshow(self.Ny) ax2f1.axis('off') ax3f1 = self.fig2.add_subplot(223) ax3f1.imshow(self.Nz) ax3f1.axis('off') ax4f1 = self.fig2.add_subplot(224) ax4f1.imshow(self.A, cmap='gray') ax4f1.axis('off') self.canvas.draw() if not hasattr(self, 'toolbar'): self.toolbar = NavigationToolbar(self.canvas, self.mplwindow3, coordinates=True) self.mplvl3.addWidget(self.toolbar) self.setWindowTitle('PS Acquisition Tool - %s' % self.currentArchive)
def get_plane_surface(width, height, z_offset, img_face=None): import visvis as vv xx, yy = np.meshgrid((-width / 2.0, width / 2.0), (-height / 2.0, height / 2.0)) zz = z_offset + np.zeros_like(xx) if img_face: plane_surf = vv.surf(xx, yy, zz, img_face) else: plane_surf = vv.surf(xx, yy, zz) return plane_surf
def _visualise_world_visvis(X, Y, Z, format="surf"): """ Legacy function to produce a surface render using visvis :param X: :param Y: :param Z: :param format: """ import visvis as vv # m2 = vv.surf(worldx[::detail], worldy[::detail], worldz[::detail]) app = vv.use() # prepare axes a = vv.gca() a.cameraType = '3d' a.daspectAuto = False # print("view", a.camera.GetViewParams()) # a.SetView(loc=(-1000,0,0)) # a.camera.SetView(None, loc=(-1000,0,0)) if format == "surf": l = vv.surf(X, Y, Z) a.SetLimits(rangeX=(-0.2, 0.2), rangeY=(-0.5, 0.5), rangeZ=(-0.5, 0), margin=0.02) else: # draw points pp = vv.Pointset( np.concatenate([X.flatten(), Y.flatten(), Z.flatten()], axis=0).reshape((-1, 3))) l = vv.plot(pp, ms='.', mc='r', mw='5', ls='', mew=0) l.alpha = 0.2 app.Run()
def update_plot(self): vv.cla() self.surf = vv.surf(self.x, self.y, self.z, axesAdjust=False, axes=self.axes) self.surf.clim = self.clim self.surf.colormap = vv.CM_JET
def draw_error_ellipsoid_visvis(mu, covariance_matrix, stdev=1, z_offset=0, color_ellipsoid="g", pt_size=5): """ @brief Plot the error (uncertainty) ellipsoid using a 3D covariance matrix for a given standard deviation @param mu: The mean vector @param covariance_matrix: the 3x3 covariance matrix @param stdev: The desire standard deviation value to draw the uncertainty ellipsoid for. Default is 1. """ import visvis as vv # Step 1: make a unit n-sphere u = np.linspace(0.0, 2.0 * np.pi, 30) v = np.linspace(0.0, np.pi, 30) x_sph = np.outer(np.cos(u), np.sin(v)) y_sph = np.outer(np.sin(u), np.sin(v)) z_sph = np.outer(np.ones_like(u), np.cos(v)) X_sphere = np.dstack((x_sph, y_sph, z_sph)) # Step 2: apply the following linear transformation to get the points of your ellipsoid (Y): C = np.linalg.cholesky(covariance_matrix) ellipsoid_pts = mu + stdev * np.dot(X_sphere, C) x = ellipsoid_pts[..., 0] y = ellipsoid_pts[..., 1] z = ellipsoid_pts[..., 2] + z_offset # plot ellipsoid_surf = vv.surf(x, y, z) # Get axes # ellipsoid_surf = vv.grid(x, y, z) ellipsoid_surf.faceShading = "smooth" ellipsoid_surf.faceColor = color_ellipsoid # ellipsoid_surf.edgeShading = "plain" # ellipsoid_surf.edgeColor = color_ellipsoid ellipsoid_surf.diffuse = 0.9 ellipsoid_surf.specular = 0.9 mu_pt = vv.Point(mu[0], mu[1], mu[2] + z_offset) pt_mu = vv.plot(mu_pt, ms='.', mc="k", mw=pt_size, ls='', mew=0, axesAdjust=True)
def plot_image_data(self, image_data, transformator, sampling=1.0): if not sampling == 1.0: self.logger.info("Sampling image by {}".format(sampling)) image_data = cv2.resize(image_data, dsize=(0, 0), fx=sampling, fy=sampling) # list all (x,y) coordinates of any pixel in the image, apply resolution scaling x = np.arange(image_data.shape[1]).astype(np.float32) y = np.arange(image_data.shape[0]).astype(np.float32) if not sampling == 1.0: self.logger.info( "Multiplying image coordinates by {} according to sampling by {}" .format(1 / sampling, sampling)) x /= sampling y /= sampling # make meshgrid of (x,y) X, Y = np.meshgrid(x, y) # build coordinate list C = np.array([X.flatten(), Y.flatten()]).T C = np.append(C, np.zeros([C.shape[0], 1]), axis=1) # add z C = np.append(C, np.ones([C.shape[0], 1]), axis=1) # add w # project into scene Ct = transformator.transform(C) # reverse meshgrid Xt = Ct[..., 0].reshape(image_data.shape) Yt = Ct[..., 1].reshape(image_data.shape) Zt = Ct[..., 2].reshape(image_data.shape) # plot image vv.surf(Xt, Yt, Zt, image_data, aa=3)
def grid(*args, **kwargs): """ grid(*args, axesAdjust=True, axes=None) Create a wireframe parametric surface. Usage ----- * grid(Z) - create a grid mesh using the given image with z coordinates. * grid(Z, C) - also supply a texture image to map. * grid(X, Y, Z) - give x, y and z coordinates. * grid(X, Y, Z, C) - also supply a texture image to map. Parameters ---------- Z : A MxN 2D array X : A length N 1D array, or a MxN 2D array Y : A length M 1D array, or a MxN 2D array C : A MxN 2D array, or a AxBx3 3D array If 2D, C specifies a colormap index for each vertex of Z. If 3D, C gives a RGB image to be mapped over Z. In this case, the sizes of C and Z need not match. Keyword arguments ----------------- axesAdjust : bool If True, this function will call axes.SetLimits(), and set the camera type to 3D. If daspectAuto has not been set yet, it is set to False. axes : Axes instance Display the bars in the given axes, or the current axes if not given. Notes ----- * This function should not be confused with the axis grid, see the Axis.showGrid property. * This function is know in Matlab as mesh(), but to avoid confusion with the vv.Mesh class, it is called grid() in visvis. Also see surf() and the solid*() methods. """ m = vv.surf(*args, **kwargs) m.faceShading = None m.edgeShading = 'smooth' m.edgeColor = 'w' return m
def show_layer_boundaries(self, sample): """ Displays a 3-D rendering of boundary surfaces. :param sample: index of sample for which to plot boundaries """ app = vv.use() vv.figure(1) X = np.linspace(self.xbounds[0], self.xbounds[1], self.xres) Y = np.linspace(self.ybounds[0], self.xbounds[1], self.yres) Z = np.linspace(self.zbounds[0], self.xbounds[1], self.zres) vv.xlabel('Eastings (m)') vv.ylabel('Northings (m)') vv.zlabel('Depth (m)') a = vv.gca() a.camera.fov = 70 a.daspect = 1, 1, -1 for i in range(len(self.layers)): C = plt.cm.jet(i / float(len(self.layers))) C = np.array([[[C[0], C[1], C[2]]]]) m = vv.surf(X, Y, self.fbounds[i][sample], C) vv.ColormapEditor(a) app.Run()
def grid(*args, **kwargs): """ grid(*args, axesAdjust=True, axes=None) Create a wireframe parametric surface. Usage ----- * grid(z) - create a grid mesh using the given image with z coordinates. * grid(z, c) - also supply a texture image to map. * grid(x, y, z) - give x, y and z coordinates. * grid(x, y, z, c) - also supply a texture image to map. Keyword arguments ----------------- axesAdjust : bool If True, this function will call axes.SetLimits(), and set the camera type to 3D. If daspectAuto has not been set yet, it is set to False. axes : Axes instance Display the bars in the given axes, or the current axes if not given. Notes ----- * This function should not be confused with the axis grid, see the Axis.showGrid property. * This function is know in Matlab as mesh(), but to avoid confusion with the vv.Mesh class, it is called grid() in visvis. Also see surf() and the solid*() methods. """ m = vv.surf(*args, **kwargs) m.faceShading = None m.edgeShading = 'smooth' m.edgeColor = 'w' return m
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 """ if __name__ == "__main__": m = vv.surf(peaks())
from mpl_toolkits.mplot3d.axes3d import * import matplotlib.pyplot as plt from matplotlib import cm fig = plt.figure() ax = Axes3D(fig) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,linewidth=1, antialiased=True) plt.show() #Plot in 3D with visvis import visvis f = visvis.gca() m = visvis.grid(xi,yi,Z) f.daspect = 1,1,10 # z x 10 # draped colors m = visvis.surf(xi,yi,Z) m.colormap = visvis.CM_JET #Save to GeoTiff file nrows,ncols = np.shape(Z) xres = (xmax-xmin)/ncols yres = (ymax-ymin)/nrows geotransform=(xmin,xres,0,ymin,0, yres) driver = gdal.GetDriverByName("GTiff") ds = driver.Create('output.tif', nrows,ncols, 1, gdal.GDT_Float32) ds.SetGeoTransform(geotransform) #Establish its coordinate srs = osr.SpatialReference() srs.ImportFromEPSG(your EPSG code) ds.SetProjection( srs.ExportToWkt() )
# Should we apply a texture? if c is not None and c.ndim == 3: m.SetTexture(c) else: m.clim = m.clim # trigger correct limits # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Return axes.Draw() return m if __name__ == "__main__": # Read image and smooth a bit lena = vv.imread('lena.png').astype(np.float32) im = lena.copy() im[1:, :, :] = lena[:-1, :, :] im[:-1, :, :] += lena[1:, :, :] im[:, :-1, :] += lena[:, 1:, :] im[:, 1:, :] += lena[:, :-1, :] im /= 4 # Surf m = vv.surf(im[:, :, 0], im)
def plot_mouse_head(show_now=False, size=(500, 500), ax=None, theta=0, phi=0, pitch=None, roll=None, isometric=True, azimuth=None, elevation=None, zoom=1.5, gravity_axes=True, head_axes=True, close_figure=False, color_mouse=(.5, .5, .5), color_head_axes=(.25, .95, .8), color_gravity_axes=(.75, .75, .75), backend='visvis', light_ambient=.6, light_specular=.5, arrow_kw=dict(length_cone=.1, radius_cone=.05, radius_shaft=.025)): if azimuth is None: azimuth = DEFAULT_AZIMUTH if elevation is None: elevation = DEFAULT_ELEVATION t = np.arange(0, 1 * np.pi - 2 * np.pi / 10, np.pi / 10) r = 2 + np.cos(t) n = 20 if backend in ['mayavi', 'mlab']: from mayavi import mlab from tvtk.tools import visual fig = mlab.figure(bgcolor=(1, 1, 1), size=size) fig.scene.parallel_projection = True # head c = -3 [X, Y, Z] = cylinder(r, n=n) head = mlab.mesh(X, Y, c + Z * 6, color=(.5, .5, .5)) # nose [x, y, z] = sphere(20) nose = mlab.mesh(x * 1.5, y * 1.5, c + z * 1.5 + 6, color=(.5, .5, .5)) # EARS color = (.5, .5, .5) hsE1 = mlab.mesh((x * 1.0) - 2.427, (y * 1.8) - 1.763, c + (z * 0.4) + 0, color=color) hsE2 = mlab.mesh((x * 1.0) + 2.427, (y * 1.8) - 1.763, c + (z * 0.4) + 0, color=color) # EYES [x, y, z] = sphere(10) color = (.9, .9, .9) hsEYE1 = mlab.mesh((x * .8) - 1.2, (y * .8) - 1.6, c + (z * .8) + 3.5, color=color) hsEYE2 = mlab.mesh((x * .8) + 1.2, (y * .8) - 1.6, c + (z * .8) + 3.5, color=color) # pupils hsPUP1 = mlab.mesh((x * .3) - 1.476, (y * .3) - 1.98, c + (z * .3) + 4.147, color=(0.1, 0.1, 0.1)) hsPUP2 = mlab.mesh((x * .3) + 1.476, (y * .3) - 1.98, c + (z * .3) + 4.147, color=(0.1, 0.1, 0.1)) # whiskers Px = np.array([-1.154, -1.214, -1.154, +1.154, +1.214, +1.154]) Py = np.array([-0.375, 0, 0.375, -0.375, 0, 0.375]) Pz = np.ones(np.size(Px)) * 3.882 WL = np.array([[0.5, 2], [0.05, 0.4]]) # whisker length hsWHISK = [] for W in range(0, len(Px)): # W=0 if Px[W] < 0: XSIGN = -1 else: XSIGN = +1 if Py[W] < 0: YSIGN = -1 elif Py[W] == 0: YSIGN = 0 else: YSIGN = +1 x = np.append(Px[W], Px[W] + XSIGN * WL[0, :]) y = np.append(Py[W], Py[W] + YSIGN * WL[1, :]) z = np.append(Pz[W], Pz[W]) tck, u = interpolate.splprep([x, y], k=2) xi, yi = interpolate.splev(np.linspace(0, 1, 100), tck, der=0) zi = np.ones(np.size(yi)) * Pz[W] hsWHISK.append( mlab.plot3d(xi, yi, zi, color=(0, 0, 0), line_width=2)) # rotate all objects angle_x = -90 angle_y = 0 angle_z = -90 for actor in [head, nose, hsE1, hsE2, hsEYE1, hsEYE2, hsPUP1, hsPUP2]: actor.actor.actor.rotate_z(angle_z) actor.actor.actor.rotate_x(angle_x) actor.actor.actor.rotate_y(angle_y) # actor.actor.actor.rotate_y(phi) # actor.actor.actor.rotate_z(theta) actor.actor.actor.rotate_x(theta) actor.actor.actor.rotate_y(phi) for i in range(0, len(hsWHISK)): hsWHISK[i].actor.actor.rotate_z(angle_z) hsWHISK[i].actor.actor.rotate_x(angle_x) hsWHISK[i].actor.actor.rotate_y(angle_y) hsWHISK[i].actor.actor.rotate_x(theta) hsWHISK[i].actor.actor.rotate_y(phi) if head_axes: # axes of head-centered coordinate system visual.set_viewer(fig) arr1 = Arrow3D(0, 0, 0, 0, -6, 0, color=color_head_axes, **arrow_kw) for arr in [arr1]: # , arr2, arr3]: arr.actor.rotate_z(angle_z) arr.actor.rotate_x(angle_x) arr.actor.rotate_y(angle_y) arr.actor.rotate_x(theta) arr.actor.rotate_y(phi) if gravity_axes: # gravitational coordinate system visual.set_viewer(fig) arr1 = Arrow3D(0, 0, 0, -6, 0, 0, color=(.8, .8, .8), **arrow_kw) arr2 = Arrow3D(0, 0, 0, 0, -6, 0, color=(.5, .5, .5), **arrow_kw) arr3 = Arrow3D(0, 0, 0, 0, 0, 6, color=(.25, .25, .25), **arrow_kw) for arr in [arr1, arr2, arr3]: arr.actor.rotate_z(angle_z) arr.actor.rotate_x(angle_x) arr.actor.rotate_y(angle_y) if isometric: fig.scene.isometric_view() else: mlab.view(azimuth=azimuth, elevation=elevation, figure=fig) fig.scene.camera.zoom(zoom) if show_now: mlab.show() img = mlab.screenshot(figure=fig, mode='rgb', antialiased=False) elif backend in ['visvis']: import visvis as vv if ax is None: app = vv.use() fig = vv.figure() ax = vv.subplot(111) else: app = None fig = ax.GetFigure() ax.bgcolor = (1, 1, 1) ax.axis.visible = 0 ax.axis.xLabel = 'x' ax.axis.yLabel = 'y' ax.axis.zLabel = 'z' # head c = -3 [X, Y, Z] = cylinder(r, n=n) head = vv.surf(c + 6 * Z, X, Y) head.faceColor = color_mouse # nose [x, y, z] = sphere(20) nose = vv.surf(c + z * 1.5 + 6, x * 1.5, y * 1.5) nose.faceColor = color_mouse # ears color = (.5, .5, .5) ear1 = vv.surf(c + (z * 0.4) + 0, (x * 1.0) - 2.427, -1 * ((y * 1.8) - 1.763)) ear1.faceColor = color ear2 = vv.surf(c + (z * 0.4) + 0, (x * 1.0) + 2.427, -1 * ((y * 1.8) - 1.763)) ear2.faceColor = color_mouse # eyes [x, y, z] = sphere(10) color = (.9, .9, .9) eye1 = vv.surf(c + (z * .8) + 3.5, (x * .8) - 1.2, -1 * ((y * .8) - 1.6)) eye2 = vv.surf(c + (z * .8) + 3.5, (x * .8) + 1.2, -1 * ((y * .8) - 1.6)) [setattr(eye, 'faceColor', color) for eye in [eye1, eye2]] # pupils color = (.1, .1, .1) pupil1 = vv.surf(c + (z * .3) + 4.147 - .5, (x * .3) - 1.476 - .2, -1 * ((y * .3) - 1.98)) pupil2 = vv.surf(c + (z * .3) + 4.147 - .5, (x * .3) + 1.476 + .2, -1 * ((y * .3) - 1.98)) [setattr(pupil, 'faceColor', color) for pupil in [pupil1, pupil2]] # whiskers Px = np.array([-1.154, -1.214, -1.154, +1.154, +1.214, +1.154]) Py = np.array([-0.375, 0, 0.375, -0.375, 0, 0.375]) Pz = np.ones(np.size(Px)) * 3.882 WL = np.array([[0.5, 2], [0.05, 0.4]]) # whisker length whiskers = [] for W in range(0, len(Px)): # W=0 if Px[W] < 0: XSIGN = -1 else: XSIGN = +1 if Py[W] < 0: YSIGN = -1 elif Py[W] == 0: YSIGN = 0 else: YSIGN = +1 x = np.append(Px[W], Px[W] + XSIGN * WL[0, :]) y = np.append(Py[W], Py[W] + YSIGN * WL[1, :]) z = np.append(Pz[W], Pz[W]) tck, u = interpolate.splprep([x, y], k=2) xi, yi = interpolate.splev(np.linspace(0, 1, 100), tck, der=0) zi = np.ones(np.size(yi)) * Pz[W] whisker = vv.plot(zi, xi, -1 * yi, lw=2, lc=(0, 0, 0)) whiskers.append(whisker) if head_axes: # show vector indicating orientation of head length = 1 shrink = .825 if pitch is not None and roll is not None: # convert pitch/roll to spherical coordinates by rotating # a reference point around cartesian axes; note that x and # y are swapped in visvis p0 = np.array([0, 0, 1]) a = np.deg2rad(roll) Rx = np.array([[1, 0, 0], [0, np.cos(a), -np.sin(a)], [0, np.sin(a), np.cos(a)]]) b = np.deg2rad(pitch) Ry = np.array([[np.cos(b), 0, np.sin(b)], [0, 1, 0], [-np.sin(b), 0, np.cos(b)]]) direction = np.dot(Ry, np.dot(Rx, p0)) * length else: direction = sph2cart(length, theta, phi, degrees=True).ravel() cyl = vv.solidCylinder(translation=(0, 0, .25), scaling=(.05, .05, shrink * length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = (.25, .95, .8) cyl.do_not_rotate = True cyl.do_not_scale = True translation = direction * shrink + np.array([0, 0, .25]) cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = (.25, .95, .8) cone.do_not_rotate = True cone.do_not_scale = True if gravity_axes: # show vector indicating (negative) orientation of gravity length = 1 shrink = .825 color = (.75, .75, .75) direction = np.array([0, 0, 1]) cyl = vv.solidCylinder(translation=(0, 0, .25), scaling=(.05, .05, shrink * length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = color cyl.do_not_rotate = True cyl.do_not_scale = True translation = direction * shrink + np.array([0, 0, .25]) cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = color cone.do_not_rotate = True cone.do_not_scale = True # compute pitch and/or roll if not given if pitch is None or roll is None: # we have to find rotations (=angles) between the unit vector # in spherical coordinates (1, theta, phi) and the planes # for pitch (y/z) and roll (x/z); note that xyz is already # normaizeed (norm = 1) xyz = sph2cart(1, theta, phi, degrees=True).ravel() if pitch is None: # pitch (y/z plane with normal vector (1, 0, 0)) pitch = 90 - np.degrees(np.arccos(np.dot(xyz, [1, 0, 0]))) if roll is None: # roll (x/z plane with normal vector (0, -1, 0)) roll = 90 - np.degrees(np.arccos(np.dot(xyz, [0, -1, 0]))) for obj in ax.wobjects: if not hasattr(obj, 'do_not_scale'): rot = vv.Transform_Scale(sx=.25, sy=.25, sz=.25) obj.transformations.append(rot) if obj.__class__ != vv.core.axises.CartesianAxis and\ not hasattr(obj, 'do_not_rotate'): # note that x and y are swapped rot = vv.Transform_Rotate(pitch, ax=0, ay=1, az=0) obj.transformations.append(rot) rot = vv.Transform_Rotate(roll, ax=1, ay=0, az=0) obj.transformations.append(rot) zoom = vv.view()['zoom'] if isometric: vv.view(dict(azimuth=90 + ISO_AZIMUTH, elevation=ISO_ELEVATION), zoom=4 * zoom, axes=ax) else: vv.view(dict(azimuth=90 + azimuth, elevation=elevation), zoom=4 * zoom, axes=ax) ax.light0.ambient = light_ambient ax.light0.specular = light_specular fig.DrawNow() if app is not None: app.ProcessEvents() img = vv.screenshot(None, ob=ax, sf=2, bg=None, format=None) if close_figure: vv.close(fig) fig = None return fig, img
import visvis as vv import numpy as np from matplotlib.image import imread from matplotlib.cbook import get_sample_data app = vv.use() imgdata = imread(get_sample_data('test0.png')) for i in range(144): globals()['imgdata%s' % i] = imread(get_sample_data('test'+str(i)+'.png')) nr, nc = imgdata.shape[:2] x,y = np.mgrid[:nr, :nc] z = np.ones((nr, nc)) for s in range(10): vv.surf(x, y, z*s*50, globals()['imgdata%s' % s]) app.Run()
astro = astro[100:-100, 100:-100, :] # Smooth a bit im = astro.copy() im[1:, :, :] = astro[:-1, :, :] im[:-1, :, :] += astro[1:, :, :] im[:, :-1, :] += astro[:, 1:, :] im[:, 1:, :] += astro[:, :-1, :] im /= 4 # Prepare figure vv.figure() # Without color, with colormap a1 = vv.subplot(121) m1 = vv.surf(im[:, :, 0]) m1.colormap = vv.CM_HOT vv.title('With colormap') # With color a2 = vv.subplot(122) m2 = vv.surf(im[:, :, 0], im) vv.title('With original texture') # Flip y-axis, otherwise the image is upside down a1.daspect = 1, -1, 1 a2.daspect = 1, -1, 1 # Enter mainloop app = vv.use() app.Run()
m = vv.Mesh(axes, vertices, faces, values=texcoords, verticesPerFace=4) # Should we apply a texture? if c is not None and c.ndim==3: m.SetTexture(c) # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Return axes.Draw() return m if __name__ == "__main__": # Read image and smooth a bit lena = vv.imread('lena.png').astype(np.float32) im = lena.copy() im[1:,:,:] = lena[:-1,:,:] im[:-1,:,:] += lena[1:,:,:] im[:,:-1,:] += lena[:,1:,:] im[:,1:,:] += lena[:,:-1,:] im /= 4 # Surf m = vv.surf(im[:,:,0], im)
#'multiquadric': sqrt((r/self.epsilon)**2 + 1) #'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1) #x2 = np.linspace(min(x2), max(x2)) #y2 = np.linspace(min(y2), max(y2)) #X2, Y2 = np.meshgrid(x2, y2) # interpolación Z = spline(X, Y) Z1 = spline1(X, Y) #Visualización con visvis f = visvis.gca() m = visvis.plot(x, y, z, lc='k', ls='', mc='g', mw=10, lw=10, ms='.') f.daspect = 1, 1, 10 # z x 10 #m = visvis.surf(xi,yi,Z) m = visvis.surf(xi, yi, Z) m = visvis.grid(xi, yi, Z1) m.colormap = visvis.CM_JET f.axis.visible = True #m = visvis.surf(x2,y2,Z2) #m.colormap = visvis.CM_JET #Volumen en cada interpolación con respecto a los puntos: #volume = Convexhull(xyz).volume # Necesario para que la vista no se cierre app = visvis.use() #Movimiento cámara en 3 dimensiones (FPS)
lena = lena[100:-100,100:-100, :] # Smooth a bit im = lena.copy() im[1:,:,:] = lena[:-1,:,:] im[:-1,:,:] += lena[1:,:,:] im[:,:-1,:] += lena[:,1:,:] im[:,1:,:] += lena[:,:-1,:] im /= 4 # Prepare figure vv.figure() # Without color, with colormap a1 = vv.subplot(121) m1 = vv.surf(im[:,:,0]) m1.colormap = vv.CM_HOT vv.title('With colormap') # With color a2 = vv.subplot(122) m2 = vv.surf(im[:,:,0], im) vv.title('With original texture') # Flip y-axis, otherwise the image is upside down a1.daspect = 1,-1,1 a2.daspect = 1,-1,1 # Enter mainloop app=vv.use() app.Run()
def visualizeDEM(X, Y, Z, scale=1.0): """Создание 3D-модели из вычисленных ранее массивов""" m = visvis.surf(X, Y, scale * Z) m.colormap = visvis.CM_JET app = visvis.use() app.Run()
polypp.append(i, polynom[0]*i**2 + polynom[1]*i + polynom[2]) # Visualize vv.subplot(121) vv.plot([-1,0,1],pp) vv.plot([t_max, t_max], [0,1], lc='r') vv.plot(polypp, lc='r') ## 2D # Input and result im = vv.imread('astronaut.png')[::,::,2].copy() Y,X = np.where(im==im.max()) Y,X = Y[0], X[0] im[Y-1,X] -= 20 # make more interesting :) mat = im[Y-1:Y+2, X-1:X+2] # Get result and scale mat ymin, ymax, surface = fitting.fit_lq2(mat, True) mat = Aarray(mat, sampling=(100, 100), origin=(50, 50)) # Visualize vv.subplot(122) vv.imshow(mat) m = vv.surf(surface) a = vv.gca() a.SetLimits() m.colormap = vv.CM_MAGMA
def plot3d(self, img, bodies={ 'pose3d': np.empty((0, 13, 3)), 'pose2d': np.empty((0, 13, 2)) }, hands={ 'pose3d': np.empty((0, 21, 3)), 'pose2d': np.empty((0, 21, 2)) }, faces={ 'pose3d': np.empty((0, 84, 3)), 'pose2d': np.empty((0, 84, 2)) }, body_with_wrists=[], body_with_head=[], interactive=False): """ :param img: a HxWx3 numpy array :param bodies: dictionnaroes with 'pose3d' (resp 'pose2d') with the body 3D (resp 2D) pose :param faces: same with face pose :param hands: same with hand pose :param body_with_wrists: list with for each body, a tuple (left_hand_id, right_hand_id) of the index of the hand detection attached to this body detection (-1 if none) for left and right hands :parma body_with_head: list with for each body, the index of the face detection attached to this body detection (-1 if none) :param interactive: whether to open the viewer in an interactive manner or not """ # body pose do not use the same coordinate systems bodies['pose3d'][:, :, 0] *= -1 bodies['pose3d'][:, :, 1] *= -1 # Compute 3D scaled representation of each part, stored in "points3d" hands, bodies, faces = [copy.copy(s) for s in (hands, bodies, faces)] parts = (hands, bodies, faces) for part in parts: part['points3d'] = np.zeros_like(part['pose3d']) for part_idx in range(len(part['pose3d'])): points3d = scale_orthographic(part['pose3d'][part_idx], part['pose2d'][part_idx]) part['points3d'][part_idx] = points3d # Various display tricks to make the 3D visualization of full-body nice # (1) for faces, add a Z offset to faces to align them with the body for body_id, face_id in enumerate(body_with_head): if face_id != -1: z_offset = bodies['points3d'][body_id, 12, 2] - np.mean( faces['points3d'][face_id, :, 2]) faces['points3d'][face_id, :, 2] += z_offset # (2) for hands, add a 3D offset to put them at the wrist location for body_id, (lwrist_id, rwrist_id) in enumerate(body_with_wrists): if lwrist_id != -1: hands['points3d'][lwrist_id, :, :] = bodies['points3d'][ body_id, 7, :] - hands['points3d'][lwrist_id, 0, :] if rwrist_id != -1: hands['points3d'][rwrist_id, :, :] = bodies['points3d'][ body_id, 6, :] - hands['points3d'][rwrist_id, 0, :] img = np.asarray(img) height, width = img.shape[:2] fig = vv.figure(1) fig.Clear() fig._SetPosition(0, 0, self.figsize[0], self.figsize[1]) if not interactive: fig._enableUserInteraction = False axes = vv.gca() # Hide axis axes.axis.visible = False scaling_factor = 1.0 / height # Camera interaction is not intuitive along z axis # We reference every object to a parent frame that is rotated to circumvent the issue ref_frame = vv.Wobject(axes) ref_frame.transformations.append(vv.Transform_Rotate(-90, 1, 0, 0)) ref_frame.transformations.append( vv.Transform_Translate(-0.5 * width * scaling_factor, -0.5, 0)) # Draw image if self.display2d: # Display pose in 2D img = visu.visualize_bodyhandface2d(img, dict_poses2d={ 'body': bodies['pose2d'], 'hand': hands['pose2d'], 'face': faces['pose2d'] }, lw=2, max_padding=0, bgr=False) XX, YY = np.meshgrid([0, width * scaling_factor], [0, 1]) img_z_offset = 0.5 ZZ = img_z_offset * np.ones(XX.shape) # Draw image embedded_img = vv.surf(XX, YY, ZZ, img) embedded_img.parent = ref_frame embedded_img.ambientAndDiffuse = 1.0 # Draw a grid on the bottom floor to get a sense of depth XX, ZZ = np.meshgrid( np.linspace(0, width * scaling_factor, 10), img_z_offset - np.linspace(0, width * scaling_factor, 10)) YY = np.ones_like(XX) grid3d = vv.surf(XX, YY, ZZ) grid3d.parent = ref_frame grid3d.edgeColor = (0.1, 0.1, 0.1, 1.0) grid3d.edgeShading = 'plain' grid3d.faceShading = None # Draw pose for part in parts: for part_idx in range(len(part['points3d'])): points3d = part['points3d'][part_idx] * scaling_factor # Draw bones J = len(points3d) is_body = (J == 13) ignore_neck = False if not is_body else body_with_head[ part_idx] != -1 bones, bonecolors, pltcolors = visu._get_bones_and_colors( J, ignore_neck=ignore_neck) for (kpt_id1, kpt_id2), color in zip(bones, bonecolors): color = color[2], color[1], color[0] # BGR vs RGB p1 = visu._get_xyz(points3d, kpt_id1) p2 = visu._get_xyz(points3d, kpt_id2) pointset = vv.Pointset(3) pointset.append(p1) pointset.append(p2) # Draw bones as solid capsules bone_radius = 0.005 line = vv.solidLine(pointset, radius=bone_radius) line.faceColor = color line.ambientAndDiffuse = 1.0 line.parent = ref_frame # Draw keypoints, except for faces if J != 84: keypoints_to_plot = points3d if ignore_neck: # for a nicer display, ignore head keypoint keypoints_to_plot = keypoints_to_plot[:12, :] # Use solid spheres for i in range(len(keypoints_to_plot)): kpt_wobject = vv.solidSphere( translation=keypoints_to_plot[i, :].tolist(), scaling=1.5 * bone_radius) kpt_wobject.faceColor = (255, 0, 0) kpt_wobject.ambientAndDiffuse = 1.0 kpt_wobject.parent = ref_frame # Use just an ambient lighting axes.light0.ambient = 0.8 axes.light0.diffuse = 0.2 axes.light0.specular = 0.0 cam = vv.cameras.ThreeDCamera() axes.camera = cam #z axis cam.azimuth = -45 cam.elevation = 20 cam.roll = 0 # Orthographic camera cam.fov = 0 if self.camera_zoom is None: cam.zoom *= 1.3 # Zoom a bit more else: cam.zoom = self.camera_zoom if self.camera_location is not None: cam.loc = self.camera_location cam.SetView() if interactive: self.app.Run() else: fig._widget.update() self.app.ProcessEvents() img3d = vv.getframe(vv.gcf()) img3d = np.clip(img3d * 255, 0, 255).astype(np.uint8) # Crop gray borders img3d = img3d[10:-10, 10:-10, :] return img3d, img
def updatePlot(self, X, Y, Z): self.activePlot = (X,Y,Z) x, y = np.meshgrid(X,Y) vv.clf() surface = vv.surf(x,y,Z) surface.colormap = vv.CM_HOT
r = 5 + (np.sqrt((gray + 1)) - 1) * scalefactor # Equirectangular parametric equations to convert 2D map to 3D projection x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) #+ 0.5* sin(sqrt(x**2 + y**2)) * cos(2*theta) # ____ _ _ # | _ \| | ___ | |_ # | |_) | |/ _ \| __| # | __/| | (_) | |_ # |_| |_|\___/ \__| vv.figure() vv.axis('off') k = vv.surf(x, y, z, img) # If you turn on edge shading, things get weird k.faceShading = 'smooth' k.edgeShading = None Rot = vv.Transform_Rotate(1) k.transformations.insert(0, Rot) axes = vv.gca() # Zoom axes.SetLimits(margin=0.0) axes.SetLimits(margin=0.0, rangeX=(-1, 1)) # Control lighting #axes.bgcolor='k' # axes.light0.ambient = 0.0 # 0.2 is default for light 0
def plot_density_sphere(xyz_centers, H, ax=None, method='hist', azimuth=None, elevation=None, backend='visvis', oversample=1, smoothing=None, zoom=1.7, cmap='jet', scaling='log', log_offset=-.1, clim=None, isometric=False, light_ambient=.6, light_specular=.5, avg_direction=None, pitch_label=True, roll_label=True, pitch_arrow=True, roll_arrow=True, arrow_color=(.25, .95, .8), close_figure=False): if azimuth is None: azimuth = DEFAULT_AZIMUTH if elevation is None: elevation = DEFAULT_ELEVATION scaling = scaling.lower() if scaling.startswith('log'): H = H / float(H.sum()) v = H > 0 if scaling == 'log': H[v] = np.log(H[v]) elif scaling == 'log2': H[v] = np.log2(H[v]) H[~v] = H[v].min() + log_offset if smoothing is not None and smoothing > 1: x = np.linspace(-3., 3., smoothing) xx, yy = np.meshgrid(x, x) G = np.exp((-xx**2 - yy**2)) H = signal.convolve2d(H, G / G.sum(), mode='same', boundary='wrap') if backend in ['mpl', 'matplotlib']: if ax is None: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') from matplotlib.colors import LightSource ls = LightSource(azdeg=315, altdeg=45) cm = getattr(plt.cm, cmap) colors = ls.shade(H, cmap=cm, blend_mode='soft', vert_exag=1) ax.plot_surface(xyz_centers[:, 0].reshape(H), xyz_centers[:, 1].reshape(H), xyz_centers[:, 2].reshape(H), cstride=1, rstride=1, facecolors=colors, linewidth=0, antialiased=False, shade=False) # add arrows in front of sphere import mousecam_helpers as helpers arrow_props = dict(arrowstyle='simple', mutation_scale=15, mutation_aspect=None, linewidth=.5, facecolor=3 * [.75], edgecolor=3 * [.1]) length = .6 arr = helpers.Arrow3D((1, 1 + length), (0, 0), (0, 0), **arrow_props) ax.add_artist(arr) arr = helpers.Arrow3D((0, 0), (1, 1 + length), (0, 0), **arrow_props) ax.add_artist(arr) arr = helpers.Arrow3D((0, 0), (0, 0), (1, 1 + length), **arrow_props) ax.add_artist(arr) extents = 3 * [[-.6, .6]] ax.auto_scale_xyz(*extents) ax.set_aspect('equal') ax.axis('off') ax.view_init(elev=elevation, azim=360 - azimuth) elif backend in ['mayavi', 'mlab']: from mayavi import mlab fig = mlab.figure(bgcolor=(1, 1, 1), size=(1000, 1000)) fig.scene.parallel_projection = True mlab.mesh(xyz_centers[:, 0].reshape(H.shape), xyz_centers[:, 1].reshape(H.shape), xyz_centers[:, 2].reshape(H.shape), scalars=H, colormap='jet') from tvtk.tools import visual visual.set_viewer(fig) arrow_kw = dict(color=(.75, .75, .75), length_cone=.1, radius_cone=.05, radius_shaft=.025) Arrow3D(0, 0, 0, 1.4, 0, 0, **arrow_kw) Arrow3D(0, 0, 0, 0, 1.4, 0, **arrow_kw) Arrow3D(0, 0, 0, 0, 0, 1.4, **arrow_kw) if isometric: fig.scene.isometric_view() else: mlab.view(azimuth=-azimuth, elevation=elevation, figure=fig) fig.scene.camera.zoom(zoom) ax = mlab.screenshot(figure=fig, mode='rgb', antialiased=False) elif backend in ['visvis']: import visvis as vv app = vv.use() fig = vv.figure() ax = vv.subplot(111) ax.axis.visible = 0 ax.axis.xLabel = 'x' ax.axis.yLabel = 'y' ax.axis.zLabel = 'z' length = 1.4 for i in range(3): direction = np.zeros((3, )) direction[i] = 1 cyl = vv.solidCylinder(translation=(0, 0, 0), scaling=(.05, .05, length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = (.75, .75, .75) translation = np.zeros((3, )) translation[i] = length cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = (.75, .75, .75) surf = vv.surf(xyz_centers[:, 0].reshape(H.shape), xyz_centers[:, 1].reshape(H.shape), xyz_centers[:, 2].reshape(H.shape), H, axes=ax) # set colormap cmap = cmap.lower() if cmap.endswith('_r'): cm = vv.colormaps[cmap[:-2]] cm = cm[::-1] else: cm = vv.colormaps[cmap] surf.colormap = cm if clim is not None: # apply colormap limits surf.clim = clim # ax.Draw() # add labels to indicate pitch and/or roll axes aa = np.deg2rad(np.linspace(45, 315, 100) - 90) r = .25 + .05 d = 1.25 + .25 color = (.25, .25, .25) if pitch_arrow: # pitch rotation (in x/z plane, i.e. around y-axis) xx = r * np.cos(aa) zz = r * np.sin(aa) yy = d * np.ones_like(xx) vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax) translation = (xx[0], yy[0], zz[0]) direction = (xx[0] - xx[1], yy[0] - yy[1], zz[0] - zz[1]) cone = vv.solidCone(translation=translation, scaling=(.05, .05, .1), direction=direction, axesAdjust=False, axes=ax) cone.faceColor = color if pitch_label: vv.Text(ax, 'Pitch', x=0, y=.9 * d, z=.5, fontSize=28, color=color) if roll_arrow: # roll rotation (in y/z plane, i.e. around x-axis) yy = r * np.cos(aa[::-1]) zz = r * np.sin(aa[::-1]) xx = d * np.ones_like(xx) vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax) translation = (xx[0], yy[0], zz[0]) direction = (xx[0] - xx[1], yy[0] - yy[1], zz[0] - zz[1]) cone = vv.solidCone(translation=translation, scaling=(.05, .05, .1), direction=direction, axesAdjust=False, axes=ax) cone.faceColor = color if roll_label: vv.Text(ax, 'Roll', x=1.25 * d, y=-.8, z=0, fontSize=28, color=color) if avg_direction is not None: # indicate direction of avg head orientation avg_direction = avg_direction / np.sqrt(np.sum(avg_direction**2)) avg_direction *= length cyl = vv.solidCylinder(translation=(0, 0, 0), scaling=(.05, .05, length), direction=tuple(avg_direction), axesAdjust=False, axes=ax) cyl.faceColor = arrow_color cone = vv.solidCone(translation=tuple(avg_direction), scaling=(.1, .1, .2), direction=tuple(avg_direction), axesAdjust=False, axes=ax) cone.faceColor = arrow_color zoom_ = vv.view()['zoom'] if isometric: vv.view(dict(azimuth=90 + ISO_AZIMUTH, elevation=ISO_ELEVATION), zoom=zoom_ * zoom, axes=ax) else: vv.view(dict(azimuth=90 + azimuth, elevation=elevation), zoom=zoom * zoom_, axes=ax) ax.light0.ambient = light_ambient ax.light0.specular = light_specular fig.DrawNow() app.ProcessEvents() img = vv.screenshot(None, ob=ax, sf=2, bg=None, format=None) ax = img if close_figure: vv.close(fig) fig = None return fig, ax