python - 在函数中更新 matplotlib 图像

标签 python matplotlib

我有一个处理图像的循环,我希望在每 100 次迭代时(比如说)使用 matplotlib 在单个输出窗口中显示图像。所以我试图编写一个函数,它将采用 numpy 张量作为输入并显示相应的图像。

这是我所拥有的不起作用的内容:

def display(image):
  global im

  # If  im has been initialized, update it with the current image; otherwise initialize im and update with current image.   
  try:
    im
    im.set_array(image)
    plt.draw()
  except NameError:
    im = plt.imshow(image, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)
    plt.show(block=False)
    plt.draw()

我一开始试图通过 FuncAnimation 传递它,但这似乎是为了让动画调用函数来进行更新,而不是在 matplotlib 上调用函数来显示结果。

上面的代码打开一个窗口,但它似乎没有更新。有人能指出我正确的方向吗?

非常感谢,

贾斯汀

最佳答案

也许您可以组合使用:

第一个将重新绘制图形,而第二个将调用 GUI 事件循环来更新图形。

此外,您不需要每次都调用 imshow,在“im”对象上调用“set_data”方法就足够了。类似的东西应该有效:

import matplotlib.pyplot as plt
import numpy

fig,ax = plt.subplots(1,1)
image = numpy.array([[1,1,1], [2,2,2], [3,3,3]])
im = ax.imshow(image)

while True:       
    image = numpy.multiply(1.1, image)
    im.set_data(image)
    fig.canvas.draw_idle()
    plt.pause(1)

改编自this回答。希望对您有所帮助。

关于python - 在函数中更新 matplotlib 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51520143/

相关文章:

python - 是否可以将坐标拟合到 OSMnx 中的街道?

python - 在Python中根据 channel 条件替换图像像素颜色

python - 如何在 Tkinter 中找出 PhotoImage 的大小?

python - matplotlib NavigationToolbar2 回调(例如release_zoom())语法示例?

Python getattr 默认值评估

python - 如何比较R中两个向量的分布?

python - matplotlib:在堆叠散点图中对齐 y 轴标签

python - 导入错误: cannot import name 'ft2font' from partially initialized module 'matplotlib'

python - matplotlib/cartopy Mollweide 投影中经度环绕的接缝

python - 在 Python 3.5.1 中使用 pylab.scatter 和 cmap