0

尝试使用 matplotlib 写入 iostream,然后在另一个 matplotlib 图中显示该数据(从以下开始:将 Matplotlib savefig 写入 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] invalid mode ('rb') or filename: 'iVBORw...followed by a long string with the data from the image'

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

谢谢参观。

4

1 回答 1

1

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()
于 2017-10-30T08:50:21.957 回答