【发布时间】: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