Matplotlib将画布转换为RGBA



我正在尝试修改机器人工具箱,以显示具有特定背景颜色的动画。我成功地实现了实时显示,它在RGBA中渲染颜色,但在将其保存为GIF时,我失去了透明度。

据我所知,这里是显示图像并生成图像的函数。我添加了self.fig.set_facecolor(color)(color是0到1之间的四个值的元组(。

def getframe(self, color=False):
global _pil
if _pil is None:
try:
import PIL
_pil = PIL.Image.frombytes
except ImportError:  # pragma nocover
pass
if _pil is None:
raise RuntimeError(
"to save movies PIL must be installed:npip3 install PIL"
)
# make the background white, looks better than grey stipple
if isinstance(color, Boolean):
self.ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
self.ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
self.ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
else:
self.ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
self.ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
self.ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
self.fig.set_facecolor(color)

plt.gcf().canvas.draw()
# render the frame and save as a PIL image in the list
canvas = self.fig.canvas
return _pil("RGB", canvas.get_width_height(), canvas.tostring_rgb())

我试着把最后一行改成

return _pil("RGBA", canvas.get_width_height(), canvas.tostring_rgb())

但我得到了一个ValueError: not enough image data,我想这是因为函数tostring_rgb去除了透明度。

然后我在文档中看到有一个tostring_argb函数,但是,因为Alpha在开头,所以图像完全错误。如何将我的画布转换为RGBA(或将ARGB转换为RGBA(?

提前感谢

我找到了将画布转换为RGBA的方法,return应该替换为:

return _pil("RGBA", canvas.get_width_height(), bytes(canvas.get_renderer().buffer_rgba())

然而,我意识到GIF不使用alpha透明度(它可以是完全透明的,也可以是完全不透明的,但不能在中间(。然后,我将格式更改为.apng(动画PNG(。

最新更新