使用PIL加载大图像时计时显示0秒但实际未完成加载的问题
问题:PIL加载超大图像时耗时统计异常
我编写了一个测试函数,用于查看图像加载状态及耗时:
from PIL import Image from timeit import default_timer as timer def ImageLoad(path: str): print("Loading '" + path + "'... ", end='') start = timer() im = Image.open(path) print("successfully (%.2fs)." % (timer()-start)) return im
但加载约20K×60K像素的超大图像时,始终显示耗时0秒:
Loading 'Image0.png'... successfully (0.00s). Loading 'Image1.png'... successfully (0.00s).
我在函数调用后添加了打印语句:
image = ImageLoad(path) print("Image loaded")
发现该打印语句至少在40秒后才显示,符合实际加载耗时。为何函数内的成功提示会立即显示,而图像实际并未加载完成?
解答
这是因为PIL的Image.open()采用了懒加载机制:它仅创建图像对象并读取元数据(比如尺寸、格式),并不会立刻把像素数据加载到内存。真正的像素加载操作会延迟到你第一次访问图像内容时触发——比如调用图像处理方法、访问像素值,甚至某些隐式的内存操作。
所以你的函数里,im = Image.open(path)执行速度极快,瞬间就能完成,耗时统计自然显示0秒。而后续的print("Image loaded")迟迟不出现,是因为函数返回后,解释器处理图像对象的隐式操作触发了真实的像素加载,这部分耗时被算在了函数外部。
要统计真实的加载耗时,需要在函数内强制触发像素加载,比如调用im.load()方法:
from PIL import Image from timeit import default_timer as timer def ImageLoad(path: str): print("Loading '" + path + "'... ", end='') start = timer() im = Image.open(path) im.load() # 强制将像素数据加载到内存 print("successfully (%.2fs)." % (timer()-start)) return im
修改后,函数就能准确统计到整个图像加载的真实耗时。
内容的提问来源于stack exchange,提问作者FiReTiTi
相关产品推荐
相关产品推荐

