blob: 28ee57d8b3393cd8309ccf82960775c5520a4f84 [file] [log] [blame]
Shad Ansari26682be2021-10-26 03:52:35 +00001from multiprocessing import Process, Queue
Shad Ansari30a23732021-09-29 23:07:21 -07002
3
4class BaseCamera(object):
Shad Ansari26682be2021-10-26 03:52:35 +00005 process = {} # background process that reads frames from camera
Shad Ansaric9f48d32021-10-25 19:03:34 +00006 frame = {} # frame queue
Shad Ansari30a23732021-09-29 23:07:21 -07007
Shad Ansari60ca8cc2021-11-02 18:46:44 +00008 def __init__(self, device=None, idle=False):
Shad Ansari26682be2021-10-26 03:52:35 +00009 """Start the background camera process if it isn't running yet."""
Shad Ansaric0726e62021-10-04 22:38:53 +000010 self.device = device
Shad Ansari26682be2021-10-26 03:52:35 +000011 if self.device not in BaseCamera.process:
12 BaseCamera.process[self.device] = None
13 if BaseCamera.process[self.device] is None:
Shad Ansaric9f48d32021-10-25 19:03:34 +000014
Shad Ansari60ca8cc2021-11-02 18:46:44 +000015 self.frame[device] = Queue(100)
Shad Ansari30a23732021-09-29 23:07:21 -070016
Shad Ansari26682be2021-10-26 03:52:35 +000017 # start background frame process
18 BaseCamera.process[self.device] = Process(target=self._process, args=(self.device))
19 BaseCamera.process[self.device].start()
Shad Ansari30a23732021-09-29 23:07:21 -070020
21 # wait until frames are available
Shad Ansari60ca8cc2021-11-02 18:46:44 +000022 _ = self.get_frame()
Shad Ansari30a23732021-09-29 23:07:21 -070023
24 def get_frame(self):
25 """Return the current camera frame."""
Shad Ansari30a23732021-09-29 23:07:21 -070026
Shad Ansari60ca8cc2021-11-02 18:46:44 +000027 # blocks
28 return BaseCamera.frame[self.device].get(block=True)
Shad Ansari30a23732021-09-29 23:07:21 -070029
Shad Ansari341ca3a2021-09-30 12:10:00 -070030 def frames(self):
Shad Ansari30a23732021-09-29 23:07:21 -070031 """"Generator that returns frames from the camera."""
Shad Ansari341ca3a2021-09-30 12:10:00 -070032 raise NotImplementedError('Must be implemented by subclasses.')
Shad Ansari30a23732021-09-29 23:07:21 -070033
Shad Ansari26682be2021-10-26 03:52:35 +000034 def _process(self, device):
35 """Camera background process."""
Shad Ansari30a23732021-09-29 23:07:21 -070036 frames_iterator = self.frames()
37 for frame in frames_iterator:
Shad Ansaric9f48d32021-10-25 19:03:34 +000038 BaseCamera.frame[device].put(frame, block=True)
Shad Ansari4ae11682021-10-22 18:51:53 +000039
Shad Ansari26682be2021-10-26 03:52:35 +000040 BaseCamera.process[device] = None