我想使用Matplotlib生成的圖作爲OpenGL中的紋理。我到目前爲止遇到的matplotlib的OpenGL後端要麼是不成熟的,要麼是已經停產的,所以我想避免它們。matplotlib:渲染到緩衝區/訪問像素數據
我目前的做法是將數字保存到臨時.png文件中,我可以從中組合紋理地圖集。不過,我寧願避免存儲中間文件,直接從matplotlib獲取像素數據。這可能以某種方式嗎?
我在找的答案是fig.canvas.print_to_buffer()
。喬的答案包含其他值得檢查的選擇。
我想使用Matplotlib生成的圖作爲OpenGL中的紋理。我到目前爲止遇到的matplotlib的OpenGL後端要麼是不成熟的,要麼是已經停產的,所以我想避免它們。matplotlib:渲染到緩衝區/訪問像素數據
我目前的做法是將數字保存到臨時.png文件中,我可以從中組合紋理地圖集。不過,我寧願避免存儲中間文件,直接從matplotlib獲取像素數據。這可能以某種方式嗎?
我在找的答案是fig.canvas.print_to_buffer()
。喬的答案包含其他值得檢查的選擇。
當然,只需使用fig.canvas.tostring_rgb()
即可將rgb緩衝區轉儲爲字符串。
同樣,如果您還需要alpha通道,還有fig.canvas.tostring_argb()
。
如果要將緩衝區轉儲到文件,則有fig.canvas.print_rgb
和fig.canvas.print_rgba
(或等同於print_raw
,它是rgba)。
您需要在傾倒緩衝區前用tostring*
來繪製圖形。 (即調用fig.canvas.tostring_rgb()
之前做fig.canvas.draw()
)
只是爲了好玩,這裏是一個相當愚蠢的例子:
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()
謝謝你指着我這個方向努力。有一個'fig.canvas.print_to_buffer()'這似乎正是我正在尋找! – kazemakase
喬,有沒有辦法在屏幕上顯示3個子圖中的前2個? –
@JamesSynge - 當然,每次抓住它的內容時都要清楚這個圖。作爲一個有趣的例子(我寫這個時,我最初寫的答案):https://gist.github.com/joferkington/9138655 –