Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save a pylab figure into in-memory file which can be read into PIL image?

The following is my first shot which never works:

import cStringIO import pylab from PIL import Image pylab.figure() pylab.plot([1,2]) pylab.title("test") buffer = cStringIO.StringIO() pylab.savefig(buffer, format='png') im = Image.open(buffer.read()) buffer.close() 

the error says,

Traceback (most recent call last):   File "try.py", line 10, in <module>     im = Image.open(buffer.read())   File "/awesomepath/python2.7/site-packages/PIL/Image.py", line 1952, in open     fp = __builtin__.open(fp, "rb") 

any ideas? I don't want the solution to involve extra packages.

like image 568
nye17 Avatar asked Dec 22 '11 02:12

nye17


People also ask

How do I save a figure to a file in Matplotlib?

Matplotlib plots can be saved as image files using the plt. savefig() function. The plt. savefig() function needs to be called right above the plt.

How do I save a Matplotlib file as a JPEG?

To save plot figure as JPG or PNG file, call savefig() function on matplotlib. pyplot object. Pass the file name along with extension, as string argument, to savefig() function.

Is PyLab and Matplotlib same?

PyLab is a procedural interface to the Matplotlib object-oriented plotting library. Matplotlib is the whole package; matplotlib. pyplot is a module in Matplotlib; and PyLab is a module that gets installed alongside Matplotlib. PyLab is a convenience module that bulk imports matplotlib.


2 Answers

Remember to call buf.seek(0) so Image.open(buf) starts reading from the beginning of the buf:

import io from PIL import Image import matplotlib.pyplot as plt  plt.figure() plt.plot([1, 2]) plt.title("test") buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) im = Image.open(buf) im.show() buf.close() 
like image 130
unutbu Avatar answered Sep 22 '22 08:09

unutbu


I like having it encapsulated in a function:

def fig2img(fig):     """Convert a Matplotlib figure to a PIL Image and return it"""     import io     buf = io.BytesIO()     fig.savefig(buf)     buf.seek(0)     img = Image.open(buf)     return img 

Then I can call it easily this way:

import numpy as np import matplotlib.pyplot as plt from PIL import Image  x = np.arange(-3,3) plt.plot(x) fig = plt.gcf()  img = fig2img(fig) img.show() 
like image 29
kotchwane Avatar answered Sep 24 '22 08:09

kotchwane