-
Notifications
You must be signed in to change notification settings - Fork 0
/
video_capture.py
48 lines (42 loc) · 1.21 KB
/
video_capture.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
36
37
38
39
40
41
42
43
44
45
46
47
48
import cv2
import queue
import threading
class BufferlessVideoCapture:
'''
BufferlessVideoCapture is a wrapper for cv2.VideoCapture,
which doesn't have frame buffer.
@param name: videocapture name
'''
def __init__(self, name):
self.cap = cv2.VideoCapture(name)
self.q = queue.Queue()
self.thr = threading.Thread(target=self._reader)
self.thr.daemon = True
self.thr.start()
def _reader(self):
'''
Main loop for thread.
'''
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
if self.q.qsize() > 2:
print(self.q.qsize())
self.q.put(frame)
def isOpened(self):
return self.cap.isOpened()
def release(self):
self.cap.release()
def read(self):
'''
Read current frame.
'''
return True, self.q.get()
def close(self):
pass