本文整理汇总了Python中mayavi.mlab.savefig函数的典型用法代码示例。如果您正苦于以下问题:Python savefig函数的具体用法?Python savefig怎么用?Python savefig使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了savefig函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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')
示例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)
示例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
示例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()
示例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)
示例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()
示例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)
示例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'])
示例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
示例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)
示例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])
示例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!
示例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()
示例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)