OpenCV vs Pillow 谁读取文件速度更快?

在训练深度学习模型时,通常要从硬盘载入图片文件到内存,那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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章