1

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??

2
  • You could try to enable CUDA to use GPU to speed up. Not sure if it will actually do alot of speedup but learnopencv.com/getting-started-opencv-cuda-modul Commented Jan 22, 2021 at 14:56
  • I don't think the set is the slow part, but you can get rid of it by moving it outside of the for loop. You can set it to range1 before the for loop, video.read() will advance by one frame each time it's caled. Commented Jan 22, 2021 at 15:21

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much, it works!. For me it reduces the time required from 3-3.5 sec to 0.5-0.8 sec.
Btw, is there any way to squeeze the performance even more by replacing the cap.read() function with something else, maybe cap.retrieve() or something? just asking..
I don't think so. cap.read() is really just a wrapper that combines cap.grab() and cap.retrieve() into one function.
0

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

1 Comment

This is not an answer. See How do I write a good answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.