我正在使用mayavi.mlab生成网格图,并希望将背景透明度设置为0(或透明)。这可能吗?
如果您的目标是将mayavi图形集成到matplotlib图形中,则可以实现此目标。您可以使用mlab.screenshot
获取RGBA值的numpy数组,并且mlab
会自动将背景像素的alpha设置为0
。然后,您可以通过imshow
将这个RGBA矩阵添加到matplotlib图形中。示例(改编自这里):
import numpy as np
from mayavi import mlab
import matplotlib.pyplot as plt
# set up some plotting params
dphi, dtheta = np.pi / 250.0, np.pi / 250.0
[phi, theta] = np.mgrid[0:np.pi + dphi * 1.5:dphi,
0:2 * np.pi + dtheta * 1.5:dtheta]
m0, m1, m2, m3 = 4, 3, 2, 3
m4, m5, m6, m7 = 6, 2, 6, 4
r = np.sin(m0 * phi) ** m1 + np.cos(m2 * phi) ** m3 + \
np.sin(m4 * theta) ** m5 + np.cos(m6 * theta) ** m7
x = r * np.sin(phi) * np.cos(theta)
y = r * np.cos(phi)
z = r * np.sin(phi) * np.sin(theta)
# do the meshplot
fig = mlab.figure(size=(480, 340))
mlab.mesh(x, y, z, colormap='cool', figure=fig)
imgmap = mlab.screenshot(figure=fig, mode='rgba', antialiased=True)
mlab.close(fig)
# do the matplotlib plot
fig2 = plt.figure(figsize=(7, 5))
plt.imshow(imgmap, zorder=4)
plt.plot(np.arange(0, 480), np.arange(480, 0, -1), 'r-')
plt.savefig('example.png')
您也可以直接使用plt.imsave(arr=imgmap, fname="foo.png")
将RGBA数组保存为文件。
mayavi
版本 4.5.0
和 matplotlib
版本 1.5.1
。 - ryanjdillonmlab.figure(size = (1024,768),\
bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5))
# Your fantastic plotting script
mlab.save('pure_beauty.png')
convert pure_beauty.png -transparent white pure_transparent_beauty.png
就像这里所示的那样。