blob: 0998e1ab9561286ee27c4fe51ddbee318372bcba [file] [log] [blame]
Shad Ansari30a23732021-09-29 23:07:21 -07001import threading
Shad Ansaric9f48d32021-10-25 19:03:34 +00002from queue import Queue
Shad Ansari30a23732021-09-29 23:07:21 -07003
4
5class BaseCamera(object):
Shad Ansaric0726e62021-10-04 22:38:53 +00006 thread = {} # background thread that reads frames from camera
Shad Ansaric9f48d32021-10-25 19:03:34 +00007 frame = {} # frame queue
Shad Ansari30a23732021-09-29 23:07:21 -07008
Shad Ansari4ae11682021-10-22 18:51:53 +00009 def __init__(self, device=None, idle=False):
Shad Ansari30a23732021-09-29 23:07:21 -070010 """Start the background camera thread if it isn't running yet."""
Shad Ansaric0726e62021-10-04 22:38:53 +000011 self.device = device
Shad Ansaric0726e62021-10-04 22:38:53 +000012 if self.device not in BaseCamera.thread:
13 BaseCamera.thread[self.device] = None
14 if BaseCamera.thread[self.device] is None:
Shad Ansaric9f48d32021-10-25 19:03:34 +000015
16 self.frame[device] = Queue(100)
Shad Ansari30a23732021-09-29 23:07:21 -070017
18 # start background frame thread
Shad Ansaric0726e62021-10-04 22:38:53 +000019 BaseCamera.thread[self.device] = threading.Thread(target=self._thread, args=(self.device))
20 BaseCamera.thread[self.device].start()
Shad Ansari30a23732021-09-29 23:07:21 -070021
22 # wait until frames are available
Shad Ansaric9f48d32021-10-25 19:03:34 +000023 _ = self.get_frame()
Shad Ansari30a23732021-09-29 23:07:21 -070024
25 def get_frame(self):
26 """Return the current camera frame."""
Shad Ansari30a23732021-09-29 23:07:21 -070027
Shad Ansaric9f48d32021-10-25 19:03:34 +000028 # blocks
29 return BaseCamera.frame[self.device].get(block=True)
Shad Ansari30a23732021-09-29 23:07:21 -070030
Shad Ansari341ca3a2021-09-30 12:10:00 -070031 def frames(self):
Shad Ansari30a23732021-09-29 23:07:21 -070032 """"Generator that returns frames from the camera."""
Shad Ansari341ca3a2021-09-30 12:10:00 -070033 raise NotImplementedError('Must be implemented by subclasses.')
Shad Ansari30a23732021-09-29 23:07:21 -070034
Shad Ansaric0726e62021-10-04 22:38:53 +000035 def _thread(self, device):
Shad Ansari30a23732021-09-29 23:07:21 -070036 """Camera background thread."""
37 frames_iterator = self.frames()
38 for frame in frames_iterator:
Shad Ansaric9f48d32021-10-25 19:03:34 +000039 BaseCamera.frame[device].put(frame, block=True)
Shad Ansari4ae11682021-10-22 18:51:53 +000040
Shad Ansaric0726e62021-10-04 22:38:53 +000041 BaseCamera.thread[device] = None