我注意到以下兩種使用 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() # <--------
uj5u.com熱心網友回復:
第一個選項可以通過幾種方式改進。
- 洗掉之前繪制的 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)
- 或者,為每個軸創建一次 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352901.html
上一篇:for回圈嵌套在for回圈中
下一篇:根據條件從上一組中選擇值
