在训练深度学习模型时,通常要从硬盘载入图片文件到内存,那cv2.imread() vs Image.open() 读取文件速度谁更快?
结论:Pillow的Image.open()读取图片速度更快!
测试代码如下:
import os, time
import numpy as np
import cv2
from PIL import Image
IMG_DIR = "D:/datasets/PascalVOC/images"
image_files = [os.path.join(IMG_DIR, f) for f in os.listdir(IMG_DIR)]
print('total image files: {}'.format(len(image_files)))
def test(f, n_trials=5):
elapsed_times = []
for i in range(n_trials):
t1 = time.time()
f()
t2 = time.time()
elapsed_times.append(t2-t1)
print('Mean: {:.3f}s - Std: {:.3f}s - Max: {:.3f}s - Min: {:.3f}s'.format(
np.mean(elapsed_times),
np.std(elapsed_times),
np.max(elapsed_times),
np.min(elapsed_times)
))
image_files_1000 = image_files[:1000]
opencv_imread = lambda: [cv2.imread(f) for f in image_files_1000]
print("Test the speed of OpenCV imread()... ")
test(opencv_imread, n_trials=5)
print("Test the speed of Image open()... ")
image_open = lambda: [Image.open(f) for f in image_files_1000]
test(image_open, n_trials=5)