2011-10-19 15 views
15

PythonとMatplotlibでは、プロットをポップアップウィンドウとして表示するか、プロットをPNGファイルとして保存するのは簡単です。代わりに、プロットをRGB形式の数値配列に保存する方法はありますか?Matplotlib:numpy配列にプロットを保存

答えて

35

これは、保存されたプロットとピクセルとピクセルの比較を行う必要があるときに、単体テストなどの便利なトリックです。

1つの方法は、fig.canvas.tostring_rgb、次にnumpy.fromstringを適切なdtypeで使用することです。他の方法もありますが、これは私が使用する傾向があります。

など。

import matplotlib.pyplot as plt 
import numpy as np 

# Make a random plot... 
fig = plt.figure() 
fig.add_subplot(111) 

# If we haven't already shown or saved the plot, then we need to 
# draw the figure first... 
fig.canvas.draw() 

# Now we can save it to a numpy array. 
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') 
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) 
+0

優秀! 12345 – Petter

+0

これは特定のバックエンドでのみサポートされていますか? 'macosx'バックエンド(' tostring_rgb')が見つからないと思われません。 – mirosval

+1

Aggで動作し、 'matplotlib.pyplot as plt'をインポートする前に' matplotlib.use( 'agg') 'を追加して使用してください。 – mirosval

関連する問題