2011-10-19 83 views

回答

35

當您需要對保存的圖進行像素到像素的比較時,這對於單元測試等是非常方便的技巧。

一種方法是使用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

Works on Agg,在'import matplotlib.pyplot as plt'之前加'matplotlib.use('agg')'來使用它。 – mirosval

相關問題