打印到图像对象

2024-04-25 23:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用imshow()保存一个绘图,因为它返回一个图像对象,如下所示:

image = plt.imshow(list, interpolation=None)

稍后,我想创建许多这些图像的动画,保存在列表中,并将其渲染为视频。(如果这种方法很愚蠢,请让我知道,我担心我做错了什么。)

anim = animation.ArtistAnimation(fig, images, interval=15, blit=True)

但是我不知道我怎么能用两个子地块的图形做同样的事情。难道不应该有一个函数返回图像对象吗

list = [[1,2,3,4,5,6,7,8],
        [1,2,3,4,5,6,7,8]]
list2 = [[1,2,3,4,5,6,7,8],
        [1,2,3,4,5,6,7,8]]

fig = plt.figure()

ax = fig.add_subplot(2, 1, 1)
ax.imshow(list, interpolation=None)

ax2 = fig.add_subplot(2, 1, 2)
ax2.imshow(list, interpolation=None)

plt.show()

我不想显示绘图,而是想将其保存为图像对象。 我的目标是创建一个动画(许多情节)并将其渲染为视频。也许我的方法是错误的。有更好的解决办法吗


Tags: 对象方法图像noneadd绘图视频fig
3条回答
plt.savefig('someimgname.jpg')

这样就行了。但请记住,在完成此操作后,使用Image.Open()打开此操作,此操作将起作用

im  = Image.open('someimgname.jpg')
im.show() # or do whatever you want to do with this image object

示例代码:

from matplotlib import pyplot as plt
from PIL import Image

list = [[1,2,3,4,5,6,7,8],
        [1,2,3,4,5,6,7,8]]
list2 = [[1,2,3,4,5,6,7,8],
        [1,2,3,4,5,6,7,8]]

fig = plt.figure()

ax = fig.add_subplot(2, 1, 1)
ax.imshow(list, interpolation=None)

ax2 = fig.add_subplot(2, 1, 2)
ax2.imshow(list, interpolation=None)
plt.savefig('someimgname.jpg')
im = Image.open("someimgname.jpg")  # desired image object
im.show()
plt.show()

参考资料:

  1. Pillow Reference
  2. Matplotlib Reference

好的,回答的第二部分,当我检查文档中的matplotlib.pyplot.savefig(*args, **kwargs)时,它说

第一个参数fnameA path, or a Python file-like object, or possibly some backend-dependent object such as

在python中,类文件对象是StringIO对象

buf = io.BytesIO()
plt.savefig(buf, format='jpg')
buf.seek(0)
im = Image.open(buf)

从python文档来看,它更有意义:-

In-memory streams: It is also possible to use a str or bytes-like object as a file for both reading and writing. For strings StringIO can be used like a file opened in text mode. BytesIO can be used like a file opened in binary mode. Both provide full read-write capabilities with random access.

示例代码:(内存中的

from matplotlib import pyplot as plt
from PIL import Image
import io

list = [[1,2,3,4,5,6,7,8],
        [1,2,3,4,5,6,7,8]]
list2 = [[1,2,3,4,5,6,7,8],
        [1,2,3,4,5,6,7,8]]

fig = plt.figure()

ax = fig.add_subplot(2, 1, 1)
ax.imshow(list, interpolation=None)

ax2 = fig.add_subplot(2, 1, 2)
ax2.imshow(list, interpolation=None)
plt.show()
buf = io.BytesIO()
plt.savefig(buf, format='jpg')
buf.seek(0)
im = Image.open(buf)
im.show()

参考: 3. Python docs

您可以使用:

plt.savefig('name.png')

您可以将其保存到“内存中”缓冲区,如下所示:

# Save PNG to memory buffer as BytesIO
from io import BytesIO
buffer = BytesIO()

plt.savefig(buffer,format='png')
PNG = buffer.getvalue()

如果您的意思是希望从中获得PIL/枕头图像:

reloadedPILImage = Image.open(buffer)

相关问题 更多 >