【发布时间】:2019-10-26 16:17:36
【问题描述】:
如何加快 matplotlib 图到 numpy 数组之间的转换? 我的程序创建了数百万个图,并且对于每个图,我想返回其 numpy 数组(我不关心查看或保存图!我只关心转换为 numpy 数组)。
我设法使用以下代码进行了转换:
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
不幸的是,由于我在开头使用:fig = plt.figure(num=1),在结尾使用plt.clf(),因此程序将图像一张一张地显示在图中,这会减慢所有速度(大约每秒 1 到 2 帧)。
我正在寻找一种更快的解决方案,将 matplotlib 图转换为 numpy 数组。
更新
我进行了 aggbackend 更改,但没有任何改进,我错在哪里? 我附上我的代码:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import imageio
from Game import Init, Draw, Game_step
images = []
Init()
fig = plt.figure(num=1)
Draw()
fig.canvas.draw()
for stp in range(100):
action_button = np.random.randint(4)
observation = Game_step(action_button)
Draw()
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
images.append(data)
imageio.mimsave("game.gif", images, duration=1 / 35)
当Init:初始化游戏,Draw:在matplotlib中绘制当前游戏截图,Game_step:在游戏环境中采取一个动作 目标是获取每个屏幕图的np数组
(我使用 Imagio 只是为了检查,但它是多余的)
【问题讨论】:
-
在不开启交互模式的情况下尝试使用
agg后端。 -
好的,经过一番调查,我认为问题来自循环行:fig.canvas.draw()。毫无疑问,没有它,我在尝试使用 .canvas.tostring_rgb() 时收到错误消息。还有其他方法可以将绘图转换为 nparray 吗?我应该使用 FuncAnimate 还是 pyqtgraph 之类的东西?
-
不,您应该使用 agg 后端并关闭交互模式。
-
谢谢,我试过了,还是没有改善。我附在我的完整代码上方。我做错了什么?
标签: python matplotlib