dwiandhika
dwiandhika

Reputation: 27

OpenCV set() and read() function is too slow (Python)

I want to loop frames from a certain range, and append it to an array. The thing is that, it's too slow. I already check how long the function would take and i think that's pretty slow. Here is my current code:

imgs = []
for j in range(range1, range2):
      video.set(cv.CAP_PROP_POS_FRAMES, j)
      ret, frame = video.read()
      imgs.append(frame)

i also tried to replace imgs.append(frame) with video.retrieve(video.grab()), but the performance didn't really differs much. Is there any better solution/alternative to do what this code does??

Upvotes: 1

Views: 2140

Answers (2)

Chuck Liao
Chuck Liao

Reputation: 1

I also came across this problem. I have to use set(3,width) and set(4,height)to acquire the original size of my camera but this method makes my code run much slower

Upvotes: 0

Ian Chu
Ian Chu

Reputation: 3143

Oh wow, nvm. It is set that's making this slow:

Inside Time: 15.308052062988281

Outside Time: 0.4459998607635498

import cv2
import time

def setInside(cap, start, end):
    imgs = [];
    for a in range(start, end):
        cap.set(cv2.CAP_PROP_POS_FRAMES, a);
        _, frame = cap.read();
        imgs.append(frame);

def setOutside(cap, start, end):
    imgs = [];
    cap.set(cv2.CAP_PROP_POS_FRAMES, start);
    for a in range(start, end):
        _, frame = cap.read();
        imgs.append(frame);

# open vidcap
cap = cv2.VideoCapture("202534.avi");

# bounds
start = 0;
end = 2000;

# time it
start_time = time.time();
setInside(cap, start, end);
print("Inside Time: " + str(time.time() - start_time));

start_time = time.time();
setOutside(cap, start, end);
print("Outside Time: " + str(time.time() - start_time));

If you move the set to before the loop it'll be way faster.

Upvotes: 3

Related Questions