2011-10-19 7 views

Répondre

35

Ceci est une astuce pratique pour les tests unitaires et autres, lorsque vous avez besoin de faire une comparaison de pixel à pixel avec un tracé sauvegardé.

Une façon est d'utiliser fig.canvas.tostring_rgb puis numpy.fromstring avec le dtype approprié. Il y a aussi d'autres moyens, mais c'est celui que j'ai tendance à utiliser.

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

Excellent! 12345 – Petter

+0

Est-ce seulement supporté sur certain backend? Ne semble pas fonctionner avec le backend 'macosx' (' tostring_rgb') introuvable. – mirosval

+1

Fonctionne sur Agg, ajoute 'matplotlib.use ('agg')' avant d'importer matplotlib.pyplot comme plt' pour l'utiliser. – mirosval

Questions connexes