-
Notifications
You must be signed in to change notification settings - Fork 0
/
capture.py
65 lines (52 loc) · 2.04 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import cv2
from threading import Thread
# Non blocking video capture!
class Capture:
def __init__(self,source=0): # Source 0 is the default (usually webcam)
if not isinstance(source, int) and source.isdigit():
source = int(source)
self.video_capture = cv2.VideoCapture(source)
if not self.video_capture.isOpened():
raise ValueError('Cannot open source!')
self.flip = cv2.flip if source == 0 else lambda f, *a, **k: f # Flip around y axis only if is PC webcam
self.running = False
self.t=Thread(target=self.loop)
self.t.daemon=True
self.frame = None
self.retrieve = self.video_capture.retrieve if isinstance(source,str) else self.video_capture.read
self.grab = self.video_capture.grab if isinstance(source,str) else lambda *args: None # Grab only if it is not PC webcam, otherwise do nothing
def start(self):
self.running = True
self.t.start()
def stop(self):
self.running = False
self.t.join()
return
def loop(self):
while(self.running):
self.grab() # Keep grabbing frames...
def get(self):
ret, self.frame = self.retrieve() #capture frame-by-frame
return self.flip(self.frame, 1)
# The following tries to elaborate EACH frame. Very slow! Do not use in production.
class CaptureEveryFrame:
def __init__(self,source=0): # Source 0 is the default (usually webcam)
self.video_capture = cv2.VideoCapture(source)
self.running = False
self.t=Thread(target=self.loop)
self.t.daemon=True
self.frame = None
def start(self):
self.running = True
self.t.start()
def stop(self):
self.running = False
self.t.join()
return
def loop(self):
while(self.running):
ret, self.frame = self.video_capture.read() #capture frame-by-frame
def get(self):
return self.frame