Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

the video plays faster than realtime because that's a useful behavior to rapidly work through data.

if you want it to "play" at 1x speed, you'll need to insert some waiting. you can pass such a delay to waitKey() in milliseconds.

you could simply pass in 1000 / cap.get(cv.CAP_PROP_FPS) but that won't account for processing time and your video will play slower than realtime.

that's why you should do the following:

tstart = time.perf_counter() # before the loop
# loop starts...
    pts = cap.get(cv.CAP_PROP_POS_MSEC) # before your cap.read()
    # ... cap.read...
    # ... your processing and imshow()...
    time_left = pts - 1000 * (time.perf_counter() - tstart)
    cv.waitKey(int(max(1, time_left)))

the video plays faster than realtime because that's a useful behavior to rapidly work through data.

if you want it to "play" at 1x speed, you'll need to insert some waiting. you can pass such a delay to waitKey() in milliseconds.

you could simply pass in 1000 / cap.get(cv.CAP_PROP_FPS) but that won't account for processing time and your video will play slower than realtime.

that's why you should do the following:

# ... open capture...
tstart = time.perf_counter() # before the loop
# in seconds
# ... loop starts...
    pts = cap.get(cv.CAP_PROP_POS_MSEC) # before your cap.read()
    # ... cap.read...
in milliseconds
    # ... cap.read()...
    # ... your processing and imshow()...
    time_left = pts - 1000 * (time.perf_counter() - tstart)
tstart) # in milliseconds
    cv.waitKey(int(max(1, time_left)))

that is also not perfect. waitKey will return sooner if you press a key, which makes the video play faster. it will maintain the correct pace though. how it works: the 'pts' is the presentation timestamp of the frame you are reading. after all processing for the frame is done, we calculate how much time has elapsed, and how much is left before this frame is due for presentation. we then give that time remaining to waitKey()