2011-10-19 17 views

risposta

35

Questo è un trucco pratico per i test di unità e simili, quando è necessario eseguire un confronto pixel-a-pixel con una trama salvata.

Un modo è utilizzare fig.canvas.tostring_rgb e quindi numpy.fromstring con il tipo appropriato. Ci sono anche altri modi, ma questo è quello che tendo ad usare.

E.g.

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

Eccellente! 12345 – Petter

+0

È supportato solo su determinati back-end? Sembra che non funzioni con 'macosx' backend (' tostring_rgb') non trovato. – mirosval

+1

Funziona su Agg, aggiungi 'matplotlib.use ('agg')' prima di 'import matplotlib.pyplot as plt' per usarlo. – mirosval