问题描述
我想将用matplotlib生成的图用作OpenGL中的纹理.到目前为止,我遇到的matplotlib的OpenGL后端不成熟或已停产,所以我想避免使用它们.
I want to use plots generated with matplotlib as textures in OpenGL. The OpenGL backends for matplotlib I came across so far are either immature or discontinued, so I want to avoid them.
我目前的方法是将图形保存到临时的.png文件中,从中组合纹理图集.但是,我宁愿避免存储中间文件,而是直接从matplotlib获取像素数据.这有可能吗?
My current approach is to save figures into temporary .png files from which I assemble texture atlases. However, I would prefer to avoid storing intermediate files and get pixel data directly from matplotlib instead. Is this possible somehow?
我一直在寻找的答案是fig.canvas.print_to_buffer()
.乔的答案包含其他值得一试的替代方法.
The answer I was looking for is fig.canvas.print_to_buffer()
. Joe's answer contains other alternatives worth checking out.
推荐答案
当然,只需使用fig.canvas.tostring_rgb()
将rgb缓冲区转储到字符串中即可.
Sure, just use fig.canvas.tostring_rgb()
to dump the rgb buffer to a string.
类似地,如果您还需要Alpha通道,则还有fig.canvas.tostring_argb()
.
Similarly, there's fig.canvas.tostring_argb()
if you need the alpha channel, as well.
如果要将缓冲区转储到文件,则有fig.canvas.print_rgb
和fig.canvas.print_rgba
(或等价的print_raw
,即rgba).
If you want to dump the buffer to a file, there's fig.canvas.print_rgb
and fig.canvas.print_rgba
(or equivalently, print_raw
, which is rgba).
在使用tostring*
转储缓冲区之前,您需要绘制图形. (即在调用fig.canvas.tostring_rgb()
之前先执行fig.canvas.draw()
)
You'll need to draw the figure before dumping the buffer with tostring*
. (i.e. do fig.canvas.draw()
before calling fig.canvas.tostring_rgb()
)
只是为了好玩,这是一个很愚蠢的例子:
Just for fun, here's a rather silly example:
import matplotlib.pyplot as plt
import numpy as np
def main():
t = np.linspace(0, 4*np.pi, 1000)
fig1, ax = plt.subplots()
ax.plot(t, np.cos(t))
ax.plot(t, np.sin(t))
inception(inception(fig1))
plt.show()
def fig2rgb_array(fig):
fig.canvas.draw()
buf = fig.canvas.tostring_rgb()
ncols, nrows = fig.canvas.get_width_height()
return np.fromstring(buf, dtype=np.uint8).reshape(nrows, ncols, 3)
def inception(fig):
newfig, ax = plt.subplots()
ax.imshow(fig2rgb_array(fig))
return newfig
main()
这篇关于matplotlib:渲染到缓冲区/访问像素数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!