本文整理汇总了Python中mayavi.mlab.savefig函数的典型用法代码示例。如果您正苦于以下问题:Python savefig函数的具体用法?Python savefig怎么用?Python savefig使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了savefig函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: m2screenshot
def m2screenshot(mayavi_fig=None, mpl_axes=None, autocrop=True):
""" Capture a screeshot of the Mayavi figure and display it in the
matplotlib axes.
"""
import pylab as pl
# Late import to avoid triggering wx imports before needed.
try:
from mayavi import mlab
except ImportError:
# Try out old install of Mayavi, with namespace packages
from enthought.mayavi import mlab
if mayavi_fig is None:
mayavi_fig = mlab.gcf()
else:
mlab.figure(mayavi_fig)
if mpl_axes is not None:
pl.axes(mpl_axes)
filename = tempfile.mktemp('.png')
mlab.savefig(filename, figure=mayavi_fig)
image3d = pl.imread(filename)
if autocrop:
bg_color = mayavi_fig.scene.background
image3d = autocrop_img(image3d, bg_color)
pl.imshow(image3d)
pl.axis('off')
os.unlink(filename)
开发者ID:FNNDSC,项目名称:nipy,代码行数:28,代码来源:maps_3d.py
示例2: run_plots
def run_plots(DataDirectory,Base_file):
root = DataDirectory+Base_file
filenames = get_filenames(root)
counter = 0
# create the plot for the initial raster
initial_file = filenames[0]
# read in the raster
raster = IO.ReadRasterArrayBlocks(initial_file)
f = mlab.figure(size=(1000,1000), bgcolor=(0.5,0.5,0.5))
s = mlab.surf(raster, warp_scale=0.4, colormap='gist_earth', vmax=100)
#mlab.outline(color=(0,0,0))
#mlab.axes(s, color=(1,1,1), z_axis_visibility=True, y_axis_visibility=False, xlabel='', ylabel='', zlabel='', ranges=[0,500,0,1000,0,0])
#@mlab.animate(delay=10)
#def anim():
# now loop through each file and update the z values
for fname in filenames:
this_rast = IO.ReadRasterArrayBlocks(fname)
s.mlab_source.scalars = this_rast
#f.scene.render()
#
mlab.savefig(fname[:-4]+'_3d.png')
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:27,代码来源:3d_elev_animations.py
示例3: plot_channel
def plot_channel(self,fn_hist,fn_corrvec,fn_arrows):
list_channel = self.list_channel
import matplotlib.pyplot as plt
# plot vecs
plt.figure()
#vecs = np.array((3,len(list_channel)))
for i in range(3):
vecs = [chan.vec[i] for chan in list_channel]
plt.hist(vecs,bins=100)
plt.savefig(fn_hist)
# plot corr vecs
plt.figure()
v0 = [chan.vec[0] for chan in list_channel]
v1 = [chan.vec[1] for chan in list_channel]
v2 = [chan.vec[2] for chan in list_channel]
plt.plot(v0,v1,"o")
plt.plot(v0,v2,"o")
plt.plot(v1,v2,"o")
plt.savefig(fn_corrvec)
# cluster
import matplotlib.pyplot as plt
import mayavi.mlab as mlab
#from mlab import quiver3d
mlab.options.backend = 'envisage' # one way to save visualization
#f = mlab.figure()
mlab.figure()
x = [np.zeros(v.shape) for v in v0]
mlab.quiver3d(x,x,x,v0,v1,v2)
mlab.savefig(fn_arrows)
开发者ID:annekegh,项目名称:saman,代码行数:29,代码来源:ringfunc.py
示例4: plot_mcontour
def plot_mcontour(self, ndim0, ndim1, z, show_mode):
"use mayavi.mlab to plot contour."
if not mayavi_installed:
self.__logger.info("Mayavi is not installed on your device.")
return
#do 2d interpolation
#get slice object
s = np.s_[0:ndim0:1, 0:ndim1:1]
x, y = np.ogrid[s]
mx, my = np.mgrid[s]
#use cubic 2d interpolation
interpfunc = interp2d(x, y, z, kind='cubic')
newx = np.linspace(0, ndim0, 600)
newy = np.linspace(0, ndim1, 600)
newz = interpfunc(newx, newy)
#mlab
face = mlab.surf(newx, newy, newz, warp_scale=2)
mlab.axes(xlabel='x', ylabel='y', zlabel='z')
mlab.outline(face)
#save or show
if show_mode == 'show':
mlab.show()
elif show_mode == 'save':
mlab.savefig('mlab_contour3d.png')
else:
raise ValueError('Unrecognized show mode parameter : ' +
show_mode)
return
开发者ID:nickirk,项目名称:VASPy,代码行数:29,代码来源:electro.py
示例5: Main
def Main(outputFolder, isData, normalized = True):
assert isinstance(outputFolder, str)
min, max = 0., 1.
if os.path.splitext(args.file)[1] == '.arff':
datasets, targets, targetMap = loadFromArff(args.file)
elif os.path.splitext(args.file)[1] == '.npy':
datasets = numpy.load(args.file)
min = -1.
else:
assert False
datasets = (lambda x : histogramEqualization(x, min=min, max=max) if normalized else x)(datasets)
if normalized : assert (datasets.min(), datasets.max()) == (min, max)
if not os.path.isdir("%s/Pictures" % outputFolder):
os.makedirs("%s/Pictures" % outputFolder)
global listIndex
if listIndex is None or (len(listIndex) >= len(datasets)):
listIndex = xrange(len(datasets))
for index in listIndex:
assert 0 <= index < len(datasets)
mlab.figure("Index : %d" % index, bgcolor=(1,1,1))
showArray(datasets[index], isData)
mlab.savefig("%s/Pictures/Index_%d.png" % (outputFolder, index))
if isData:
saveData('%s/Pictures/%s_Index_%d.txt' % (outputFolder, targetMap.reverse_mapping[targets[index]], index), datasets[index])
else:
saveData('%s/Pictures/Index_%d.txt' % (outputFolder, index), datasets[index])
mlab.close()
开发者ID:mehdidc,项目名称:boosting,代码行数:31,代码来源:ILC_showDataset.py
示例6: snapshot
def snapshot(cuds, filename):
""" Save a snapshot of the cuds object using the default visualisation.
Parameters
----------
cuds :
A top level cuds object (e.g. a mesh). The method will detect
the type of object and create the appropriate visualisation.
filename : string
The filename to use for the output file.
"""
# adapt to CUDSSource
if isinstance(cuds, (ABCMesh, ABCParticles, ABCLattice)):
source = CUDSSource(cuds=cuds)
else:
msg = 'Provided object {} is not of any known cuds type'
raise TypeError(msg.format(type(cuds)))
# set image size
size = 800, 600
with get_figure(size=size):
# add source
mlab.pipeline.add_dataset(source)
modules = default_module(source)
# add default modules
for module in modules:
source.add_module(module)
mlab.savefig(filename, size=size)
开发者ID:simphony,项目名称:simphony-mayavi,代码行数:34,代码来源:snapshot.py
示例7: savefig
def savefig(filename,mlabview=[],magnification = 3):
"""
Save mayavi figure
Parameters
----------
name : str
name of the figure
mlabview : [] | (x,y,z, np.array([ xroll,yroll,zroll]))
specifyy angle of camera view ( see mayavi.view )
magnification : int
resolution of the generated image ( see mayavi.savefig)
"""
import os
path = os.path.dirname(filename)
if not mlabview == []:
mlab.view(mlabview)
if os.path.exists(path):
mlab.savefig(filename+'.png',magnification=magnification )
else:
os.mkdir(path)
mlab.savefig(filename+'.png',magnification=magnification )
mlab.close()
开发者ID:mmhedhbi,项目名称:pylayers,代码行数:27,代码来源:mayautil.py
示例8: example
def example():
# setup movie
m = movie(frame_rate=22.5)
# setup example
from mayavi import mlab
mlab.options.offscreen = True
mlab.test_contour3d()
f = mlab.gcf()
# save frames
for i in range(36*3):
f.scene.camera.azimuth(10) # rotate
f.scene.render()
mlab.savefig(m.next_frame(), figure=f)
# encode frames
encoded = m.encode()
# remove tempdir
del m
if not encoded:
# report error
exit(m.output)
开发者ID:jvb,项目名称:infobiotics-dashboard,代码行数:25,代码来源:movie.py
示例9: mayavi_scraper
def mayavi_scraper(block, block_vars, gallery_conf):
"""Scrape Mayavi images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
rst : str
The ReSTructuredText that will be rendered to HTML containing
the images. This is often produced by
:func:`sphinx_gallery.gen_rst.figure_rst`.
"""
from mayavi import mlab
image_path_iterator = block_vars['image_path_iterator']
image_paths = list()
e = mlab.get_engine()
for scene, image_path in zip(e.scenes, image_path_iterator):
mlab.savefig(image_path, figure=scene)
# make sure the image is not too large
scale_image(image_path, image_path, 850, 999)
image_paths.append(image_path)
mlab.close(all=True)
return figure_rst(image_paths, gallery_conf['src_dir'])
开发者ID:Titan-C,项目名称:sphinx-gallery,代码行数:30,代码来源:scrapers.py
示例10: make_fractal_movie
def make_fractal_movie(seed="X", iter=6):
"""
"""
f = hilbert.VoxelisedFractal.fromSeed(seed, iter)
f.center_fractal()
pos = np.array([vox.pos for vox in f.fractal])
max_pos = np.max(pos, axis=0)
mask = lambda x: np.sum((x[0:3]/max_pos[0:3])**2) <= 1
f = f.to_pretty_plot(refine=5, mayavi=True, mask=mask)
fig = mlab.gcf()
fig.scene.set_size([1024, 768])
fig.scene.render()
mlab.savefig("example/img/fractal_rotate0000.png")
step = 5
for ii in range(1, int(720/step)):
fig.scene.camera.azimuth(step)
fig.scene.render()
mlab.savefig("example/img/fractal_rotate{:04d}.png".format(ii))
mlab.savefig("example/img/fractal_zoom0000.png")
nsteps = 200
for ii in range(nsteps):
fig.scene.camera.zoom(1.02)
fig.scene.render()
mlab.savefig("example/img/fractal_zoom{:04d}.png".format(ii))
for ii in range(nsteps, nsteps + int(720/step)):
fig.scene.camera.azimuth(step)
fig.scene.render()
mlab.savefig("example/img/fractal_zoom{:04d}.png".format(ii))
return None
开发者ID:natl,项目名称:fractaldna,代码行数:31,代码来源:fractal_example.py
示例11: setUp
def setUp(self):
# set up source
sgrid = datasets.generateStructuredGrid()
source = VTKDataSource(data=sgrid)
self.engine = mlab.get_engine()
# set up scene, first scene is empty
# second scene has the settings we want to restore
for _ in range(2):
fig = mlab.figure()
fig.scene.off_screen_rendering = True
# add source
self.engine.add_source(source)
# add more modules
self.engine.add_module(IsoSurface())
self.engine.add_module(Text3D())
self.modules = source.children[0].children
# set camera
self.view = (25., 14., 20., [0., 0., 2.5])
mlab.view(*self.view)
# save the visualisation
self.temp_dir = tempfile.mkdtemp()
self.filename = os.path.join(self.temp_dir, "test_vis.mv2")
self.engine.save_visualization(self.filename)
# save the scene as an image for comparison later
self.ref_saved_filename = os.path.join(self.temp_dir, "ref_saved.png")
mlab.savefig(self.ref_saved_filename)
开发者ID:simphony,项目名称:simphony-mayavi,代码行数:33,代码来源:test_restore_scene.py
示例12: draw_volume
def draw_volume(scalars):
# filts out low data
nmax = np.amax(scalars)
nmin = np.amin(scalars)
#nptp = nmax - nmin
#lowBound = nmin + nptp*0
#for i in np.nditer(scalars, op_flags=['readwrite']):
# if i<lowBound: i[...] = 0
# Get the shape of axes
shape = scalars.shape
# draw
fig = mlab.figure(bgcolor=(0,0,0), size=(800,800) )
src = mlab.pipeline.scalar_field(scalars)
src.update_image_data = True
#src.spacing = [1, 1, 1]
vol = mlab.pipeline.volume(src)
change_volume_property(vol)
#change_test(vol)
#vol = mlab.pipeline.image_plane_widget(src,plane_orientation='z_axes', slice_index=shape[2]/2)
ax = mlab.axes(nb_labels=5, ranges=(0,shape[0],0,shape[1],0,shape[2]))
mlab.savefig("result.jpg")
print "nmax =", nmax
print "nmin =", nmin
viewkeeper = mlab.view()
print "View", mlab.view()
draw_map(shape[0],shape[1])
mlab.view(viewkeeper[0],viewkeeper[1],viewkeeper[2],viewkeeper[3])
开发者ID:HPCGISLab,项目名称:STDataViz,代码行数:34,代码来源:draw_volume.py
示例13: action
def action(u, x, xv, y, yv, t, n):
#print 'action, t=',t,'\nu=',u, '\Nx=',x, '\Ny=', y
if plot == 1:
mesh(xv, yv, u, title='t=%g' %t[n])
time.sleep(0.2) # pause between frames
elif plot == 2:
# mayavi plotting
mlab.clf()
extent1 = (0, 20, 0, 20,-2, 2)
s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1)
mlab.axes(s, color=(.7, .7, .7), extent=extent1,
ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
zlabel='',
x_axis_visibility=False, z_axis_visibility=False)
mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
mlab.text(2, -2.5, '', z=-4, width=0.1)
mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None)
mlab.title('test 1D t=%g' % t[n])
mlab.view(142, -72, 50)
f = mlab.gcf()
camera = f.scene.camera
camera.yaw(0)
if plot > 0:
path = 'Figures_wave2D'
time.sleep(0) # pause between frames
if save_plot and plot != 2:
filename = '%s/%08d.png' % (path, n)
savefig(filename) # time consuming!
elif save_plot and plot == 2:
filename = '%s/%08d.png' % (path,n)
mlab.savefig(filename) # time consuming!
开发者ID:yellowsimulator,项目名称:Blender,代码行数:35,代码来源:wave2D.py
示例14: plot_isosurface
def plot_isosurface(crystal):
filename = './output/potentialfield.txt'
data = np.genfromtxt(filename, delimiter='\t')
size = np.round((len(data))**(1/3))
X = np.reshape(data[:,0], (size,size,size))
Y = np.reshape(data[:,1], (size,size,size))
Z = np.reshape(data[:,2], (size,size,size))
DeltaU = np.reshape(data[:,3], (size,size,size))
average = np.average(crystal.coordinates[:,0])
start = average - crystal.a
end = average + crystal.a
coords1 = np.array([[start, start, start]])
coords2 = np.array([[end, end, end]])
array1 = np.repeat(coords1,len(crystal.coordinates),axis=0)
array2 = np.repeat(coords2,len(crystal.coordinates),axis=0)
basefilter1 = np.greater(crystal.coordinates,array1)
basefilter2 = np.less(crystal.coordinates,array2)
basefilter = np.nonzero(np.all(basefilter1*basefilter2, axis=1))
base = crystal.coordinates[basefilter]
mlab.figure(bgcolor=(1, 1, 1), fgcolor=(1, 1, 1), size=(2048,2048))
dataset = mlab.contour3d(X, Y, Z, DeltaU, contours=[3.50],color=(1,0.25,0))
scatter = mlab.points3d(base[:,0],
base[:,1],
base[:,2],
color=(0.255,0.647,0.88),
resolution=24,
scale_factor=1.0,
opacity=0.40)
mlab.view(azimuth=17, elevation=90, distance=10, focalpoint=[average,average-0.2,average])
mlab.draw()
savename = './output/3Dpotential.png'
mlab.savefig(savename, size=(2048,2048))
mlab.show()
开发者ID:sprakellab,项目名称:dopantdynamics,代码行数:34,代码来源:plotpotential.py
示例15: test_restore_scene
def test_restore_scene(self):
# create a new scene with new data source
fig = mlab.figure()
fig.scene.off_screen_rendering = True
sgrid_2 = datasets.generateStructuredGrid()
source = VTKDataSource(data=sgrid_2)
self.engine.add_source(source)
# when
restore_scene(self.filename, scene_index=1)
# then
modules = source.children[0].children
self.check_items_same_types(modules, self.modules)
self.check_items_not_same_object(modules, self.modules)
self.check_camera_view(mlab.view(), self.view)
# save the scene to a file
saved_filename = os.path.join(self.temp_dir, "test_restore.png")
mlab.savefig(saved_filename)
# compare the pixels to the desired one
self.check_images_almost_identical(saved_filename,
self.ref_saved_filename)
开发者ID:simphony,项目名称:simphony-mayavi,代码行数:26,代码来源:test_restore_scene.py
示例16: vis_breakups
def vis_breakups():
"""
This function allows to visualize break-ups as the highlighted branches in
the original skeleton.
"""
data_sk = glob.glob('/backup/yuliya/vsi05/skeletons_largdom/*.h5')
data_sk.sort()
data_br = glob.glob('/backup/yuliya/vsi05/breakups_con_correction/dict/*.npy')
data_br.sort()
for i,j in zip(data_sk[27:67][::-1], data_br[19:][::-1]):
d = tb.openFile(i, mode='r')
bran1 = np.copy(d.root.branches)
skel1 = np.copy(d.root.skel)
d.close()
br = np.load(j).item()
mlab.figure(1, bgcolor=(1,1,1), size=(1200,1200))
surf_skel = mlab.contour3d(skel1, colormap='hot')
surf_skel.actor.property.representation = 'points'
surf_skel.actor.property.line_width = 2.3
mask = np.zeros_like(skel1)
for k in br:
sl = br[k]
mask[sl] = (bran1[sl] == k)
surf_mask = mlab.contour3d(mask.astype('uint8'))
surf_mask.actor.property.representation = 'wireframe'
surf_mask.actor.property.line_width = 5
mlab.savefig('/backup/yuliya/vsi05/breakups_con_correction/video_hot/' + i[39:-3] + '.png')
mlab.close()
开发者ID:YuliyaKar,项目名称:Skeleton_to_graph-labeling-,代码行数:33,代码来源:graph_vis.py
示例17: short_branches
def short_branches():
"""
Visualization of short branches of the skeleton.
"""
data1_sk = glob.glob('/backup/yuliya/vsi05/skeletons_largdom/*.h5')
data1_sk.sort()
for i,j, k in zip(d[1][37:47], data1_sk[46:56], ell[1][37:47]):
g = nx.read_gpickle(i)
dat = tb.openFile(j)
skel = np.copy(dat.root.skel)
bra = np.copy(dat.root.branches)
mask = np.zeros_like(skel)
dat.close()
length = nx.get_edge_attributes(g, 'length')
number = nx.get_edge_attributes(g, 'number')
num_dict = {}
for m in number:
for v in number[m]:
num_dict.setdefault(v, []).append(m)
find_br = ndimage.find_objects(bra)
for l in list(length.keys()):
if length[l]<0.5*k: #Criteria
for b in number[l]:
mask[find_br[b-1]] = bra[find_br[b-1]]==b
mlab.figure(bgcolor=(1,1,1), size=(1200,1200))
mlab.contour3d(skel, colormap='hot')
mlab.contour3d(mask)
mlab.savefig('/backup/yuliya/vsi05/skeletons/short_bran/'+ i[42:-10] + '.png')
mlab.close()
开发者ID:YuliyaKar,项目名称:Skeleton_to_graph-labeling-,代码行数:32,代码来源:graph_analisys.py
示例18: mark_gt_box3d
def mark_gt_box3d( lidar_dir, gt_boxes3d_dir, mark_dir):
os.makedirs(mark_dir, exist_ok=True)
fig = mlab.figure(figure=None, bgcolor=(0,0,0), fgcolor=None, engine=None, size=(500, 500))
dummy = np.zeros((10,10,3),dtype=np.uint8)
for file in sorted(glob.glob(lidar_dir + '/*.npy')):
name = os.path.basename(file).replace('.npy','')
lidar_file = lidar_dir +'/'+name+'.npy'
boxes3d_file = gt_boxes3d_dir+'/'+name+'.npy'
lidar = np.load(lidar_file)
boxes3d = np.load(boxes3d_file)
mlab.clf(fig)
draw_didi_lidar(fig, lidar, is_grid=1, is_axis=1)
if len(boxes3d)!=0:
draw_didi_boxes3d(fig, boxes3d)
azimuth,elevation,distance,focalpoint = MM_PER_VIEW1
mlab.view(azimuth,elevation,distance,focalpoint)
mlab.show(1)
imshow('dummy',dummy)
cv2.waitKey(1)
mlab.savefig(mark_dir+'/'+name+'.png',figure=fig)
开发者ID:Bruslan,项目名称:MV3D-1,代码行数:26,代码来源:show_lidar.py
示例19: plot_inverse_operator
def plot_inverse_operator(subject, fnout_img=None, verbose=None):
""""Reads in and plots the inverse solution."""
# get name of inverse solution-file
subjects_dir = os.environ.get('SUBJECTS_DIR')
fname_dir_inv = os.path.join(subjects_dir,
subject)
for files in os.listdir(fname_dir_inv):
if files.endswith(",cleaned_epochs_avg-7-src-meg-inv.fif"):
fname_inv = os.path.join(fname_dir_inv,
files)
break
try:
fname_inv
except NameError:
print "ERROR: No forward solution found!"
sys.exit()
# read inverse solution
inv = min_norm.read_inverse_operator(fname_inv)
# print some information if desired
if verbose is not None:
print "Method: %s" % inv['methods']
print "fMRI prior: %s" % inv['fmri_prior']
print "Number of sources: %s" % inv['nsource']
print "Number of channels: %s" % inv['nchan']
# show 3D source space
lh_points = inv['src'][0]['rr']
lh_faces = inv['src'][0]['tris']
rh_points = inv['src'][1]['rr']
rh_faces = inv['src'][1]['tris']
# create figure and plot results
fig_inverse = mlab.figure(size=(1200, 1200),
bgcolor=(0, 0, 0))
mlab.triangular_mesh(lh_points[:, 0],
lh_points[:, 1],
lh_points[:, 2],
lh_faces)
mlab.triangular_mesh(rh_points[:, 0],
rh_points[:, 1],
rh_points[:, 2],
rh_faces)
# save result
if fnout_img is not None:
mlab.savefig(fnout_img,
figure=fig_inverse,
size=(1200, 1200))
mlab.close(all=True)
开发者ID:VolkanChen,项目名称:jumeg,代码行数:59,代码来源:meg_source_localization.py
示例20: anim
def anim():
f = mlab.gcf()
for count, i in enumerate(range(2,361,2)):
#while 1:
f.scene.camera.azimuth(degree_step)
f.scene.render()
mlab.savefig('/Users/jessebrown/Desktop/mayavi_figs/r_hipp_network%03d.png' %count)
yield
开发者ID:lusamino,项目名称:umcp,代码行数:8,代码来源:plot_network.py
注:本文中的mayavi.mlab.savefig函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论