def saveScreenshots(self,filename): if(self.status == self.playing): self.playPause() self.status = self.paused vv.screenshot(str(filename +'_figure.png'), self.axes) self.spectrogram.screenshot(str(filename +'_spec.png'))
def OnKey(event): """ Called when a key is pressed down in the axes. """ import visvis as vv global shot_counter, filename_prefix, file_format if event.text and event.text.lower() in 's': current_filename = "%s-%02d.%s" % (filename_prefix, shot_counter, file_format) print("Saving screenshot as %s" % (current_filename)) vv.screenshot(filename=current_filename, bg="w", sf=3, format=file_format) shot_counter += 1
def savefig(self, widget): chooser = _gtk.FileChooserDialog("Save As...", None, _gtk.FILE_CHOOSER_ACTION_SAVE, (_gtk.STOCK_CANCEL, _gtk.RESPONSE_CANCEL, _gtk.STOCK_SAVE, _gtk.RESPONSE_OK)) chooser.set_default_response(_gtk.RESPONSE_OK) response = chooser.run() filename = None if response == _gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename is not None: visvis.screenshot(filename, self.figure, sf=1)
def savefig(self, widget): chooser = _gtk.FileChooserDialog( "Save As...", None, _gtk.FILE_CHOOSER_ACTION_SAVE, (_gtk.STOCK_CANCEL, _gtk.RESPONSE_CANCEL, _gtk.STOCK_SAVE, _gtk.RESPONSE_OK)) chooser.set_default_response(_gtk.RESPONSE_OK) response = chooser.run() filename = None if response == _gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename is not None: visvis.screenshot(filename, self.figure, sf=1)
def print_result(self, context, render): cr = context.get_cairo_context() height = self._GetPosition()[-1] if render: sf = 2 # Scale factor for rendering. (Note that screenshot # doesn't actually do supersampling yet.) # PIL (used by screenshot) doesn't like pipes. fd, fn = _tempfile.mkstemp() _os.close(fd) visvis.screenshot(fn, self, sf=sf, format="png") image = _cairo.ImageSurface.create_from_png(fn) _os.unlink(fn) cr.scale(1./sf, 1./sf) cr.set_source_surface(image, 0, 0) cr.paint() return height
def print_result(self, context, render): cr = context.get_cairo_context() height = self._GetPosition()[-1] if render: sf = 2 # Scale factor for rendering. (Note that screenshot # doesn't actually do supersampling yet.) # PIL (used by screenshot) doesn't like pipes. fd, fn = _tempfile.mkstemp() _os.close(fd) visvis.screenshot(fn, self, sf=sf, format="png") image = _cairo.ImageSurface.create_from_png(fn) _os.unlink(fn) cr.scale(1. / sf, 1. / sf) cr.set_source_surface(image, 0, 0) cr.paint() return height
def psf_volume(stack, xyz_ratio, filepath): app = vv.use() # Init a figure with two axes a1 = vv.subplot(121) vv.title('PSF Volume') a2 = vv.subplot(122) vv.title('PSF XYZ Cross Sections') # show t1 = vv.volshow(stack, axes=a1) # volume t2 = vv.volshow2(stack, axes=a2) # cross-section interactive # set labels for both axes vv.xlabel('Pixel X', axes=a1) vv.ylabel('Pixel Y', axes=a1) vv.zlabel('Z-Slice', axes=a1) vv.xlabel('Pixel X', axes=a2) vv.ylabel('Pixel Y', axes=a2) vv.zlabel('Z-Slice', axes=a2) # set colormaps t1.colormap = vv.CM_JET t2.colormap = vv.CM_JET # set correct aspect ration corresponding to voxel size a1.daspect = 1, 1, xyz_ratio a2.daspect = 1, 1, xyz_ratio # show grid a1.axis.showGrid = 1 a2.axis.showGrid = 1 # run visvis and show results app.Run() # save screenshot if filepath != 'nosave': print 'Saving PSF volume.' savename = filepath[:-4] + '_PSF_3D.png' # sf: scale factor vv.screenshot(savename, sf=1, bg='w')
def plot_3d_orientation_map(name, lat_data, azth_data, radius_structure_elem=1, output_dir=None, width=512, height=512, camera_azth=44.5, camera_elev=35.8, camera_roll=0.0, camera_fov=35.0, camera_zoom=0.0035, camera_loc=(67.0, 81.6, 45.2), xlabel='', ylabel='', zlabel='', axis_color='w', background_color='k'): """Renders orientation data in 3D with RGB angular color-coding. Parameters ---------- name : str Indicates the name of the output png file. lat_data : 3D array Indicates the 3D array containing latitude / elevation angle at every point of the skeleton in radians. azth_data : 3D array Indicates the 3D array containing azimuth angle at every point of the skeleton in radians. radius_structure_elem : integer Indicates the size of the structure element of the dilation process to thicken the skeleton. output_dir : str Indicates the path to the output folder where the image will be stored. width : int Indicates the width of the visualization window. height : int Indicates the width of the visualization window. camera_azth : float Indicates the azimuth angle of the camera. camera_elev : float Indicates the latitude / elevation angle of the camera. camera_roll : float Indicates the roll angle of the camera. camera_fov : float Indicates the field of view of the camera. camera_zoom : float Indicates the zoom level of the camera. camera_loc : tuple Indicates the camera location. xlabel : str Indicates the label along the x-axis. ylabel : str Indicates the label along the y-axis. zlabel : str Indicates the label along the z-axis. axis_color : str Indicates the color of axes. background_color : str Indicates the background color of the figure. """ if not visvis_available: print( 'The visvis package is not found. The visualization cannot be done.' ) return rmin, rmax, cmin, cmax, zmin, zmax = _bbox_3D(azth_data) azth, lat = azth_data[rmin:rmax, cmin:cmax, zmin:zmax], \ np.abs(lat_data[rmin:rmax, cmin:cmax, zmin:zmax]) skel = azth.copy().astype(np.float32) skel[skel.nonzero()] = 1. azth = ndi.grey_dilation(azth, structure=morphology.ball(radius_structure_elem)) lat = ndi.grey_dilation(lat, structure=morphology.ball(radius_structure_elem)) skel = ndi.binary_dilation( skel, structure=morphology.ball(radius_structure_elem)) Z, Y, X = skel.nonzero() vol_orient = np.zeros(skel.shape + (3, ), dtype=np.float32) print(vol_orient.size, vol_orient[skel.nonzero()].size) for z, y, x in zip(Z, Y, X): vol_orient[z, y, x] = geo2rgb(lat[z, y, x], azth[z, y, x]) app = vv.use() fig = vv.figure() fig._currentAxes = None fig.relativeFontSize = 2. fig.position.w = width fig.position.h = height t = vv.volshow(vol_orient[:, :, :], renderStyle='iso') t.isoThreshold = 0.5 a = vv.gca() a.camera.azimuth = camera_azth a.camera.elevation = camera_elev a.camera.roll = camera_roll a.camera.fov = camera_fov a.camera.zoom = camera_zoom a.camera.loc = camera_loc a.bgcolor = background_color a.axis.axisColor = axis_color a.axis.xLabel = xlabel a.axis.yLabel = ylabel a.axis.zLabel = zlabel # def mouseUp(event): # print 'mouseUp!!' # a = vv.gca() # print a.camera.GetViewParams() # # a.eventMouseUp.Bind(mouseUp) # fig.eventMouseUp.Bind(mouseUp) # # a.Draw() # fig.DrawNow() if output_dir is not None: if not os.path.exists(output_dir): os.makedirs(output_dir) vv.screenshot(os.path.join(output_dir, f'{name}_3d_orientation.png'), sf=1, bg=background_color) app.Run()
def plot_3d_diameter_map(name, data, unit_scale=1.0, measure_quantity='vox', radius_structure_elem=1, output_dir=None, width=512, height=512, camera_azth=44.5, camera_elev=35.8, camera_roll=0.0, camera_fov=35.0, camera_zoom=0.0035, camera_loc=(67.0, 81.6, 45.2), xlabel='', ylabel='', zlabel='', axis_color='w', background_color='k', cb_x_offset=10): """Renders orientation data in 3D with RGB angular color-coding. Parameters ---------- name : str Indicates the name of the output png file. data : 3D array Indicates the 3D array containing diameter at every point of the skeleton. unit_scale : float Indicates the scale factor of the data values. measure_quantity : str Indicates the name of measure of the values. radius_structure_elem : integer Indicates the size of the structure element of the dilation process to thicken the skeleton. output_dir : str Indicates the path to the output folder where the image will be stored. camera_azth : float Indicates the azimuth angle of the camera. width : int Indicates the width of the visualization window. height : int Indicates the width of the visualization window. camera_elev : float Indicates the latitude / elevation angle of the camera. camera_roll : float Indicates the roll angle of the camera. camera_fov : float Indicates the field of view of the camera. camera_zoom : float Indicates the zoom level of the camera. camera_loc : tuple Indicates the camera location. xlabel : str Indicates the label along the x-axis. ylabel : str Indicates the label along the y-axis. zlabel : str Indicates the label along the z-axis. axis_color : str Indicates the color of axes. background_color : str Indicates the background color of the figure. cb_x_offset : int Indicates the offset of the colorbar from the right window side. """ if not visvis_available: print( 'The visvis package is not found. The visualization cannot be done.' ) return rmin, rmax, cmin, cmax, zmin, zmax = _bbox_3D(data) dmtr = data[rmin:rmax, cmin:cmax, zmin:zmax] * unit_scale skel = np.zeros_like(dmtr, dtype=np.uint8) skel[dmtr.nonzero()] = 1 dmtr = ndi.grey_dilation(dmtr, structure=morphology.ball(radius_structure_elem)) skel = ndi.binary_dilation( skel, structure=morphology.ball(radius_structure_elem)).astype(np.float32) skel[skel.nonzero()] = 1. dmtr = dmtr * skel app = vv.use() fig = vv.figure() fig._currentAxes = None fig.relativeFontSize = 2. fig.position.w = width fig.position.h = height t = vv.volshow(dmtr[:, :, :], renderStyle='iso') t.isoThreshold = 0.5 t.colormap = vv.CM_JET a = vv.gca() a.camera.azimuth = camera_azth a.camera.elevation = camera_elev a.camera.roll = camera_roll a.camera.fov = camera_fov a.camera.zoom = camera_zoom a.camera.loc = camera_loc a.bgcolor = background_color a.axis.axisColor = axis_color a.axis.xLabel = xlabel a.axis.yLabel = ylabel a.axis.zLabel = zlabel cb = vv.colorbar() cb.SetLabel(f'Diameter, [{measure_quantity}]') cb._label.position.x += cb_x_offset if output_dir is not None: if not os.path.exists(output_dir): os.makedirs(output_dir) vv.screenshot(os.path.join(output_dir, f'{name}_3d_diameter.png'), sf=1, bg='w') app.Run()
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
def plot_reference_sphere(theta=0, phi=0, isometric=True, ax=None, azimuth=None, elevation=None, degrees=True, labels=True, light_ambient=.6, zoom=1.4, arrow_color=(.25, .95, .8), close_figure=False): if azimuth is None: azimuth = DEFAULT_AZIMUTH if elevation is None: elevation = DEFAULT_ELEVATION 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.axis.visible = 0 ax.axis.xLabel = 'x' ax.axis.yLabel = 'y' ax.axis.zLabel = 'z' # coordinate system length = 1.4 cyl_diameter = .05 for i in range(3): direction = np.zeros((3, )) direction[i] = 1 cyl = vv.solidCylinder(translation=(0, 0, 0), scaling=(cyl_diameter, cyl_diameter, 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) # example direction length = 1 shrink = .825 direction = sph2cart(1, theta, phi, degrees=degrees).ravel() cyl = vv.solidCylinder(translation=(0, 0, 0), scaling=(.05, .05, shrink * length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = arrow_color translation = direction * shrink cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = arrow_color # indicate unit sphere sphere = vv.solidSphere((0, 0, 0), N=100, M=100) sphere.faceColor = (.5, .5, .5, .25) # some lines on sphere indicating main axes phi = np.linspace(0, 2 * np.pi, 100) theta = np.ones_like(phi) * np.pi / 2. r = np.ones_like(phi) xyz = sph2cart(r, theta, phi, degrees=False) vv.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], lw=1, lc=(.5, .5, .5), ls="-", mc='b', axesAdjust=False, axes=ax) theta = np.linspace(-np.pi, np.pi, 100) phi = np.ones_like(theta) * 0 r = np.ones_like(phi) xyz = sph2cart(r, theta, phi, degrees=False) vv.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], lw=1, lc=(.5, .5, .5), ls="-", mc='b', axesAdjust=False, axes=ax) theta = np.linspace(-np.pi, np.pi, 100) phi = np.ones_like(theta) * np.pi / 2. r = np.ones_like(phi) xyz = sph2cart(r, theta, phi, degrees=False) vv.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], lw=1, lc=(.5, .5, .5), ls="-", mc='b', axesAdjust=False, axes=ax) # add pitch and roll axes aa = np.deg2rad(np.linspace(45, 315, 100) - 90) r = .25 + .025 d = 1.25 + .05 color = (.25, .25, .25) # 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 labels: vv.Text(ax, 'Pitch', x=0, y=1.25 * d, z=.25, fontSize=28, color=color) # roll rotation (in y/z plane, i.e. around x-axis) yy = r * np.cos(aa) zz = r * np.sin(aa) xx = d * np.ones_like(xx) vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax) translation = (xx[-1], yy[-1], zz[-1]) direction = (xx[-1] - xx[-2], yy[-1] - yy[-2], zz[-1] - zz[-2]) cone = vv.solidCone(translation=translation, scaling=(.05, .05, .1), direction=direction, axesAdjust=False, axes=ax) cone.faceColor = color if labels: vv.Text(ax, 'Roll', x=1.25 * d, y=-.8, z=0, fontSize=28, color=color) # set camera view 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 = .5 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
D = {0:-3,1:-2,2:-1,3:None} slicey = slice(iy, D[iy]) slicex = slice(ix, D[ix]) # Get contribution and add to temp image imTmp += w * im2[slicey, slicex, :] # Store contributions D = [-1 for tmp in range(s)]; D.append(None) slicey = slice(dy,D[dy],s) slicex = slice(dx,D[dx],s) im3[slicey, slicex, :] = imTmp # Correct for overshoot im3[im3>1]=1 im3[im3<0]=0 # Store image to file if filename is not None: vv.imwrite(filename, im3, format) else: return im3 if __name__ == '__main__': # Make plot vv.plot([1,2,3,1,4,2,3], ms='.') # Take screenshot, twice enlarged, on a white background vv.screenshot('screenshot.jpg', vv.gcf(), sf=2, bg='w')
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
ax5 = vv.subplot(122) #; vv.title('profile5') plot_pattern(*(tt5, aa5)) ax5.axis.showGrid = False ax5.SetLimits(rangeX=(-0.01, 2), rangeY=(-0.02, 2.5)) ax5.axis.showBox = False vv.xlabel('time (s)') vv.ylabel('position (mm)') vv.legend('B5 (A=2.0, T=0.8, extra=0.7, 0.8, 0.05)') f.relativeFontSize = 1.2 if False: exceldir = select_dir(r'C:\Users\Maaike\Desktop', r'D:\Profiles\koenradesma\Desktop') vv.screenshot(os.path.join(exceldir, 'screenshot.png'), f, sf=3, bg=(1, 1, 1)) ## Plot for paper proceedings, patternexample import matplotlib.pyplot as plt from lspeas.analysis.utils_analysis import _initaxis from stentseg.utils.aortamotionpattern import plot_pattern_plt import numpy as np dirsave = select_dir(r'C:\Users\Maaike\Desktop', 'D:\Profiles\koenradesma\Desktop') xlim = (-0.01, 2) ylim = 2.5 major_ticks = np.arange(0, xlim[1], 0.2)
def save_3D_gradient_images(save_path, data, name): """ Makes an avi of the volume rendered gradient specified by the name parameter using visvis """ #load all of the volumes into memory vols = [] #setup the visvis setup to capture all of the images f = vv.clf() a = vv.gca() m = vv.MotionDataContainer(a, interval = 500) #loop over all the times times = data.get_times() mn = 1000000000000 mx = -1 #get the min and max range over which to scale the image set for i in range(0, len(times)): #load the volume vol = data.get_gradient_at_time(times[i], name).C #get the min and max of these to save mx = max(np.max(vol), mx) mn = min(np.min(vol), mn) #delete the loaded volume for memory issues del vol #now take screen shots of these images for i in range(0, len(times)): #load the volume vol = data.get_gradient_at_time(times[i], name).C print(vol.shape) #draw it t = vv.volshow(vol) t.colormap = vv.CM_HOT t.renderstyle = 'iso' t.parent = m #set the camera filed of view a.camera.fov = 60 a.camera.elevation = 30 a.camera.zoom = 0.01 #set the limits to the min and max t.clim = (mn, mx) #Force the axis to draw now a.Draw() f.DrawNow() t_m.sleep(1) #get the zero padded time s = ZeroPad(times[-1], times[i]) #create the save file path file_path = save_path + name + "_" + s + ".jpeg" #Now get the screenshot vv.screenshot(file_path) #load this image using PIL, append a color bar showing the min and max ss = Image.open(file_path) w, h = ss.size #make a new font font = ImageFont.truetype("arial.ttf", 24) color_bar = draw_color_bar(mn, mx, 50, int(.99*h), font) #get the colorbar dimension w1, h1 = color_bar.size #make a new image ht = max(h, h1) im_final = Image.new("RGB", (w + w1 + 10, ht), "white") #paste the other images on to this im_final.paste(color_bar, (w + 10, 0)) im_final.paste(ss, (0, 0)) #Now finally draw the time and the text on top of this draw = ImageDraw.Draw(im_final) #get the text to draw txt = "Species: " + name + " Time: " + repr(times[i]) #gte the position pos = (25, 20) draw.text(pos, txt, font = font, fill = (0,0,0)) #save the final file im_final.save(file_path) #close all the figures vv.closeAll()
removeStent=removeStent, showmodelavgreg=showmodelavgreg, showvol=showvol, phases=phases, colors=colors, meshWithColors=meshWithColors) vv.title('Model for LSPEAS %s - %s' % (ptcode[7:], ctcode3)) axes.append(ax) #bind view control f.eventKeyDown.Bind( lambda event: _utils_GUI.RotateView(event, axes, axishandling=False)) f.eventKeyDown.Bind(lambda event: _utils_GUI.ViewPresets(event, axes)) ## Set view # a1.SetView(view1) # a2.SetView(view2) # a3.SetView(view3) ## Use same camera #a1.camera = a2.camera = a3.camera if False: a = vv.gca() a.camera = ax.camera ## Save figure if False: vv.screenshot(r'D:\Profiles\koenradesma\Desktop\ZA3_phase90.jpg', vv.gcf(), sf=2) #phantom validation manuscript
a5 = vv.subplot(245) vv.title('Input image') vv.imshow(im, clim=clim, cm=cmap) # a6 = vv.subplot(246) vv.title('Backward deform field') vv.imshow(deform_backward[1]) # a7 = vv.subplot(247) vv.title('Backward field vectors') vv.imshow(im_backward, clim=clim, cm=cmap) arrows(pp, vvb, (-0.2, 0.9), lc=veccolor, lw=2, axesAdjust=False) # a8 = vv.subplot(248) vv.title('Vectors scaled by half') vv.imshow(im_backward2, clim=clim, cm=cmap) arrows(pp, vvb2, (-0.2, 0.9), lc=veccolor, lw=2, axesAdjust=False) # for a in [a1, a2, a3, a4]: a.axis.visible = False for a in [a5, a6, a7, a8]: a.axis.visible = False if False: vv.screenshot('~/forwardVSbackward1.jpg', a1, sf=2) vv.screenshot('~/forwardVSbackward2.jpg', a2, sf=2) vv.screenshot('~/forwardVSbackward3.jpg', a3, sf=2) vv.screenshot('~/forwardVSbackward4.jpg', a4, sf=2)
D = {0: -3, 1: -2, 2: -1, 3: None} slicey = slice(iy, D[iy]) slicex = slice(ix, D[ix]) # Get contribution and add to temp image imTmp += w * im2[slicey, slicex, :] # Store contributions D = [-1 for tmp in range(s)] D.append(None) slicey = slice(dy, D[dy], s) slicex = slice(dx, D[dx], s) im3[slicey, slicex, :] = imTmp # Correct for overshoot im3[im3 > 1] = 1 im3[im3 < 0] = 0 # Store image to file if filename is not None: vv.imwrite(filename, im3, format) else: return im3 if __name__ == '__main__': # Make plot vv.plot([1, 2, 3, 1, 4, 2, 3], ms='.') # Take screenshot, twice enlarged, on a white background vv.screenshot('screenshot.jpg', vv.gcf(), sf=2, bg='w')