我想使用matplotlib生成的图作为OpenGL中的纹理。我到目前为止遇到的matplotlib的OpenGL后端要么不成熟要么已经停止,所以我想避免它们。
我目前的方法是将数字保存到临时的.png文件中,我从中汇编纹理图集。但是,我宁愿避免存储中间文件,而是直接从matplotlib获取像素数据。这有可能吗?
我要找的答案是fig.canvas.print_to_buffer()
。乔的答案包含值得一试的其他选择。
答案 0 :(得分:15)
当然,只需使用fig.canvas.tostring_rgb()
将rgb缓冲区转储为字符串。
同样,如果你需要alpha通道,还有fig.canvas.tostring_argb()
。
如果要将缓冲区转储到文件,则有fig.canvas.print_rgb
和fig.canvas.print_rgba
(或等效的print_raw
,即rgba)。
在使用tostring*
转储缓冲区之前,您需要绘制图形。 (即在致电fig.canvas.draw()
之前执行fig.canvas.tostring_rgb()
)
只是为了好玩,这是一个相当愚蠢的例子:
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()