Reputation: 21
I am trying to make a simple Video player with OpenCV as a beginner project. I tried on both, an I5 processor and an I9 processor, but the Python script runs very slowly.
Questions:
How to increase speed?
How to maintain FPS?
if fileformat in VIDEO_FORMATS:
cap = cv2.VideoCapture(filepath)
fps = 24
backward_seconds = 5
forward_seconds = 5
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
i = 0
isPaused = False
def reshape_img(image):
return cv2.resize(image, (1280, 1024), interpolation=cv2.INTER_AREA)
while True:
time.sleep(1/fps)
cap.set(cv2.CAP_PROP_POS_FRAMES, i)
ret, frame = cap.read()
frame = reshape_img(frame)
cv2.imshow('i', frame)
x = cv2.waitKeyEx(24)
if x == ord("a"):
if i > backward_seconds * fps:
i -= backward_seconds * fps
else:
i = 0
elif x == ord("d"):
if i < length - forward_seconds * fps:
i += forward_seconds * fps
else:
i = length - 1
elif x == 32:
if isPaused == False:
isPaused = True
elif isPaused == True:
isPaused = False
elif x == 27:
break
if not isPaused:
i += 1
cv2.destroyAllWindows()
I don't have much knowledge of how to use OpenCV. So I don't know the things which I am doing wrong.
Upvotes: 1
Views: 1941
Reputation: 27577
In order to maintain the FPS, instead of using time.sleep(1 / fps)
, which would actually result in a lower FPS due to the other parts of the program within the while
loop that also takes time, you can define a time delta variable. Here is a minial example:
import time
fps = 24
delta = 1 / fps
last_time = time.time()
new_time = time.time()
while True:
new_time = time.time()
if new_time - last_time < delta:
continue
last_time += delta
# Your code here
Adding it to your program's while
loop would be:
import time
delta = 1 / fps
last_time = time.time()
new_time = time.time()
while True:
new_time = time.time()
if new_time - last_time < delta:
continue
last_time += delta
cap.set(cv2.CAP_PROP_POS_FRAMES, i)
ret, frame = cap.read()
frame = reshape_img(frame)
cv2.imshow('i', frame)
x = cv2.waitKeyEx(24)
if x == ord("a"):
if i > backward_seconds * fps:
i -= backward_seconds * fps
else:
i = 0
elif x == ord("d"):
if i < length - forward_seconds * fps:
i += forward_seconds * fps
else:
i = length - 1
elif x == 32:
if isPaused == False:
isPaused = True
elif isPaused == True:
isPaused = False
elif x == 27:
break
if not isPaused:
i += 1
Upvotes: 1