-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.py
35 lines (28 loc) · 927 Bytes
/
reader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import queue
import threading
import cv2
class VideoCapture:
def __init__(self, name):
self.fourcc = cv2.VideoWriter_fourcc(*'XVID')
self.out = cv2.VideoWriter(
'output.avi', self.fourcc, 20.0, (640, 480))
self.cap = cv2.VideoCapture(name)
self.q = queue.Queue()
t = threading.Thread(target=self._reader)
t.daemon = True
t.start()
# read frames as soon as they are available, keeping only most recent one
def _reader(self):
while True:
ret, frame = self.cap.read()
if not ret:
break
if not self.q.empty():
try:
self.q.get_nowait() # discard previous (unprocessed) frame
except queue.Empty:
pass
self.out.write(frame)
self.q.put(frame)
def read(self):
return self.q.get()