python - 加快在 matplotlib 中绘制图像

标签 python matplotlib spyder

我在 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 键,并在响应后再花几秒钟进行更新。在浏览数百张大部分都很好的图像时,会导致糟糕的人体工程学。任何简化此代码的想法都将不胜感激。

最佳答案

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

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 被破坏了,所以我移动了图形创建和轴创建,这样我就可以在制作图形时设置图形大小。

关于python - 加快在 matplotlib 中绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602185/

相关文章:

python - edX LMS 端口 8000 已在使用中(即使在终止进程之后)

python - 将 xarray.plot.line 与颜色图结合使用

python - PyCharm 无法正确打开 matplotlib 图

python - 如何在 Spyder 3.6 中安装 GraphViz

python-3.x - 在 Spyder 中运行 PyQt5 应用程序时,它总是以 -1 退出

python - 如何删除顶部和底部 nth% 的数据

python - python中的嵌套条件

python - pandas 添加迄今为止的日期和基于另一列的天数

python - 如何通过绘图通过 Python doctest

python - 检测 Python 代码在哪里运行(例如,在 Spyder 解释器、IDLE 和 cmd 中)