简体   繁体   English

Mayavi 可以渲染背景透明的人物场景吗?

[英]Can Mayavi render a figure scene with a transparent background?

I am generating a mesh plot using mayavi.mlab and want the background opacity to be 0. (or transparent).我正在使用 mayavi.mlab 生成网格图,并希望背景不透明度为 0。(或透明)。 Is this possible?这可能吗?

If your goal is to integrate the mayavi figure into a matplotlib figure, this is possible.如果您的目标是将 mayavi 图形集成到 matplotlib 图形中,这是可能的。 You can use mlab.screenshot to get a numpy array of RGBA values, and mlab will set background pixels to have alpha 0 automatically.您可以使用mlab.screenshot获取 RGBA 值的 numpy 数组, mlab会自动将背景像素设置为 alpha 0 You can then add this RGBA matrix to a matplotlib figure via imshow .然后,您可以通过imshow将此 RGBA 矩阵添加到 matplotlib 图。 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')

mayavi 网格图合成到 matplotlib 线图上

You can also just save the RGBA array directly to file using plt.imsave(arr=imgmap, fname="foo.png")您也可以使用plt.imsave(arr=imgmap, fname="foo.png")将 RGBA 数组直接保存到文件中

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但是,您可以使用背景颜色(不同于前景色)保存图形并使用 ImageMagick 删除背景

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现在使用 ImageMagick 去除背景

convert pure_beauty.png -transparent white pure_transparent_beauty.png

like shown here .就像这里所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM