【问题标题】:Fast way of saving many images with matplotlib and for loop使用 matplotlib 和 for 循环保存许多图像的快速方法
【发布时间】:2021-11-08 11:54:23
【问题描述】:

我注意到以下两种使用 matplotlib 加载和保存图像的解决方案之间存在很大的性能差距。谁能解释为什么,以及在 python for 循环中保存图像的最佳(和最快)方法是什么?

实施 1: 在 for 循环之外创建一个图形,更新显示的内容然后保存。

fig, a = plt.subplots(1, 3, figsize=(30, 20))  # <--------

# list_of_fnames is just a list of file names
for k, fname in enumerate(list_of_fnames):
    with Image.open(fname) as img:
        x = np.array(img)

    y = process_image_fn1(x)
    z = process_image_fn2(x)

    a[0].imshow(x)
    a[1].imshow(y)
    a[2].imshow(z)

    output_filename = f'results_{k}.png'
    plt.savefig(output_filename, dpi=320, format='png', transparent=False, bbox_inches='tight', pad_inches=0)

实施 2: 在 for 循环中创建一个图形,保存它,最后销毁它。

# list_of_fnames is just a list of file names
for k, fname in enumerate(list_of_fnames):
    with Image.open(fname) as img:
        x = np.array(img)

    y = process_image_fn1(x)
    z = process_image_fn2(x)

    fig, a = plt.subplots(1, 3, figsize=(30, 20))  # <--------
    a[0].imshow(x)
    a[1].imshow(y)
    a[2].imshow(z)

    output_filename = f'results_{k}.png'
    plt.savefig(output_filename, dpi=320, format='png', transparent=False, bbox_inches='tight', pad_inches=0)

    plt.close()  # <--------

【问题讨论】:

  • 我想第一个非常慢,因为保存的文件越来越大。每次循环迭代,您都在向每个子图添加越来越多的图像。
  • 我也有同样的嫌疑人。在 for 循环的每次迭代中,除了关闭并创建一个新图形之外,还有其他选择吗?我的意思是,有没有办法在不增大我保存的文件的情况下重复使用相同的数字(即plt.subplots 的输出)?
  • 每次循环可以清轴或清图

标签: python for-loop matplotlib


【解决方案1】:

第一个选项可以通过多种方式进行改进。

  1. 删除之前绘制的 AxesImages(来自 imshow),这样您就不会不断增加轴上绘制的图像数量
fig, a = plt.subplots(1, 3, figsize=(30, 20))  # <--------

# list_of_fnames is just a list of file names
for k, fname in enumerate(list_of_fnames):

    for ax in a:
        ax.images.pop()

    with Image.open(fname) as img:
        x = np.array(img)

    y = process_image_fn1(x)
    z = process_image_fn2(x)

    a[0].imshow(x)
    a[1].imshow(y)
    a[2].imshow(z)

    output_filename = f'results_{k}.png'
    plt.savefig(output_filename, dpi=320, format='png', transparent=False, bbox_inches='tight', pad_inches=0)
  1. 或者,为每个轴创建一次 AxesImages,而不是每次迭代都重新绘制它们,而是使用 .set_array() 更改 AxesImage 上绘制的内容
fig, a = plt.subplots(1, 3, figsize=(30, 20))  # <--------

# list_of_fnames is just a list of file names
for k, fname in enumerate(list_of_fnames):
    with Image.open(fname) as img:
        x = np.array(img)

    y = process_image_fn1(x)
    z = process_image_fn2(x)

    if k == 0:
        im0 = a[0].imshow(x)
        im1 = a[1].imshow(y)
        im2 = a[2].imshow(z)
    else:
        im0.set_array(x)
        im1.set_array(y)
        im2.set_array(z)

    output_filename = f'results_{k}.png'
    plt.savefig(output_filename, dpi=320, format='png', transparent=False, bbox_inches='tight', pad_inches=0)

【讨论】:

  • 第一个解决方案似乎对我不起作用
猜你喜欢
  • 1970-01-01
  • 2021-09-09
  • 2017-08-16
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多