【问题标题】:return a numpy array from a matplotlib plot is too slow, how can i speed it up?从 matplotlib 图中返回一个 numpy 数组太慢了,我该如何加快速度?
【发布时间】: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


【解决方案1】:

尝试使用plt.ioff() 关闭交互模式。除非您明确调用 draw() 或其他函数,否则这应该会阻止您绘制图形。

关于 ioff() 语义的帖子:Exact semantics of Matplotlib's "interactive mode" (ion(), ioff())?

以及文档链接:https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.ioff.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 2017-12-20
    • 1970-01-01
    • 2021-07-13
    • 2023-03-08
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多