Skip to content

VideoCapture faster than imread when reading image files #19740

@adamhrv

Description

@adamhrv
System information (version)
  • OpenCV => 4.5.1
  • Operating System / Platform => Ubuntu 20.04
  • Compiler => pip install opencv-python==4.5.1
Detailed description

I assume cv2.imread() is the faster/preferred method for loading images but cv2.VideoCapture is approximately 0.002 milliseconds faster per image/frame.

I'm trying to optimize performance (using Python 3.6 environment) and noticed that VideoCapture is slightly faster than imread. The difference is trivial and can be ignored for most applications, but when loading large collections of images (eg 1 million) it could save 30 minutes.

Should cv2.VideoCapture be the preferred method for loading images?

Steps to reproduce
import time
import cv2

fp = '/path/to/my.jpg'
n = 1000

# read jpg image using VideoCapture
st = time.perf_counter()
for i in range(n):
  cap = cv2.VideoCapture(fp)
  (grabbed, frame) = cap.read()
  cap.release()
t1 = time.perf_counter() - st

# read jpg image using imread
st = time.perf_counter()
for i in range(n):
  im = cv2.imread(fp)
t2 = time.perf_counter() - st

print(f'VideoCapture: {t1/n:.4f} ms/iter')
print(f'imread: {t2/n:.4f} ms/iter')
print(f'VideoCapture is {t2 - t1:.4f} ms/iter faster averaged over {n} iterations')
print(f'cv2 version: {cv2.__version__}')

Result:

VideoCapture: 0.0067 ms/iter
imread: 0.0086 ms/iter
VideoCapture is 0.0019 ms/iter faster averaged over 1000 iterations
cv2 version: 4.5.1
Issue submission checklist
  • I report the issue, it's not a question
  • I checked the problem with documentation, FAQ, open issues,
    forum.opencv.org, Stack Overflow, etc and have not found solution
  • I updated to latest OpenCV version and the issue is still there
  • There is reproducer code and related data files: videos, images, onnx, etc

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions