15
在Python和Matplotlib中,很容易將繪圖顯示爲彈出窗口或將繪圖另存爲PNG文件。我怎樣才能將繪圖保存爲RGB格式的數組?Matplotlib:將繪圖保存爲numpy數組
在Python和Matplotlib中,很容易將繪圖顯示爲彈出窗口或將繪圖另存爲PNG文件。我怎樣才能將繪圖保存爲RGB格式的數組?Matplotlib:將繪圖保存爲numpy數組
當您需要對保存的圖進行像素到像素的比較時,這對於單元測試等是非常方便的技巧。
一種方法是使用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,))
非常好! 12345 – Petter
這隻支持某些後端?似乎沒有找到'macosx'後端('tostring_rgb')。 – mirosval
Works on Agg,在'import matplotlib.pyplot as plt'之前加'matplotlib.use('agg')'來使用它。 – mirosval