I have two threads, one for capturing frames from a high frame rate camera (producter) and the other for writing frames to video files (consumer). I use Queue
to transfer frames from producter to consumer. At first, my code was like this:
# consumer
class VideoWriter:
...
def record(self):
while self.isRecording or not self.frame_queue.empty():
if not self.frame_queue.empty():
writer.imwrite(self.frame_queue.get())
...
# producter
class MyVideo:
...
def play(self):
while self.isLiving:
if self.cap.IsGrabbing():
frame = self.cap.RetrieveResult(1000)
if self.video_writer.isRecording:
self.video_writer.frame_queue.put(frame)
show_frame(frame)
...
When I don't start recording, everything in the code is normal. However, when I started the consumer thread(started recording), the producer thread began to become very sluggish, and the consumer thread received far fewer frames than the producer thread captured from the camera. Then I fixed this problem by changing my codes into following:
# consumer
class VideoWriter:
...
def record(self):
while self.isRecording or not self.frame_queue.empty():
try:
writer.imwrite(self.frame_queue.get(block=False))
except Empty:
time.sleep(0.001)
...
# producter
class MyVideo:
...
def play(self):
while self.isLiving:
if self.cap.IsGrabbing():
frame = self.cap.RetrieveResult(1000)
if self.video_writer.isRecording:
self.video_writer.frame_queue.put(frame,block=False)
show_frame(frame)
...
Now, everything is fine. But I don't know the reason why this problem occured. Can someone explain to me why?