如何将pylab图保存到可以读入PIL图像的内存文件中?

时间:2011-12-22 02:02:24

标签: python python-imaging-library matplotlib

PIL新手,但希望从中获得快速解决方案。以下是我的第一个从未发挥作用的镜头:

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()

错误说,

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")

任何想法?我不希望解决方案涉及额外的包,谢谢。

2 个答案:

答案 0 :(得分:71)

请记得致电buf.seek(0),以便Image.open(buf)开始阅读 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()

答案 1 :(得分:3)

我喜欢将其封装在函数中

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

然后我可以这样轻松地称呼它:

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()