使用matplotlib和for循环保存许多图像的快速方法



我注意到以下两种使用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()  # <--------

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

  1. 删除以前绘制的轴图像(从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)

最新更新