为什么在使用 tqdm 时调整图像大小的处理时间存在巨大差异?

Why is there a huge difference in processing time in resizing images when using tqdm?

我正在为我关于 Google colab 的论文调整图像大小。但是我用tqdm和不用tqdm的时候有很大的时间差

这是我使用 tqdm 时的代码:

import glob
import os
from tqdm import tqdm
import math
from PIL import Image

new_width = 224
file = r'path\*.jpeg'
images = glob.glob(file)
for i in tqdm(range(len(images))):
  for image in images:
    img = Image.open(image)
    width,height = img.size
    if width >= new_width:
      new = img.resize((224,224))
    else:
      new = img
    
    new.save('path'+os.path.basename(image))

这是我不使用 tqdm 时的情况:

import glob 
import os
import math 
from PIL import Image

new_width = 224
file = r'path\*.jpeg'
images = glob.glob(file)
for image in images:
  img = Image.open(image)
  width,height = img.size
  if width >= new_width:
    new = img.resize((224,224))
  else:
    new = img
    
  new.save('path\'+os.path.basename(image))

tqdm 的结果需要 1 个多小时,但当我不使用它时,它只需要 10 秒。我的代码有什么问题?

在第一个代码中,您有两个嵌套循环而不是一个循环,因此每个图像都被处理 N 次而不是只处理一次,其中 N 是图像的数量。总运行时间与 N2 而不是 N.

成正比

您应该只用 tdqm() 包装现有循环,而不是添加另一个循环:

images = glob.glob(file)
for image in tdqm(images):
    img = Image.open(image)