2011-10-19 166 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

相关问题