Matplotlib savefig to cStreamIO 然后加载数据到另一个Matplotlib plot/fig Python 2.7

Matplotlib savefig to cStreamIO then load the data into another Matplotlib plot/fig Python 2.7

尝试使用 matplotlib 写入 iostream,然后在另一个 matplotlib 绘图中显示该数据(从以下开始:Write Matplotlib savefig to html)。为了提高效率,我想避免将图像写入磁盘。

代码如下:

import cStringIO
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt2
import matplotlib.image as mpimg

sio = cStringIO.StringIO()
plt.savefig(sio, format='png')

# I should mention at this point here that the sio object is sent through a 
# pipe between two processes (so it has been pickled)    

imgplt = plt2.imshow(mpimg.imread(sio.getvalue().encode("base64").strip()))
# this line generates the following error.  As well as several variations 
#   including specifying 'png'

返回的错误是: IOError:[Errno 22] 无效模式('rb')或文件名:'iVBORw...followed by a long string with the data from the image'

我查看了 image.py 文件,它似乎在寻找文件名。

感谢观看。

imread 将给它的字符串解释为文件名。相反,需要提供一个类似文件的对象。

您会得到类似文件的对象,例如缓冲区本身。但是,StringIO 可能不太适合。如果使用BytesIO,可以直接读入缓冲区。

import io
import matplotlib.pyplot as plt

plt.plot([1,2,4,2])
plt.title("title")

buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)

imgplt = plt.imshow(plt.imread(buf))

plt.show()