【问题标题】:speed up plotting images in matplotlib加快在 matplotlib 中绘制图像
【发布时间】:2016-02-09 16:32:31
【问题描述】:

我在 Spyder IDE 中编写了一些 Python 来并排绘制一对图像,以便我可以直观地检查它们。大部分时间我只需要 3 秒来查看它们,但每隔一段时间我需要更长的时间来仔细查看。因此,我没有使用 time.sleep,而是将其编码为等待我按下 Enter 键,如下所示:

import matplotlib.pyplot as plt
import os

def VI_segmentation():
    root = os.getcwd()
    NR_dir = root + '\\Neurite_Results\\'
    SO_dir = root + '\\Segmentation_Overlays\\'
    jpgs = os.listdir(NR_dir)
    fig = plt.figure(figsize=(20,12))
    for jpg in jpgs:
        fig.suptitle(jpg , fontsize=14, fontweight='bold')
        image_NR = plt.imread(NR_dir + jpg)
        image_SO = plt.imread(SO_dir + jpg)
        plt.subplot(121)
        plt.imshow(image_NR)
        plt.subplot(122)
        plt.imshow(image_SO)
        plt.draw()
        plt.pause(0.01)

        input('Press Enter to continue')

VI_segmentation()

问题是我的思维速度比我的电脑快:)。计算机需要 5 或 6 秒才能响应 Enter 键,并在响应后再过几秒钟进行更新。在浏览数百张大部分都很好的图像时,会导致糟糕的人体工程学。任何简化此代码的想法将不胜感激。

【问题讨论】:

  • 因为除了你之外没有人拥有这些图片,你需要提供更多信息。至少在您的机器上运行缓慢的原因,请阅读有关分析的内容:stackoverflow.com/questions/5478351/…

标签: python matplotlib spyder


【解决方案1】:

这个版本的代码最终解决了我的问题:

import matplotlib.pyplot as plt
import os

def VI_segmentation():
    plt.ion()
    root = os.getcwd()
    NR_dir = root + '\\Neurite_Results\\'
    SO_dir = root + '\\Segmentation_Overlays\\'
    jpgs = os.listdir(NR_dir)
    f = plt.figure(figsize=(22,12))
    ax1 = f.add_subplot(121)
    ax2 = f.add_subplot(122)
    image_NR = plt.imread(NR_dir + jpgs[0])
    image_SO = plt.imread(SO_dir + jpgs[0])
    im1 = ax1.imshow(image_NR)
    im2 = ax2.imshow(image_SO) 
    f.suptitle(jpgs[0] , fontsize=14, fontweight='bold')
    f.show()
    plt.pause(0.01)
    input('Press Enter to continue')

    for jpg in jpgs[1:]:
        f.suptitle(jpg , fontsize=14, fontweight='bold')
        image_NR = plt.imread(NR_dir + jpg)
        image_SO = plt.imread(SO_dir + jpg)
        im1.set_data(image_NR)
        im2.set_data(image_SO)
        f.canvas.draw()
        plt.pause(0.01)
        input('Press Enter to continue')

VI_segmentation()

关键是更改图中的数据,而不是添加新图。这个答案对我很有帮助。

Why does my pylab animation slow down with each update?

奇怪的是,当我开始更改绘图数据而不是重新绘图时,我开始出现奇怪的行为,即图形会放大但周围的窗口不会。不知何故,这个 fig.set_size_inches 坏了,所以我围绕图形创建和轴创建移动,以便在制作图形时设置图形大小。

【讨论】:

    【解决方案2】:

    您可以更改 matplotlib 后端并检查哪个更适合您的绘图。

    您可以按照答案中的说明尝试 GTKAgg 后端:https://stackoverflow.com/a/30655528/2632856

    尝试在您的 matplotlib 导入语句之后添加第二行代码。

    import matplotlib
    matplotlib.use('GTKAgg')
    

    您可以尝试其他后端。请参阅此链接了解可用的后端,http://matplotlib.org/faq/usage_faq.html#what-is-a-backend

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多