I am generating a mesh plot using mayavi.mlab and want the background opacity to be 0. (or transparent). Is this possible?
Asked
Active
Viewed 6,797 times
7
-
What result are you expecting? More precisely, what do you expect to *do* with this transparent background? Are you trying to create images with some 3D rendered objects on some other background? Or perhaps are you trying to have your window manager composit the scene onto some other background? The first scenario is probably possible with postprocessing help. The second definitely isn't. Give more detail about what you are trying to do. – aestrivex May 19 '14 at 20:14
2 Answers
6
If your goal is to integrate the mayavi figure into a matplotlib figure, this is possible. You can use mlab.screenshot
to get a numpy array of RGBA values, and mlab
will set background pixels to have alpha 0
automatically. You can then add this RGBA matrix to a matplotlib figure via imshow
. Example (adapted from here):
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')
You can also just save the RGBA array directly to file using plt.imsave(arr=imgmap, fname="foo.png")

drammock
- 2,373
- 29
- 40
-
3When I run that exact code, it does not work (i.e. the mayavi figure has a gray background instead of transparent). – Ruben Verresen Oct 28 '16 at 00:56
-
It works just fine for me: `mayavi` version `4.5.0` & `matplotlib` version `1.5.1`. – ryanjdillon Oct 31 '16 at 10:00
2
You cannot set the transparency directly. However, you can save the figure with a background colour (different than the foreground colour) and use ImageMagick to remove the background
For example
mlab.figure(size = (1024,768),\
bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5))
# Your fantastic plotting script
mlab.save('pure_beauty.png')
now use ImageMagick to remove the background
convert pure_beauty.png -transparent white pure_transparent_beauty.png
like shown here.