-
Notifications
You must be signed in to change notification settings - Fork 7
/
camera_pi.py
68 lines (56 loc) · 1.91 KB
/
camera_pi.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
66
67
68
import time
import io
import threading
import picamera
import config as cfg
def init_camera():
try:
camera = picamera.PiCamera()
# camera setup
camera.resolution = (cfg.width, cfg.height)
camera.hflip = cfg.pi_hflip
camera.vflip = cfg.pi_vflip
# let camera warm up
camera.start_preview()
time.sleep(2)
return True, camera
except:
return False, False
def single_frame():
stream = io.BytesIO()
cfg.camera.capture(stream, 'jpeg', use_video_port=True)
stream.seek(0)
frame = stream.read()
return frame
class Camera(object):
thread = None # background thread that reads frames from camera
frame = None # current frame is stored here by background thread
last_access = 0 # time of last client access to the camera
def initialize(self):
if Camera.thread is None:
# start background frame thread
Camera.thread = threading.Thread(target=self._thread)
Camera.thread.start()
# wait until frames start to be available
while self.frame is None:
time.sleep(0)
def get_frame(self):
Camera.last_access = time.time()
self.initialize()
return self.frame
@classmethod
def _thread(cls):
stream = io.BytesIO()
for foo in cfg.camera.capture_continuous(stream, 'jpeg',
use_video_port=True):
# store frame
stream.seek(0)
cls.frame = stream.read()
# reset stream for next frame
stream.seek(0)
stream.truncate()
# if there hasn't been any clients asking for frames in
# the last 10 seconds stop the thread
if time.time() - cls.last_access > 10 or cfg.camera_active is False:
break
cls.thread = None