I am trying to write the frame captured from my laptop camera in to a circular buffer. I wanted to create a thread to handle this task (in an asynchronous way). When i try to get the last frame stored with get_last()
method and show it, black screen is displayed. I have spent quite some time figuring out the reason, but all in vein. IMHO there should be a small issue with this code, but cannot see it. Any help will be highly appreciated. Complete working code is shown below:
import cv2
import sys
import time
import threading
class CamBuffer(threading.Thread):
def __init__(self, stream=0):
self.current = 0
self.max_size = 5
self.buffer = [None] * self.max_size
self.capture = cv2.VideoCapture(stream)
if not self.capture.isOpened():
print("Could not open video")
sys.exit()
print("Opened video")
self.running = True
super().__init__()
def run(self):
print('running thread')
while self.running:
print('capturing frame ', self.current)
_, frame = self.capture.read()
if _:
print('saving frame ', self.current)
self.buffer[self.current] = frame
self.current = self.current + 1
if (self.current >= self.max_size):
self.current = 0
self.capture.release()
print('stopped thread')
def terminate(self):
print('terminating thread')
self.running = False
def get_last(self):
current = 0
if self.current > 0:
current = self.current - 1
print('get_last()', current)
return self.buffer[current]
if __name__ == "__main__":
print('Frame buffer test')
stream = 0
cb = CamBuffer(stream)
cb.start()
time.sleep(1.25)
frame = cb.get_last()
if frame is not None:
print('showing frame')
cv2.imshow('Frame', frame)
time.sleep(3)
cb.terminate()
cv2.destroyAllWindows()
print('Frame buffer test [Done]')