Skip to content

Instantly share code, notes, and snippets.

Last active December 9, 2022 12:59
What would you like to do?
Allows to always get most recent frame, in case video capture loop has some (computation) delay inside
# Based on:
# Added:
# - configurable delay handling
# - renamed class
# - per frame timestamp output
import cv2, threading, time, queue
from sys import argv
wait = 0 if len(argv) == 1 else float(argv[1])
class BufferlessVideoCapture:
def __init__(self, name):
self.cap = cv2.VideoCapture(name)
self.q = queue.Queue()
t = threading.Thread(target=self._reader)
t.daemon = True
# read frames as soon as they are available, keeping only most recent one
def _reader(self):
while True:
ret, frame =
if not ret:
if not self.q.empty():
self.q.get_nowait() # discard previous (unprocessed) frame
except queue.Empty:
def read(self):
return self.q.get()
cap = BufferlessVideoCapture(0)
while True:
print("after wait, before", time.time())
frame =
cv2.imshow("frame", frame)
if chr(cv2.waitKey(1)&255) == 'q':
Copy link

Call with "python 2" for 2 second delay between loop executions.
Whenever a timestamp message is written, do after a seond a change (eg. of hand) in view.
When next timestamp gets printed, newly displayed frame will show changed scene.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment