Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript

Added `FMC_MultiCameraRecorder` and `FMC_Camera` classes

jon matthis8ab62de6ab5e
diff --git a/freemocap/dev_scratchpad/dev_alpha/FMC_MultiCameraRecorder.py b/freemocap/dev_scratchpad/dev_alpha/FMC_MultiCameraRecorder.py
new file mode 100644
index 00000000..430f9b4b
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/FMC_MultiCameraRecorder.py
@@ -0,0 +1,287 @@
+from os import mkdir
+from fmc_camera import FMC_Camera
+
+import concurrent.futures
+import logging
+import queue
+import threading
+import time
+import platform
+import datetime
+
+import cv2
+import matplotlib.pyplot as plt
+import numpy as np
+import h5py
+from pathlib import Path
+
+from rich import print
+from rich import inspect
+from rich.progress import track
+from rich.traceback import install
+install(show_locals=True)
+from rich.console import Console
+from rich.progress import track
+
+
+class FMC_MultiCameraRecorder:
+
+ def __init__(
+ self,
+ rec_name = None,
+ save_path = None,
+ num_cams = 0,
+ cams_to_use_list = None,
+ show_multi_cam_stream = True,
+ save_to_mp4 = True,
+ save_to_h5 = False,
+ save_log_file = False
+ ):
+
+ self._init_start_time = time.time_ns()#the precision is aspirational, lol
+
+ if rec_name is None:
+ self._rec_name = datetime.datetime.now().strftime("FMC_MultiCamRecording_%Y-%b-%d_%H_%M_%S")
+ else:
+ self._rec_name = rec_name
+
+
+ if save_path is None:
+ self._save_path = Path('data/' + self._rec_name)
+ else:
+ self._save_path = Path(save_path)
+
+ if save_path or save_to_mp4 or save_to_h5 or save_log_file:
+ self._save_path.mkdir(parents=True)
+ self._path_to_log_file = Path(str(self._save_path / self._rec_name) + '_log.txt')
+
+ self._save_to_mp4 = save_to_mp4
+ if self._save_to_mp4:
+ self._output_video_object = None #build this after we get the first multi_frame_image
+
+ # log_file_obj = open(self._path_to_log_file,'w+')
+ # self.rich_console = Console(file=log_file_ob)
+ self.rich_console = Console()
+
+ self._num_cams = num_cams
+ self._cams_to_use_list = cams_to_use_list
+
+ self.exit_event = threading.Event()
+
+
+
+ self.rich_console.rule('Starting FreeMoCap MultiCam Recorder!')
+
+ if self.cams_to_use_list is None:
+ self.find_available_cameras()
+
+
+ self.start_multi_cam_thread_pool()
+
+ @property
+ def num_cams(self):
+ """How many cameras to use"""
+ return self._num_cams
+
+ @num_cams.setter
+ def num_cams(self, num_cams_input):
+ """Define how many cameras to use"""
+ self._num_cams = num_cams_input
+
+ @property
+ def cams_to_use_list(self):
+ """ a list denoting which camera IDs to use.
+ If both this and `num_cams` are set to default value (`0` and `None`, respectively), use all available cameras).
+ """
+ return self._cams_to_use_list
+
+ @property
+ def init_start_time(self):
+ """Time that this object was initialized (UNIX Epoch time from `time.time_ns())
+
+ Returns:
+ float: time this object was created (UNIX Epoch time from `time.time_ns())
+ """
+ return self._init_start_time
+
+ @property
+ def each_cam_timestamps_unix_ns(self): #not really a property though?
+ return self._each_cam_timestamps_unix_ns
+
+
+ def __enter__(self):
+ """Context manager - No need to do anything special on start"""
+ return self
+
+ def __exit__(self, exc_type, exc_value, exc_traceback):
+ """Context manager - on exit, set `self.exit_event` to activate shutdown sequence """
+ self.create_diagnostic_images()
+ return self
+
+ def find_available_cameras(self):
+ """find available webcams and return IDs in list."""
+
+ if self.num_cams == 0:
+ num_cams_to_check = 20 #man, i HOPE you're out there trying to record from more than 20 cameras!!!
+ else:
+ num_cams_to_check = self.num_cams
+
+ if platform.system() == 'Windows':
+ capBackend = cv2.CAP_DSHOW
+ else:
+ capBackend = cv2.CAP_ANY
+
+ self._cams_to_use_list = []
+ for camNum in track(range(num_cams_to_check), description='[green]Finding available cameras...' ):
+ cap = cv2.VideoCapture(camNum, capBackend)
+ if cap.isOpened():
+ self._cams_to_use_list.append(camNum)
+ cap.release()
+ console.print("Found cameras at ", self._cams_to_use_list)
+
+ self.num_cams = len(self._cams_to_use_list)
+ return self.cams_to_use_list
+
+
+ def start_multi_cam_thread_pool(self):
+ """creates a threading.ThreadPoolExecutor that creates an `FMC_Camera` object for each camera in `self.cams_to_use_list` and sets each to trigger `run_in_thread` mode
+
+ NOTE - Eventually I want these to be in different processes, I think?
+ """
+ self.cam_frame_queue = queue.Queue(maxsize=self.num_cams)
+ self.multi_cam_image_queue = queue.Queue()
+
+ self._each_cam_timestamps_unix_ns = None
+ self._cam_thread = [None] * self.num_cams
+
+ self.rich_console.rule('starting multi_cam_thread_pool')
+
+ while not self.exit_event.is_set():
+ with concurrent.futures.ThreadPoolExecutor(max_workers=self.num_cams+1) as executor:
+ self.thread_barrier = threading.Barrier(self.num_cams, action=self.grab_incoming_cam_tuples)
+ for this_cam_num in self.cams_to_use_list: #i feel like there is some cooler way to do this using 'map' and 'zip' or whatever, but this feels easier on the ol' brain noggin lol
+ self._cam_thread[this_cam_num] = executor.submit(FMC_Camera, cam_num=this_cam_num, frame_queue = self.cam_frame_queue, thread_barrier = self.thread_barrier, exit_event = self.exit_event, console=self.rich_console)
+ executor.submit(self.show_multi_cam_cv2)
+
+ def grab_incoming_cam_tuples(self):
+ """grab incoming cam_tuples, put them into a multi_cam_tuple and stuff that into the multi_cam_tuple_queue"""
+
+ these_images_list = [None]*self.num_cams #empty list of size (numCam)
+ these_timestamps = np.ndarray(self.num_cams)
+
+ for cam_num in range(self.num_cams):
+ this_cam_image_timestamp_tuple = self.cam_frame_queue.get()
+ this_cam_num = this_cam_image_timestamp_tuple[0]
+ these_images_list[this_cam_num] = this_cam_image_timestamp_tuple[1]
+ these_timestamps[this_cam_num] = this_cam_image_timestamp_tuple[2]
+
+ if self._each_cam_timestamps_unix_ns is None:
+ self._each_cam_timestamps_unix_ns = these_timestamps
+ else:
+ self._each_cam_timestamps_unix_ns = np.vstack((self._each_cam_timestamps_unix_ns, these_timestamps)) #result will be numpy array with `num_frames` rows and `num_cams` columns
+
+
+ multi_cam_image = np.hstack(these_images_list) #create multiFrame_image by stitching together incoming camera images
+ self.multi_cam_image_queue.put(multi_cam_image)
+ # self.rich_console.log('Created a multi_cam_image')
+
+
+
+
+ def show_multi_cam_cv2(self):
+ """display multi_cam_image using `cv2.imshow` and maybe save it to mp4, who knows?
+ """
+ self.rich_console.log('Launching Multi Cam Viewer')
+ while not self.exit_event.is_set():
+ if not self.multi_cam_image_queue.empty():
+ multi_cam_image = self.multi_cam_image_queue.get()
+
+ if self._save_to_mp4:
+ if self._output_video_object is None:
+ self.initialize_video(multi_cam_image)
+ self._output_video_object.write(multi_cam_image)
+
+ cv2.imshow(self._rec_name, multi_cam_image)
+ key = cv2.waitKey(1)
+
+ if key == 27: # exit on ESC
+ self.exit_event.set()
+
+ if cv2.getWindowProperty(self._rec_name, cv2.WND_PROP_VISIBLE) < 1: #break loop if window closed
+ self.exit_event.set()
+
+ cv2.destroyAllWindows()
+ if self._save_to_mp4:
+ self._output_video_object.release()
+ self.rich_console.log('Shutting down MultiCamera Viewer')
+ selfmulti_cam.exit_event.set() #send the 'Exit' signal to everyone
+
+ def initialize_video(self, multi_cam_image):
+ """use the multi_cam_image to initialize the video
+ multicam image will be of size [cam_resolution_width*num_cams by cam_resolution_height]
+ Args:
+ multi_cam_image ([type]): [description]
+ """
+ #create video save object
+ self._multi_cam_image_height, self._multi_cam_image_width, channels = multi_cam_image.shape
+
+ self.multi_cam_image_size = ( self._multi_cam_image_width, self._multi_cam_image_height)
+ fourcc = cv2.VideoWriter_fourcc(*'DIVX')
+ self._outputVid_fileName = str(self._save_path / self._rec_name) + '_outVid.mp4'
+ fps = 30 #this is a bad and stupid guess, but it's actually kinda tricky to guess what is the right thing to put here. I'll fix this later and expect videos to be a bit faster than usual :(
+ self._output_video_object = cv2.VideoWriter(self._outputVid_fileName, fourcc, fps, self.multi_cam_image_size)
+
+ def create_diagnostic_images(self):
+ """plot some diagnostics to assess quality of camera sync"""
+
+ camTimestamps = (self.each_cam_timestamps_unix_ns-self.init_start_time)/1e9 #subtract start time and convert to sec
+ np.save(str(self._save_path /'multi_cam_timestamps_frameNum_camNum.npy'), camTimestamps)
+ meanMultiFrameTimestamp = np.mean(camTimestamps, axis=1)
+ meanMultiFrameTimespan = np.max(camTimestamps, axis=1) - np.min(camTimestamps, axis=1) #what was the timespan covered by each frame
+ plt.ion()
+ fig = plt.figure(figsize=(18,10))
+ max_frame_duration = .1
+ ax1 = plt.subplot(231, title='Camera Frame Timestamp vs Frame#', xlabel='Frame#', ylabel='Timestamp (sec)')
+ ax2 = plt.subplot(232, ylim=(0,max_frame_duration), title='Camera Frame Duration Trace', xlabel='Frame#', ylabel='Duration (sec)')
+ ax3 = plt.subplot(233, xlim=(0,max_frame_duration), title='Camera Frame Duration Histogram (count)', xlabel='Duration(s, 1ms bins)', ylabel='Probability')
+ ax4 = plt.subplot(234, title='MuliFrame Timestamp vs Frame#', xlabel='Frame#', ylabel='Timestamp (sec)')
+ ax5 = plt.subplot(235, ylim=(0,max_frame_duration), title='Multi Frame Duration/Span Trace', xlabel='Frame#', ylabel='Duration (sec)')
+ ax6 = plt.subplot(236, xlim=(0,max_frame_duration), title='MultiFrame Duration Histogram (count)', xlabel='Duration(s, 1ms bins)', ylabel='Probability')
+
+ for camNum in range(self.num_cams):
+ thisCamTimestamps = camTimestamps[:,camNum]
+ ax1.plot(thisCamTimestamps, label='Camera#'+str(camNum))
+ ax1.legend()
+ ax2.plot(np.diff(thisCamTimestamps),'.')
+ ax3.hist(np.diff(thisCamTimestamps), bins=np.arange(0,max_frame_duration,.001), alpha=0.5)
+
+ ax4.plot(meanMultiFrameTimestamp, color='darkslategrey', label='MultiFrame'+str(camNum))
+ ax5.plot(np.diff(meanMultiFrameTimestamp),'.',color='darkslategrey', label='Frame Duration')
+ ax5.plot(meanMultiFrameTimespan, '.', color='orangered', label='Frame TimeSpan')
+ ax5.legend()
+ ax6.hist(np.diff(meanMultiFrameTimestamp), bins=np.arange(0,max_frame_duration,.001), density=True, alpha=0.5, color='darkslategrey', label='Frame Duration')
+ ax6.hist(np.diff(meanMultiFrameTimespan), bins=np.arange(0,max_frame_duration,.001), density=True, alpha=0.5, color='orangered', label='Frame Timespan')
+ ax5.legend()
+
+ plt.savefig(str(self._save_path / 'recording_diagnostics.png'))
+ plt.show()
+ f=9
+
+
+
+
+
+
+if __name__ == '__main__':
+ console = Console() #create rich console to catch and print exceptions
+ try:
+ with FMC_MultiCameraRecorder() as multi_cam:
+ runtime = 10
+ logging.info("Main: Record for {} seconds".format(runtime))
+ time.sleep(runtime)
+ print('shutting down MultiCamRecorder')
+
+ except Exception:
+ console.print_exception()
+
+
diff --git a/freemocap/dev_scratchpad/dev_alpha/__init__.py b/freemocap/dev_scratchpad/dev_alpha/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/freemocap/dev_scratchpad/dev_alpha/fmc_camera.py b/freemocap/dev_scratchpad/dev_alpha/fmc_camera.py
new file mode 100644
index 00000000..c86d4874
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/fmc_camera.py
@@ -0,0 +1,333 @@
+##
+##
+## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+## β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+##
+##
+#Font - ANSI Regular - https://patorjk.com/software/taag/#p=display&f=ANSI%20Regular&t=Play%20Skeleton%20Animation
+
+
+
+import platform
+from pathlib import Path
+import time
+
+import cv2
+import numpy as np
+
+#python rich stuff - https://rich.readthedocs.io/
+from rich import print
+from rich.console import Console
+from rich.live import Live
+from rich.table import Table
+
+
+cap_default_parameters_dict = {
+ 'exposure': -6,
+ 'cap_resolution_width': 640,
+ 'cap_resolution_height': 480,
+ }
+
+class FMC_Camera:
+ """Simple class to open a cv2.VideoCapture object, with parts to connect to a `MutliCamRecorder` object
+ """
+ def __init__(
+ self,
+ cam_num=0,
+ cap_parameters_dict = cap_default_parameters_dict,
+ vid_save_path=None,
+ frame_queue = None,
+ thread_barrier = None,
+ exit_event = None,
+ show_cam_stream = False,
+ console = None,
+ show_console = False,
+ ):
+ """Open a camera stream using `cv2.VideoCapture()`.
+ If `Windows`, use `cv2.VideoCapture(camNum, cv2.CAP_DSHOW)` to make video initialize much faster. Otherwise, use `cv2.VideoCapture(camNum, cv2.CAP_ANY)
+
+ Args:
+ camNum (int, optional): The ID of the camera to open. Defaults to 0 (i.e. the first camera it finds)
+ vid_save_path (pathlib Path, optional): Where to save the video. Defaults to None.
+ barrier (threading.Barrier, optional): Barrier for syncronized multicam recording. Defaults to None.
+ frame_queue (queue.Queue, optional): [description]. Queue to send out images when we're recording in a thread.
+ """
+
+ self._cam_num = cam_num
+ self._cam_name = 'Camera_{}'.format(str(self._cam_num).zfill(2))
+ self._cam_short_name = 'cam{}'.format(self._cam_name)
+
+ self._vid_cap_start_time_unix = None
+
+ self._cap_parameters_dict = cap_parameters_dict
+
+ self._frame_queue = frame_queue
+ self._thread_barrier = thread_barrier
+ self._exit_event = exit_event
+ self._vid_save_path = vid_save_path
+ self._show_console = show_console
+ self.rich_console = console # a console object from the Rich python package
+
+
+ if vid_save_path:
+ self._vid_save_path = Path(vid_save_path)
+
+
+ if not console:
+ self.rich_console = Console()
+
+ self.open() #open VideoCapture Object
+
+ self._show_cam_stream = show_cam_stream
+ if self._show_cam_stream:
+ self.show()#display camera stream
+
+ if self._frame_queue:
+ self.run_in_thread() #launch in thread (or process?) mode
+ ##
+ ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ## β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ## β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ##
+ ##
+ @property
+ def cam_num(self):
+ return self._cam_num
+
+ @property
+ def cam_name(self):
+ return self._cam_name
+
+ @property
+ def cam_short_name(self):
+ return self._cam_short_name
+
+ @property
+ def vid_save_path(self):
+ return self._vid_save_path
+
+ @property
+ def show_cam_stream(self):
+ return self._show_cam_stream
+
+ @show_cam_stream.setter
+ def show_cam_stream(self, input_bool):
+ self._show_cam_stream = input_bool
+
+ @property
+ def vid_cap_start_time_unix(self):
+ return self._vid_cap_start_time_unix
+
+ @property
+ def vid_cap_timestamps_unix_ns(self): #not really a property though?
+ return self._vid_cap_timestamps_unix_ns
+
+ @property
+ def show_console(self):
+ return self._show_console
+
+ @show_console.setter
+ def show_console(self, input_bool):
+ self._show_console = input_bool
+
+ ###
+ ###
+ ### β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ
+ ###
+ ###
+ ###
+
+ def show_cam_stream(self, show_cam_stream_bool=True):
+ """whether to open a window showing camera stream
+
+ calls `self.show()` when set to `True`
+ and calls `self.close()` when set to `False` (b/c I'm too lazy to figure out how to make ti close th the display without closing the capture right now, sorry lol)
+
+ Args:
+ show_cam_stream_bool (Bool): whether to show stream (default)
+
+ Returns:
+ self
+ """
+ assert type(show_cam_stream_bool) == type(True), 'Input to `show_cam_stream` must be a bool'
+ self._show_cam_stream = show_cam_stream_bool
+
+ if self._show_cam_stream:
+ self.show()
+ else:
+ self.close()
+
+ return self._show_cam_stream
+ ###
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ###
+ ###
+ def open(self):
+ """
+ Open Video Capture Object and dispaly in little video
+ """
+
+ if platform.system() == 'Windows':
+ self.cv2_cap = cv2.VideoCapture(self._cam_num, cv2.CAP_DSHOW)
+ else:
+ self.cv2_cap = cv2.VideoCapture(self._cam_num, cv2.CAP_ANY)
+
+ self.cv2_cap.set(cv2.CAP_PROP_EXPOSURE, self._cap_parameters_dict['exposure'])
+ self.cv2_cap.set(cv2.CAP_PROP_FRAME_WIDTH, self._cap_parameters_dict['cap_resolution_width'])
+ self.cv2_cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self._cap_parameters_dict['exposure'])
+
+ if not self.cv2_cap.isOpened():
+ self.rich_console.log("Camera# "+str(self._cam_num)+" failed to open :(")
+
+ else:
+ self.rich_console.log("Camera# "+str(self._cam_num)+" VideoCapture started successfully")
+ self._vid_cap_start_time_unix = time.time_ns() #the precision is aspirational, lol
+ self._vid_cap_timestamps_unix_ns = np.empty(0)
+
+ ###
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ###
+
+ def show(self):
+ """
+ display the camera stream, press ESC to close (and release the `cv2_cap`)
+ """
+ success, image, timestamp = self.read_next_frame()
+
+ while success:
+ cv2.imshow(self._cam_name, image)
+
+ success, image, timestamp = self.read_next_frame()
+
+ console_msg = self.cam_name + " read an image at {:.4f}".format(timestamp)
+ self.update_console(console_msg)
+ self._vid_cap_timestamps_unix_ns = np.append(self.vid_cap_timestamps_unix_ns, timestamp)
+
+ if self.wait_key() == 27: # exit on ESC
+ self.close()
+
+ if cv2.getWindowProperty(self._cam_name, cv2.WND_PROP_VISIBLE) < 1: #break loop if window closed
+ break
+ cv2.destroyAllWindows()
+
+ ###
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ###
+ ###
+ def run_in_thread(self):
+ """run camera in a thread
+ put incoming images into an tuple containing camNum_image_timestamp_tuple and stuff it into `self._frame_queue`
+ """
+ while not self._exit_event.is_set():
+ try:
+ success, image, timestamp = self.read_next_frame()
+ cam_image_timestamp_tuple = (self.cam_num, image, timestamp)
+
+ self._frame_queue.put(cam_image_timestamp_tuple) #stuff this frame tuple packet into this camera's Queueue object
+
+ # log_msg = self.cam_name+" got a frame at timestamp:"+ str(timestamp) + ' queue size: ' + str(self._frame_queue.qsize())
+ # self.rich_console.log(log_msg)
+
+ self._thread_barrier.wait()
+ except:
+ self.rich_console.print_exception()
+
+
+ ###
+ ###
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ### β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+ ###
+ ###
+
+
+
+ def __enter__(self):
+ """Context manager - No need to do anything special on start"""
+ return self
+
+ def __exit__(self, exc_type, exc_value, exc_traceback):
+ """Context manager - close `self.cv2_cap` on exit"""
+ self.close()
+ return self
+
+ def update_console(self, console_msg):
+ if self.show_console:
+ self.rich_console.log(console_msg) #there should be a way to log this without printing it, but I don't know how....
+
+ def read_next_frame(self):
+ """ Grab next frame, return `Tuple(success[bool, True], image, timestamp)` on success or `Tuple(success[bool, False], False, False)` on failure
+
+ Returns:
+ Success[bool]: True if frame image captured successfully
+ image: the image that was recieved from the VideoCapture object
+ timestamp: unix timestamp from time.time_ns()
+ """
+ success, image = self.cv2_cap.read()
+ timestamp = time.time_ns() #the precision is aspirational, lol
+ if success:
+ self._vid_cap_timestamps_unix_ns = np.append(self._vid_cap_timestamps_unix_ns, time.time_ns()) #the precision is aspirational, lol
+ return success, image, timestamp
+ else:
+ return success, success, success
+
+ def close(self):
+ """
+ close the video
+ """
+ self.cv2_cap.release()
+
+
+ def wait_key(self):
+
+ if self.show_cam_stream:
+ self._wait_key = cv2.waitKey(1)
+ else:
+ self._wait_key = 27
+
+ return self._wait_key
+
+
+###
+### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
+### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ
+### β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ
+### β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
+###
+###
+if __name__ == '__main__':
+
+ with FMC_Camera() as cam:
+ console = Console() #create Rich console to catch and print exceptions
+ try:
+ while True:
+ cam.show()
+ break
+ except Exception:
+ console.print_exception()
+
diff --git a/freemocap/dev_scratchpad/dev_alpha/fmc_pyfiglet.py b/freemocap/dev_scratchpad/dev_alpha/fmc_pyfiglet.py
new file mode 100644
index 00000000..ca4e416e
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/fmc_pyfiglet.py
@@ -0,0 +1,20 @@
+from pyfiglet import Figlet
+
+def figlet(input_string, font_name='banner3'):
+ """simple wrapper for pyfiglet, take in string and retrun in figlet ascii format (default font ('banner3')"""
+
+ f = Figlet(font=font_name)
+
+ return f.renderText(str(input_string))
+
+if __name__== '__main__':
+ import sys
+ input_string = ''
+
+ for thisArg in sys.argv[1:]:
+ input_string = input_string + thisArg +' '
+
+ if not input_string:
+ input_string = 'henlo big txt'
+
+ print(figlet(input_string))
diff --git a/freemocap/dev_scratchpad/dev_alpha/kinda_gui/test_gui.py b/freemocap/dev_scratchpad/dev_alpha/kinda_gui/test_gui.py
new file mode 100644
index 00000000..6956929a
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/kinda_gui/test_gui.py
@@ -0,0 +1,97 @@
+import sys
+import time
+# Import QApplication and the required widgets from PyQt5.QtWidgets
+
+
+from PyQt5.QtCore import Qt
+from PyQt5.QtWidgets import QApplication
+from PyQt5.QtWidgets import QMainWindow
+from PyQt5.QtWidgets import QWidget
+from PyQt5.QtWidgets import QLineEdit
+from PyQt5.QtWidgets import QPushButton
+from PyQt5.QtWidgets import QCheckBox
+from PyQt5.QtWidgets import QHBoxLayout
+from PyQt5.QtWidgets import QVBoxLayout
+from PyQt5.QtWidgets import QLabel
+from test_iPython_gui import IPythonConsoleWidget
+
+from PyQt5.QtGui import QPixmap
+
+import freemocap as fmc
+
+sessionParam_dict = {
+ "useOpenPose": False,
+}
+
+def import_fmc():
+
+ import_text = 'import freemocap as fmc'
+ print('sending command:' + import_text)
+
+ iPyWidget.print_text(import_text)
+ iPyWidget.execute_command(import_text)
+
+def set_useOpenPose(useOpenPose_button):
+
+ if useOpenPose_button.isChecked():
+ sessionParam_dict['useOpenPose'] = True
+ runMeButton.setText('fmc.RunMe(useOpenPose=True)')
+ else:
+ sessionParam_dict['useOpenPose'] = False
+ runMeButton.setText('fmc.RunMe()')
+
+
+def run_fmc():
+ useOpenPoseBool = sessionParam_dict['useOpenPose']
+ fmc.RunMe(useOpenPose=useOpenPoseBool)
+
+ # fmc_runme_text = 'fmc.RunMe()'
+ # print('sending command:' + fmc_runme_text)
+
+ # iPyWidget.print_text(fmc_runme_text)
+ # iPyWidget.execute_command(fmc_runme_text)
+
+app = QApplication(sys.argv)
+
+window = QWidget()
+window.setWindowTitle('PyQT Test')
+
+main_layout = QHBoxLayout() #This is the whole GUI window
+
+# logo_label = QLabel()
+# logo_pixmap = QPixmap('freemocap-logo--blackOutline_squareTransCanvas-01.png')
+# logo_label.setPixmap(logo_pixmap)
+# logo_label.setScaledContents(True)
+# main_layout.addWidget(logo_label)
+
+
+#Make a vertical box of check boxes
+button_layout = QVBoxLayout()
+
+useOpenPose_button = QCheckBox('useOpenPose')
+useOpenPose_button.stateChanged.connect(set_useOpenPose)
+button_layout.addWidget(QCheckBox('useOpenPose'))
+# button_layout.addWidget(QCheckBox('useDLC'))
+# button_layout.addWidget(QCheckBox('useMediaPipe'))
+
+# importFMC_button = QPushButton('import freemocap as fmc')
+# importFMC_button.clicked.connect(import_fmc)
+# button_layout.addWidget(importFMC_button)
+
+
+runMeButton = QPushButton('fmc.RunMe()')
+runMeButton.clicked.connect(run_fmc)
+button_layout.addWidget(runMeButton)
+
+main_layout.addLayout(button_layout)
+
+
+#Add the IpYthon console widget
+iPyWidget = IPythonConsoleWidget()
+main_layout.addWidget(iPyWidget)
+iPyWidget.print_text('import freemocap as fmc')
+
+window.setLayout(main_layout)
+
+window.show()
+sys.exit(app.exec_())
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha/kinda_gui/test_iPython_gui.py b/freemocap/dev_scratchpad/dev_alpha/kinda_gui/test_iPython_gui.py
new file mode 100644
index 00000000..f683ad59
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/kinda_gui/test_iPython_gui.py
@@ -0,0 +1,61 @@
+# originially cribbed from - https://stackoverflow.com/a/67829211/14662833
+
+from qtpy.QtWidgets import QApplication
+from qtconsole.rich_jupyter_widget import RichJupyterWidget
+from qtconsole.inprocess import QtInProcessKernelManager
+
+
+class IPythonConsoleWidget(RichJupyterWidget):
+
+ def __init__(self, customBanner=None, *args, **kwargs):
+ super(IPythonConsoleWidget, self).__init__(*args, **kwargs)
+
+ if customBanner is not None:
+ self.banner = customBanner
+
+ self.font_size = 10
+ self.kernel_manager = QtInProcessKernelManager()
+ self.kernel_manager.start_kernel(show_banner=False)
+ self.kernel_manager.kernel.gui = 'qt'
+ self.kernel_client = self._kernel_manager.client()
+ self.kernel_client.start_channels()
+
+ def stop():
+ self.kernel_client.stop_channels()
+ self.kernel_manager.shutdown_kernel()
+ self.guisupport.get_app_qt().exit()
+
+ self.exit_requested.connect(stop)
+
+ def push_vars(self, variableDict):
+ """
+ Given a dictionary containing name / value pairs, push those variables
+ to the Jupyter console widget
+ """
+ self.kernel_manager.kernel.shell.push(variableDict)
+
+ def clear(self):
+ """
+ Clears the terminal
+ """
+ self._control.clear()
+
+ def print_text(self, text):
+ """
+ Prints some plain text to the console
+ """
+ self._append_plain_text(text)
+
+ def execute_command(self, command):
+ """
+ Execute a command in the frame of the console widget
+ """
+ self._execute(command, False)
+
+
+
+if __name__ == '__main__':
+ app = QApplication([])
+ widget = IPythonConsoleWidget()
+ widget.show()
+ app.exec_()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha/scratch/VideoTemplate_pyqt5.py b/freemocap/dev_scratchpad/dev_alpha/scratch/VideoTemplate_pyqt5.py
new file mode 100644
index 00000000..7fd9439a
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/scratch/VideoTemplate_pyqt5.py
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+
+# Form implementation generated from reading ui file '.\VideoTemplate.ui'
+#
+# Created by: PyQt5 UI code generator 5.15.4
+#
+# WARNING: Any manual changes made to this file will be lost when pyuic5 is
+# run again. Do not edit this file unless you know what you are doing.
+
+
+from PyQt5 import QtCore, QtGui, QtWidgets
+
+
+class Ui_MainWindow(object):
+ def setupUi(self, MainWindow):
+ MainWindow.setObjectName("MainWindow")
+ MainWindow.resize(695, 798)
+ self.centralwidget = QtWidgets.QWidget(MainWindow)
+ self.centralwidget.setObjectName("centralwidget")
+ self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
+ self.gridLayout_2.setObjectName("gridLayout_2")
+ self.cudaCheck = QtWidgets.QCheckBox(self.centralwidget)
+ self.cudaCheck.setObjectName("cudaCheck")
+ self.gridLayout_2.addWidget(self.cudaCheck, 9, 0, 1, 2)
+ self.numbaCheck = QtWidgets.QCheckBox(self.centralwidget)
+ self.numbaCheck.setObjectName("numbaCheck")
+ self.gridLayout_2.addWidget(self.numbaCheck, 9, 2, 1, 2)
+ self.downsampleCheck = QtWidgets.QCheckBox(self.centralwidget)
+ self.downsampleCheck.setObjectName("downsampleCheck")
+ self.gridLayout_2.addWidget(self.downsampleCheck, 8, 0, 1, 2)
+ self.scaleCheck = QtWidgets.QCheckBox(self.centralwidget)
+ self.scaleCheck.setObjectName("scaleCheck")
+ self.gridLayout_2.addWidget(self.scaleCheck, 4, 0, 1, 1)
+ self.gridLayout = QtWidgets.QGridLayout()
+ self.gridLayout.setObjectName("gridLayout")
+ self.rawRadio = QtWidgets.QRadioButton(self.centralwidget)
+ self.rawRadio.setObjectName("rawRadio")
+ self.gridLayout.addWidget(self.rawRadio, 3, 0, 1, 1)
+ self.gfxRadio = QtWidgets.QRadioButton(self.centralwidget)
+ self.gfxRadio.setChecked(True)
+ self.gfxRadio.setObjectName("gfxRadio")
+ self.gridLayout.addWidget(self.gfxRadio, 2, 0, 1, 1)
+ self.stack = QtWidgets.QStackedWidget(self.centralwidget)
+ self.stack.setObjectName("stack")
+ self.page = QtWidgets.QWidget()
+ self.page.setObjectName("page")
+ self.gridLayout_3 = QtWidgets.QGridLayout(self.page)
+ self.gridLayout_3.setObjectName("gridLayout_3")
+ self.graphicsView = GraphicsView(self.page)
+ self.graphicsView.setObjectName("graphicsView")
+ self.gridLayout_3.addWidget(self.graphicsView, 0, 0, 1, 1)
+ self.stack.addWidget(self.page)
+ self.page_2 = QtWidgets.QWidget()
+ self.page_2.setObjectName("page_2")
+ self.gridLayout_4 = QtWidgets.QGridLayout(self.page_2)
+ self.gridLayout_4.setObjectName("gridLayout_4")
+ self.rawImg = RawImageWidget(self.page_2)
+ sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
+ sizePolicy.setHorizontalStretch(0)
+ sizePolicy.setVerticalStretch(0)
+ sizePolicy.setHeightForWidth(self.rawImg.sizePolicy().hasHeightForWidth())
+ self.rawImg.setSizePolicy(sizePolicy)
+ self.rawImg.setObjectName("rawImg")
+ self.gridLayout_4.addWidget(self.rawImg, 0, 0, 1, 1)
+ self.stack.addWidget(self.page_2)
+ self.gridLayout.addWidget(self.stack, 0, 0, 1, 1)
+ self.rawGLRadio = QtWidgets.QRadioButton(self.centralwidget)
+ self.rawGLRadio.setObjectName("rawGLRadio")
+ self.gridLayout.addWidget(self.rawGLRadio, 4, 0, 1, 1)
+ self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 4)
+ self.dtypeCombo = QtWidgets.QComboBox(self.centralwidget)
+ self.dtypeCombo.setObjectName("dtypeCombo")
+ self.dtypeCombo.addItem("")
+ self.dtypeCombo.addItem("")
+ self.dtypeCombo.addItem("")
+ self.gridLayout_2.addWidget(self.dtypeCombo, 3, 2, 1, 1)
+ self.label = QtWidgets.QLabel(self.centralwidget)
+ self.label.setObjectName("label")
+ self.gridLayout_2.addWidget(self.label, 3, 0, 1, 1)
+ self.rgbLevelsCheck = QtWidgets.QCheckBox(self.centralwidget)
+ self.rgbLevelsCheck.setObjectName("rgbLevelsCheck")
+ self.gridLayout_2.addWidget(self.rgbLevelsCheck, 4, 1, 1, 1)
+ self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
+ self.horizontalLayout_2.setObjectName("horizontalLayout_2")
+ self.minSpin2 = SpinBox(self.centralwidget)
+ self.minSpin2.setEnabled(False)
+ self.minSpin2.setObjectName("minSpin2")
+ self.horizontalLayout_2.addWidget(self.minSpin2)
+ self.label_3 = QtWidgets.QLabel(self.centralwidget)
+ self.label_3.setAlignment(QtCore.Qt.AlignCenter)
+ self.label_3.setObjectName("label_3")
+ self.horizontalLayout_2.addWidget(self.label_3)
+ self.maxSpin2 = SpinBox(self.centralwidget)
+ self.maxSpin2.setEnabled(False)
+ self.maxSpin2.setObjectName("maxSpin2")
+ self.horizontalLayout_2.addWidget(self.maxSpin2)
+ self.gridLayout_2.addLayout(self.horizontalLayout_2, 5, 2, 1, 1)
+ self.horizontalLayout = QtWidgets.QHBoxLayout()
+ self.horizontalLayout.setObjectName("horizontalLayout")
+ self.minSpin1 = SpinBox(self.centralwidget)
+ self.minSpin1.setObjectName("minSpin1")
+ self.horizontalLayout.addWidget(self.minSpin1)
+ self.label_2 = QtWidgets.QLabel(self.centralwidget)
+ self.label_2.setAlignment(QtCore.Qt.AlignCenter)
+ self.label_2.setObjectName("label_2")
+ self.horizontalLayout.addWidget(self.label_2)
+ self.maxSpin1 = SpinBox(self.centralwidget)
+ self.maxSpin1.setObjectName("maxSpin1")
+ self.horizontalLayout.addWidget(self.maxSpin1)
+ self.gridLayout_2.addLayout(self.horizontalLayout, 4, 2, 1, 1)
+ self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
+ self.horizontalLayout_3.setObjectName("horizontalLayout_3")
+ self.minSpin3 = SpinBox(self.centralwidget)
+ self.minSpin3.setEnabled(False)
+ self.minSpin3.setObjectName("minSpin3")
+ self.horizontalLayout_3.addWidget(self.minSpin3)
+ self.label_4 = QtWidgets.QLabel(self.centralwidget)
+ self.label_4.setAlignment(QtCore.Qt.AlignCenter)
+ self.label_4.setObjectName("label_4")
+ self.horizontalLayout_3.addWidget(self.label_4)
+ self.maxSpin3 = SpinBox(self.centralwidget)
+ self.maxSpin3.setEnabled(False)
+ self.maxSpin3.setObjectName("maxSpin3")
+ self.horizontalLayout_3.addWidget(self.maxSpin3)
+ self.gridLayout_2.addLayout(self.horizontalLayout_3, 6, 2, 1, 1)
+ self.lutCheck = QtWidgets.QCheckBox(self.centralwidget)
+ self.lutCheck.setObjectName("lutCheck")
+ self.gridLayout_2.addWidget(self.lutCheck, 7, 0, 1, 1)
+ self.alphaCheck = QtWidgets.QCheckBox(self.centralwidget)
+ self.alphaCheck.setObjectName("alphaCheck")
+ self.gridLayout_2.addWidget(self.alphaCheck, 7, 1, 1, 1)
+ self.gradient = GradientWidget(self.centralwidget)
+ sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
+ sizePolicy.setHorizontalStretch(0)
+ sizePolicy.setVerticalStretch(0)
+ sizePolicy.setHeightForWidth(self.gradient.sizePolicy().hasHeightForWidth())
+ self.gradient.setSizePolicy(sizePolicy)
+ self.gradient.setObjectName("gradient")
+ self.gridLayout_2.addWidget(self.gradient, 7, 2, 1, 2)
+ spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ self.gridLayout_2.addItem(spacerItem, 3, 3, 1, 1)
+ self.fpsLabel = QtWidgets.QLabel(self.centralwidget)
+ font = QtGui.QFont()
+ font.setPointSize(12)
+ self.fpsLabel.setFont(font)
+ self.fpsLabel.setAlignment(QtCore.Qt.AlignCenter)
+ self.fpsLabel.setObjectName("fpsLabel")
+ self.gridLayout_2.addWidget(self.fpsLabel, 0, 0, 1, 4)
+ self.rgbCheck = QtWidgets.QCheckBox(self.centralwidget)
+ self.rgbCheck.setObjectName("rgbCheck")
+ self.gridLayout_2.addWidget(self.rgbCheck, 3, 1, 1, 1)
+ self.label_5 = QtWidgets.QLabel(self.centralwidget)
+ self.label_5.setObjectName("label_5")
+ self.gridLayout_2.addWidget(self.label_5, 2, 0, 1, 1)
+ self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
+ self.horizontalLayout_4.setObjectName("horizontalLayout_4")
+ self.framesSpin = QtWidgets.QSpinBox(self.centralwidget)
+ self.framesSpin.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
+ self.framesSpin.setProperty("value", 10)
+ self.framesSpin.setObjectName("framesSpin")
+ self.horizontalLayout_4.addWidget(self.framesSpin)
+ self.widthSpin = QtWidgets.QSpinBox(self.centralwidget)
+ self.widthSpin.setButtonSymbols(QtWidgets.QAbstractSpinBox.PlusMinus)
+ self.widthSpin.setMaximum(10000)
+ self.widthSpin.setProperty("value", 512)
+ self.widthSpin.setObjectName("widthSpin")
+ self.horizontalLayout_4.addWidget(self.widthSpin)
+ self.heightSpin = QtWidgets.QSpinBox(self.centralwidget)
+ self.heightSpin.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
+ self.heightSpin.setMaximum(10000)
+ self.heightSpin.setProperty("value", 512)
+ self.heightSpin.setObjectName("heightSpin")
+ self.horizontalLayout_4.addWidget(self.heightSpin)
+ self.gridLayout_2.addLayout(self.horizontalLayout_4, 2, 1, 1, 2)
+ self.sizeLabel = QtWidgets.QLabel(self.centralwidget)
+ self.sizeLabel.setText("")
+ self.sizeLabel.setObjectName("sizeLabel")
+ self.gridLayout_2.addWidget(self.sizeLabel, 2, 3, 1, 1)
+ MainWindow.setCentralWidget(self.centralwidget)
+
+ self.retranslateUi(MainWindow)
+ self.stack.setCurrentIndex(1)
+ QtCore.QMetaObject.connectSlotsByName(MainWindow)
+
+ def retranslateUi(self, MainWindow):
+ _translate = QtCore.QCoreApplication.translate
+ MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
+ self.cudaCheck.setText(_translate("MainWindow", "Use CUDA (GPU) if available"))
+ self.numbaCheck.setText(_translate("MainWindow", "Use Numba if available"))
+ self.downsampleCheck.setText(_translate("MainWindow", "Auto downsample"))
+ self.scaleCheck.setText(_translate("MainWindow", "Scale Data"))
+ self.rawRadio.setText(_translate("MainWindow", "RawImageWidget"))
+ self.gfxRadio.setText(_translate("MainWindow", "GraphicsView + ImageItem"))
+ self.rawGLRadio.setText(_translate("MainWindow", "RawGLImageWidget"))
+ self.dtypeCombo.setItemText(0, _translate("MainWindow", "uint8"))
+ self.dtypeCombo.setItemText(1, _translate("MainWindow", "uint16"))
+ self.dtypeCombo.setItemText(2, _translate("MainWindow", "float"))
+ self.label.setText(_translate("MainWindow", "Data type"))
+ self.rgbLevelsCheck.setText(_translate("MainWindow", "RGB"))
+ self.label_3.setText(_translate("MainWindow", "<--->"))
+ self.label_2.setText(_translate("MainWindow", "<--->"))
+ self.label_4.setText(_translate("MainWindow", "<--->"))
+ self.lutCheck.setText(_translate("MainWindow", "Use Lookup Table"))
+ self.alphaCheck.setText(_translate("MainWindow", "alpha"))
+ self.fpsLabel.setText(_translate("MainWindow", "FPS"))
+ self.rgbCheck.setText(_translate("MainWindow", "RGB"))
+ self.label_5.setText(_translate("MainWindow", "Image size"))
+from pyqtgraph import GradientWidget, GraphicsView, SpinBox
+from pyqtgraph.widgets.RawImageWidget import RawImageWidget
diff --git a/freemocap/dev_scratchpad/dev_alpha/scratch/cv2_cam_thread_queue_jsm.py b/freemocap/dev_scratchpad/dev_alpha/scratch/cv2_cam_thread_queue_jsm.py
new file mode 100644
index 00000000..1ad545ae
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/scratch/cv2_cam_thread_queue_jsm.py
@@ -0,0 +1,256 @@
+
+# %%
+import concurrent.futures
+import logging
+import queue
+import random
+import threading
+import time
+import platform
+
+import cv2
+import matplotlib.pyplot as plt
+import numpy as np
+import h5py
+from pathlib import Path
+
+from rich import print
+from rich import inspect
+
+def CamRecordThread(camCap, webcam_frames_queue, barrier, exit_event, camNum):
+ """Pretend we're getting a number from the network."""
+ while not exit_event.is_set():
+
+ try:
+ success, frame_image = camCap.read()
+ timestamp = time.time()
+ cam_num_tuple = (camNum, )
+ frame_timestamp_tuple = (frame_image, timestamp)
+ cam_frame_timestamp_tuple = cam_num_tuple+frame_timestamp_tuple
+ webcam_frames_queue.put(cam_frame_timestamp_tuple)
+ log_msg = 'Camera '+ str(camNum)+" got a frame at timestamp:"+ str(timestamp) + ' queue size: ' + str(webcam_frames_queue.qsize())
+ print(log_msg)
+ logging.info(log_msg)
+ barrier.wait()
+
+ except Exception as ex:
+ template = "An exception of type {0} occurred. Arguments:\n{1!r}"
+ message = template.format(type(ex).__name__, ex.args)
+ logging.info(message)
+ print(message)
+ exit_event.set()
+
+
+ camCap.release()
+ logging.info("Producer received exit_event. Exiting")
+
+# def incoming_frames_handler(webcam_frames_queue, exit_event):
+# """Pretend we're saving a number in the database."""
+# while not exit_event.is_set() or not webcam_frames_queue.empty():
+# try:
+# cam_frame_timestamp_tuple= webcam_frames_queue.get() #tuple(camNum, (frame_image,timestamp))
+
+# camID = cam_frame_timestamp_tuple[0]
+# frame_timestamp_tuple = cam_frame_timestamp_tuple[1]
+# thisFrame = frame_timestamp_tuple[0]
+# thisTimestamp = frame_timestamp_tuple[1]
+
+# allTimestamps.append(thisTimestamp)
+# camTimestamps_list[camID] = np.append(camTimestamps_list[camID], thisTimestamp)
+
+# logging.info(
+# "IncomingFrameHandler got the frame from camera#"+str(camID)+" with timestamp: %s (size=%d)", str(thisTimestamp), webcam_frames_queue.qsize()
+# )
+
+
+
+# except:
+# print('something broke in the incoming_frame_handler')
+# exit_event.set()
+
+# logging.info("Consumer received exit_event . Exiting")
+
+def saveMultiViewToMP4():
+ multiIm = None
+ theseFrames_list = [None]* numCams #create an empty list with numCams entries (Python is weird sometimes, lol)
+ theseFrameTuples_list = theseFrames_list
+ theseTimestamps = np.empty(numCams)
+
+ while webcam_frames_queue.qsize() > 0:
+ this_cam_frame_timestamp_tuple = webcam_frames_queue.get() #(camNum,(frame,timestamp))
+ camNum = this_cam_frame_timestamp_tuple[0]
+ theseFrames_list[camNum] = this_cam_frame_timestamp_tuple[1]
+ thisTimestamp = this_cam_frame_timestamp_tuple[2]
+ theseTimestamps[camNum] = thisTimestamp
+ camTimestamps_list[camNum] = np.append(camTimestamps_list[camNum], thisTimestamp)
+
+ # allMultiframes.append(theseFrameTuples_list)
+
+ for camNum, image in enumerate(theseFrames_list):
+ if camNum==0:
+ multiIm = image
+ else:
+ multiIm = cv2.hconcat([multiIm, image])
+
+ multiFrame_queue.put(multiIm)
+ print('multiframe_q size: {}'.format(multiFrame_queue.qsize()))
+
+
+
+
+
+
+
+def saveMultiViewToH5():
+ multiFrameNum = len(h5OutFile)
+ thisFrameName = 'MultiFrame_{}'.format(str(multiFrameNum).zfill(12)) # 12 zeros is probably enough. prove me wrong, you crazy apes <3
+ thisMultiFrameH5Group = h5OutFile.create_group(thisFrameName, track_order=True)
+
+ theseFrames_list = [None]*numCams #empty list of size (numCam)
+ theseTimestamps_unixEpoch = np.ndarray(numCams)
+
+ while webcam_frames_queue.qsize() > 0:
+ this_cam_frame_timestamp_tuple = webcam_frames_queue.get()
+ thisCamNum = this_cam_frame_timestamp_tuple[0]
+ theseFrames_list[thisCamNum] = this_cam_frame_timestamp_tuple[1] #the image frame from thisCamera on thisMultiFrame time period
+ thisTimestamp = this_cam_frame_timestamp_tuple[2] #the timestamp that this image frame was recieved by the camera
+ theseTimestamps_unixEpoch[thisCamNum] = thisTimestamp #the timestamps of each frame in this multiframe (size:numCams)
+ camTimestamps_list[thisCamNum] = np.append(camTimestamps_list[thisCamNum], thisTimestamp)#this'll get plotted later as a time sync diagnostic debug whosit :D
+
+ thisMultiFrame = np.hstack(theseFrames_list) #horizontally stack each image into a numpy array with dimensions (imageHeight, imageWidth*numCams, 3(RGB)). Equivalent to cv2.hconcat((image0,image1,...,imageN))
+
+ theseTimeStamps_fromRecStart = theseTimestamps_unixEpoch-init_time
+ thisMultiFrameH5Group.create_dataset('multiFrameImage', data = thisMultiFrame)
+ thisMultiFrameH5Group.create_dataset('each_timestamp_unix', data= theseTimestamps_unixEpoch)
+ thisMultiFrameH5Group.create_dataset('each_timestamp_fromRecordStart', data= theseTimeStamps_fromRecStart)
+ thisMultiFrameH5Group.create_dataset('mean_timestamp_unixEpoch', data= np.mean(theseTimestamps_unixEpoch))
+ thisMultiFrameH5Group.create_dataset('mean_timestamp_fromRecordStart', data= np.mean(theseTimeStamps_fromRecStart))
+ thisMultiFrameH5Group.create_dataset('timestamp', data= np.mean(theseTimeStamps_fromRecStart)) #this is the most intuitive timestamp to use per frame, it's a copy of the more verbosely named 'meanTimestamp_fromRecordStart'
+ print('wrote ' + thisFrameName +' to H5Py - multiframe_q size: {}'.format(multiFrame_queue.qsize()))
+
+def ShowMultiView(multiFrame_queue, outputVidObj):
+ while not exit_event.is_set():
+ multiIm = multiFrame_queue.get()
+ outputVidObj.write(multiIm)
+ cv2.imshow('m', multiIm)
+ key = cv2.waitKey(1)
+ if key == 27: # exit on ESC
+ exit_event.set()
+ cv2.destroyAllWindows()
+ outputVidObj.release()
+
+
+if __name__ == "__main__":
+
+ init_time = time.time()
+ vidSaveFolderPath = Path('saveFrames_'+str(time.time()))
+ vidSaveFolderPath.mkdir()
+
+ format = "%(asctime)s: %(message)s"
+ logging.basicConfig(filename=str(vidSaveFolderPath / 'log.txt'),format=format, level=logging.INFO,
+ datefmt="%H:%M:%S")
+
+ logging.info('Logging started :D')
+
+ numCams = 3
+ fps=30
+ camCap_list = []
+ allTimestamps = []
+ camTimestamps_list = []
+ camImPath_list = []
+ camAx_list = []
+ cam_artist = []
+ multiFr = None
+
+
+ for camNum in range(numCams):
+ camTimestamps_list.append(np.empty(0)) #we'll put the timestamps for each camea in here
+
+ logging.info('starting camera ' + str(camNum))
+
+ if platform.system() == 'Windows':
+ camCap_list.append(cv2.VideoCapture(camNum, cv2.CAP_DSHOW))
+ else:
+ camCap_list.append(cv2.VideoCapture(camNum, cv2.CAP_ANY))
+
+ camCap_list[camNum].set(cv2.CAP_PROP_FPS,fps)
+ camCap_list[camNum].set(cv2.CAP_PROP_EXPOSURE,-9)
+ logging.info('camera '+str(camNum)+ ' started')
+ success, image = camCap_list[-1].read()
+ assert success, "Camera {} failed to produce an image on startup".format(camNum)
+ if multiFr is None:
+ multiFr = image
+ else:
+ multiFr = cv2.hconcat([multiFr, image])
+
+ #create video save object
+ multiFr_height, multiFr_width, channels = multiFr.shape
+ multiFrameSize = (multiFr_width, multiFr_height)
+ fourcc = cv2.VideoWriter_fourcc(*'DIVX')
+ outputVid_fileName = str(vidSaveFolderPath / 'outVid.mp4')
+ outputVidObj = cv2.VideoWriter(outputVid_fileName, fourcc, fps, multiFrameSize)
+
+ webcam_frames_queue = queue.Queue()
+ multiFrame_queue = queue.Queue()
+ exit_event = threading.Event()
+
+ with h5py.File(str(vidSaveFolderPath/"multiFrames_saved_as_numpy_arrays.hdf5"), "w", track_order=True) as h5OutFile:
+ with concurrent.futures.ThreadPoolExecutor(max_workers=numCams+1) as executor:
+ # barrier = threading.Barrier(numCams, action=saveMultiViewToH5)
+ barrier = threading.Barrier(numCams, action=saveMultiViewToMP4)
+ for camNum, camCap in enumerate(camCap_list):
+ print('starting thread for cam# '+str(camNum))
+ executor.submit(CamRecordThread, camCap, webcam_frames_queue, barrier, exit_event, camNum)
+
+ executor.submit(ShowMultiView, multiFrame_queue, outputVidObj)
+ # print('starting frame handler')
+ # executor.submit(incoming_frames_handler, webcam_frames_queue, exit_event)
+
+ runtime = 10
+ logging.info("Main: Record for {} seconds".format(runtime))
+ time.sleep(runtime)
+
+ exit_event.set() #send the 'Exit' signal to everyone
+ print('closing streams, I guess?')
+
+ print('closing h5 file too, I think?')
+
+ print('all done!')
+
+
+
+
+# %% get multiFrame framerate and frameTimespread
+ camTimestamps = np.stack(camTimestamps_list, axis=0) #a nice, matlaby 2d array
+ meanMultiFrameTimestamp = np.mean(camTimestamps, axis=0)
+ meanMultiFrameTimespan = np.max(camTimestamps, axis=0) - np.min(camTimestamps, axis=0) #what was the timespan covered by each frame
+#%%
+plt.ion()
+fig = plt.figure(figsize=(18,10))
+max_frame_duration = .1
+ax1 = plt.subplot(231, title='Camera Frame Timestamp vs Frame#', xlabel='Frame#', ylabel='Timestamp (sec)')
+ax2 = plt.subplot(232, ylim=(0,max_frame_duration), title='Camera Frame Duration Trace', xlabel='Frame#', ylabel='Duration (sec)')
+ax3 = plt.subplot(233, xlim=(0,max_frame_duration), title='Camera Frame Duration Histogram (count)', xlabel='Duration(s, 1ms bins)', ylabel='Probability')
+ax4 = plt.subplot(234, title='MuliFrame Timestamp vs Frame#', xlabel='Frame#', ylabel='Timestamp (sec)')
+ax5 = plt.subplot(235, ylim=(0,max_frame_duration), title='Multi Frame Duration/Span Trace', xlabel='Frame#', ylabel='Duration (sec)')
+ax6 = plt.subplot(236, xlim=(0,max_frame_duration), title='MultiFrame Duration Histogram (count)', xlabel='Duration(s, 1ms bins)', ylabel='Probability')
+
+for camNum, thisCamTimestamps in enumerate(camTimestamps_list):
+ ax1.plot(thisCamTimestamps, label='Camera#'+str(camNum))
+ ax1.legend()
+ ax2.plot(np.diff(thisCamTimestamps),'.')
+ ax3.hist(np.diff(thisCamTimestamps), bins=np.arange(0,max_frame_duration,.001), alpha=0.5)
+
+ax4.plot(meanMultiFrameTimestamp, color='darkslategrey', label='MultiFrame'+str(camNum))
+ax5.plot(np.diff(meanMultiFrameTimestamp),'.',color='darkslategrey', label='Frame Duration')
+ax5.plot(meanMultiFrameTimespan, '.', color='orangered', label='Frame TimeSpan')
+ax5.legend()
+ax6.hist(np.diff(meanMultiFrameTimestamp), bins=np.arange(0,max_frame_duration,.001), density=True, alpha=0.5, color='darkslategrey', label='Frame Duration')
+ax6.hist(np.diff(meanMultiFrameTimespan), bins=np.arange(0,max_frame_duration,.001), density=True, alpha=0.5, color='orangered', label='Frame Timespan')
+ax5.legend()
+plt.show()
+plt.savefig(str(vidSaveFolderPath / 'recording_diagnostics.png'))
+f=9
+
+
+# outVidObj.release()
\ No newline at end of file
diff --git a/freemocap/dev_scratchpad/dev_alpha/scratch/geeksforgeeks_qt_camera.py b/freemocap/dev_scratchpad/dev_alpha/scratch/geeksforgeeks_qt_camera.py
new file mode 100644
index 00000000..e560af2e
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/scratch/geeksforgeeks_qt_camera.py
@@ -0,0 +1,216 @@
+# importing required libraries
+from PyQt5.QtWidgets import *
+from PyQt5.QtMultimedia import *
+from PyQt5.QtMultimediaWidgets import *
+import os
+import sys
+import time
+
+# Main window class
+class MainWindow(QMainWindow):
+
+ # constructor
+ def __init__(self):
+ super().__init__()
+
+ # setting geometry
+ self.setGeometry(100, 100,
+ 800, 600)
+
+ # setting style sheet
+ self.setStyleSheet("background : lightgrey;")
+
+ # getting available cameras
+ self.available_cameras = QCameraInfo.availableCameras()
+
+ # if no camera found
+ if not self.available_cameras:
+ # exit the code
+ sys.exit()
+
+ # creating a status bar
+ self.status = QStatusBar()
+
+ # setting style sheet to the status bar
+ self.status.setStyleSheet("background : white;")
+
+ # adding status bar to the main window
+ self.setStatusBar(self.status)
+
+ # path to save
+ self.save_path = ""
+
+ # creating a QCameraViewfinder object
+ self.viewfinder = QCameraViewfinder()
+
+ # showing this viewfinder
+ self.viewfinder.show()
+
+ # making it central widget of main window
+ self.setCentralWidget(self.viewfinder)
+
+ # Set the default camera.
+ self.select_camera(0)
+
+ # creating a tool bar
+ toolbar = QToolBar("Camera Tool Bar")
+
+ # adding tool bar to main window
+ self.addToolBar(toolbar)
+
+ # creating a photo action to take photo
+ click_action = QAction("Click photo", self)
+
+ # adding status tip to the photo action
+ click_action.setStatusTip("This will capture picture")
+
+ # adding tool tip
+ click_action.setToolTip("Capture picture")
+
+
+ # adding action to it
+ # calling take_photo method
+ click_action.triggered.connect(self.click_photo)
+
+ # adding this to the tool bar
+ toolbar.addAction(click_action)
+
+ # similarly creating action for changing save folder
+ change_folder_action = QAction("Change save location",
+ self)
+
+ # adding status tip
+ change_folder_action.setStatusTip("Change folder where picture will be saved saved.")
+
+ # adding tool tip to it
+ change_folder_action.setToolTip("Change save location")
+
+ # setting calling method to the change folder action
+ # when triggered signal is emitted
+ change_folder_action.triggered.connect(self.change_folder)
+
+ # adding this to the tool bar
+ toolbar.addAction(change_folder_action)
+
+
+ # creating a combo box for selecting camera
+ camera_selector = QComboBox()
+
+ # adding status tip to it
+ camera_selector.setStatusTip("Choose camera to take pictures")
+
+ # adding tool tip to it
+ camera_selector.setToolTip("Select Camera")
+ camera_selector.setToolTipDuration(2500)
+
+ # adding items to the combo box
+ camera_selector.addItems([camera.description()
+ for camera in self.available_cameras])
+
+ # adding action to the combo box
+ # calling the select camera method
+ camera_selector.currentIndexChanged.connect(self.select_camera)
+
+ # adding this to tool bar
+ toolbar.addWidget(camera_selector)
+
+ # setting tool bar stylesheet
+ toolbar.setStyleSheet("background : white;")
+
+
+
+ # setting window title
+ self.setWindowTitle("PyQt5 Cam")
+
+ # showing the main window
+ self.show()
+
+ # method to select camera
+ def select_camera(self, i):
+
+ # getting the selected camera
+ self.camera = QCamera(self.available_cameras[i])
+
+ # setting view finder to the camera
+ self.camera.setViewfinder(self.viewfinder)
+
+ # setting capture mode to the camera
+ self.camera.setCaptureMode(QCamera.CaptureStillImage)
+
+ # if any error occur show the alert
+ self.camera.error.connect(lambda: self.alert(self.camera.errorString()))
+
+ # start the camera
+ self.camera.start()
+
+ # creating a QCameraImageCapture object
+ self.capture = QCameraImageCapture(self.camera)
+
+ # showing alert if error occur
+ self.capture.error.connect(lambda error_msg, error,
+ msg: self.alert(msg))
+
+ # when image captured showing message
+ self.capture.imageCaptured.connect(lambda d,
+ i: self.status.showMessage("Image captured : "
+ + str(self.save_seq)))
+
+ # getting current camera name
+ self.current_camera_name = self.available_cameras[i].description()
+
+ # inital save sequence
+ self.save_seq = 0
+
+ # method to take photo
+ def click_photo(self):
+
+ # time stamp
+ timestamp = time.strftime("%d-%b-%Y-%H_%M_%S")
+
+ # capture the image and save it on the save path
+ self.capture.capture(os.path.join(self.save_path,
+ "%s-%04d-%s.jpg" % (
+ self.current_camera_name,
+ self.save_seq,
+ timestamp
+ )))
+
+ # increment the sequence
+ self.save_seq += 1
+
+ # change folder method
+ def change_folder(self):
+
+ # open the dialog to select path
+ path = QFileDialog.getExistingDirectory(self,
+ "Picture Location", "")
+
+ # if path is selected
+ if path:
+
+ # update the path
+ self.save_path = path
+
+ # update the sequence
+ self.save_seq = 0
+
+ # method for alerts
+ def alert(self, msg):
+
+ # error message
+ error = QErrorMessage(self)
+
+ # setting text to the error message
+ error.showMessage(msg)
+
+# Driver code
+if __name__ == "__main__" :
+
+ # create pyqt5 app
+ App = QApplication(sys.argv)
+
+ # create the instance of our Window
+ window = MainWindow()
+
+ # start the app
+ sys.exit(App.exec())
diff --git a/freemocap/dev_scratchpad/dev_alpha/scratch/jsm_cam_VideoSpeedTest.py b/freemocap/dev_scratchpad/dev_alpha/scratch/jsm_cam_VideoSpeedTest.py
new file mode 100644
index 00000000..aeb4ab1d
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/scratch/jsm_cam_VideoSpeedTest.py
@@ -0,0 +1,313 @@
+#jsm - 2021-Oct-23 - based on pyqtgrph.example VideoSpeedTest
+
+# -*- coding: utf-8 -*-
+"""
+Tests the speed of image updates for an ImageItem and RawImageWidget.
+The speed will generally depend on the type of data being shown, whether
+it is being scaled and/or converted by lookup table, and whether OpenGL
+is used by the view widget
+"""
+
+
+import argparse
+import sys
+
+import numpy as np
+
+import pyqtgraph as pg
+from pyqtgraph.Qt import QtGui, QtCore, QT_LIB
+from time import perf_counter
+
+import cv2
+
+pg.setConfigOption('imageAxisOrder', 'row-major')
+
+import importlib
+ui_template = importlib.import_module(f'VideoTemplate_{QT_LIB.lower()}')
+
+try:
+ import cupy as cp
+ pg.setConfigOption("useCupy", True)
+ _has_cupy = True
+except ImportError:
+ cp = None
+ _has_cupy = False
+
+try:
+ import numba
+ _has_numba = True
+except ImportError:
+ numba = None
+ _has_numba = False
+
+try:
+ from pyqtgraph.widgets.RawImageWidget import RawImageGLWidget
+except ImportError:
+ RawImageGLWidget = None
+
+parser = argparse.ArgumentParser(description="Benchmark for testing video performance")
+parser.add_argument('--cuda', default=False, action='store_true', help="Use CUDA to process on the GPU", dest="cuda")
+parser.add_argument('--dtype', default='uint8', choices=['uint8', 'uint16', 'float'], help="Image dtype (uint8, uint16, or float)")
+parser.add_argument('--frames', default=3, type=int, help="Number of image frames to generate (default=3)")
+parser.add_argument('--image-mode', default='mono', choices=['mono', 'rgb'], help="Image data mode (mono or rgb)", dest='image_mode')
+parser.add_argument('--levels', default=None, type=lambda s: tuple([float(x) for x in s.split(',')]), help="min,max levels to scale monochromatic image dynamic range, or rmin,rmax,gmin,gmax,bmin,bmax to scale rgb")
+parser.add_argument('--lut', default=False, action='store_true', help="Use color lookup table")
+parser.add_argument('--lut-alpha', default=False, action='store_true', help="Use alpha color lookup table", dest='lut_alpha')
+parser.add_argument('--size', default='512x512', type=lambda s: tuple([int(x) for x in s.split('x')]), help="WxH image dimensions default='512x512'")
+args = parser.parse_args(sys.argv[1:])
+
+if RawImageGLWidget is not None:
+ # don't limit frame rate to vsync
+ sfmt = QtGui.QSurfaceFormat()
+ sfmt.setSwapInterval(0)
+ QtGui.QSurfaceFormat.setDefaultFormat(sfmt)
+
+app = pg.mkQApp("Video Speed Test Example")
+
+win = QtGui.QMainWindow()
+win.setWindowTitle('pyqtgraph example: VideoSpeedTest')
+ui = ui_template.Ui_MainWindow()
+ui.setupUi(win)
+win.show()
+
+if RawImageGLWidget is None:
+ ui.rawGLRadio.setEnabled(False)
+ ui.rawGLRadio.setText(ui.rawGLRadio.text() + " (OpenGL not available)")
+else:
+ ui.rawGLImg = RawImageGLWidget()
+ ui.stack.addWidget(ui.rawGLImg)
+
+# read in CLI args
+ui.cudaCheck.setChecked(args.cuda and _has_cupy)
+ui.cudaCheck.setEnabled(_has_cupy)
+ui.numbaCheck.setChecked(_has_numba and pg.getConfigOption("useNumba"))
+ui.numbaCheck.setEnabled(_has_numba)
+ui.framesSpin.setValue(args.frames)
+ui.widthSpin.setValue(args.size[0])
+ui.heightSpin.setValue(args.size[1])
+ui.dtypeCombo.setCurrentText(args.dtype)
+ui.rgbCheck.setChecked(args.image_mode=='rgb')
+ui.maxSpin1.setOpts(value=255, step=1)
+ui.minSpin1.setOpts(value=0, step=1)
+levelSpins = [ui.minSpin1, ui.maxSpin1, ui.minSpin2, ui.maxSpin2, ui.minSpin3, ui.maxSpin3]
+if args.cuda and _has_cupy:
+ xp = cp
+else:
+ xp = np
+if args.levels is None:
+ ui.scaleCheck.setChecked(False)
+ ui.rgbLevelsCheck.setChecked(False)
+else:
+ ui.scaleCheck.setChecked(True)
+ if len(args.levels) == 2:
+ ui.rgbLevelsCheck.setChecked(False)
+ ui.minSpin1.setValue(args.levels[0])
+ ui.maxSpin1.setValue(args.levels[1])
+ elif len(args.levels) == 6:
+ ui.rgbLevelsCheck.setChecked(True)
+ for spin,val in zip(levelSpins, args.levels):
+ spin.setValue(val)
+ else:
+ raise ValueError("levels argument must be 2 or 6 comma-separated values (got %r)" % (args.levels,))
+ui.lutCheck.setChecked(args.lut)
+ui.alphaCheck.setChecked(args.lut_alpha)
+
+
+#ui.graphicsView.useOpenGL() ## buggy, but you can try it if you need extra speed.
+
+vb = pg.ViewBox()
+ui.graphicsView.setCentralItem(vb)
+vb.setAspectLocked()
+pg_img = pg.ImageItem()
+vb.addItem(pg_img)
+
+
+cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
+success, image = cap.read()
+assert success, 'Camera Failed to load image'
+vidWidth, vidHeight, vidNumColorChannels = image.shape
+
+
+
+
+LUT = None
+def updateLUT():
+ global LUT, ui
+ dtype = ui.dtypeCombo.currentText()
+ if dtype == 'uint8':
+ n = 256
+ else:
+ n = 4096
+ LUT = ui.gradient.getLookupTable(n, alpha=ui.alphaCheck.isChecked())
+ if _has_cupy and xp == cp:
+ LUT = cp.asarray(LUT)
+ui.gradient.sigGradientChanged.connect(updateLUT)
+updateLUT()
+
+ui.alphaCheck.toggled.connect(updateLUT)
+
+def updateScale():
+ global ui, levelSpins
+ if ui.rgbLevelsCheck.isChecked():
+ for s in levelSpins[2:]:
+ s.setEnabled(True)
+ else:
+ for s in levelSpins[2:]:
+ s.setEnabled(False)
+
+updateScale()
+
+ui.rgbLevelsCheck.toggled.connect(updateScale)
+
+cache = {}
+def mkData():
+ with pg.BusyCursor():
+ global data, cache, ui, xp
+ frames = ui.framesSpin.value()
+ width = ui.widthSpin.value()
+ height = ui.heightSpin.value()
+ cacheKey = (ui.dtypeCombo.currentText(), ui.rgbCheck.isChecked(), frames, width, height)
+ if cacheKey not in cache:
+ if cacheKey[0] == 'uint8':
+ dt = xp.uint8
+ loc = 128
+ scale = 64
+ mx = 255
+ elif cacheKey[0] == 'uint16':
+ dt = xp.uint16
+ loc = 4096
+ scale = 1024
+ mx = 2**16 - 1
+ elif cacheKey[0] == 'float':
+ dt = xp.float32
+ loc = 1.0
+ scale = 0.1
+ mx = 1.0
+ else:
+ raise ValueError(f"unable to handle dtype: {cacheKey[0]}")
+
+ chan_shape = (height, width)
+ if ui.rgbCheck.isChecked():
+ frame_shape = chan_shape + (3,)
+ else:
+ frame_shape = chan_shape
+ data = xp.empty((frames,) + frame_shape, dtype=dt)
+ view = data.reshape((-1,) + chan_shape)
+ for idx in range(view.shape[0]):
+ subdata = xp.random.normal(loc=loc, scale=scale, size=chan_shape)
+ # note: gaussian filtering has been removed as it slows down array
+ # creation greatly.
+ if cacheKey[0] != 'float':
+ xp.clip(subdata, 0, mx, out=subdata)
+ view[idx] = subdata
+
+ data[:, 10:50, 10] = mx
+ data[:, 48, 9:12] = mx
+ data[:, 47, 8:13] = mx
+ cache = {cacheKey: data} # clear to save memory (but keep one to prevent unnecessary regeneration)
+
+ data = cache[cacheKey]
+ updateLUT()
+ updateSize()
+
+def updateSize():
+ global ui, vb
+ frames = ui.framesSpin.value()
+ width = ui.widthSpin.value()
+ height = ui.heightSpin.value()
+ dtype = xp.dtype(str(ui.dtypeCombo.currentText()))
+ rgb = 3 if ui.rgbCheck.isChecked() else 1
+ ui.sizeLabel.setText('%d MB' % (frames * width * height * rgb * dtype.itemsize / 1e6))
+ vb.setRange(QtCore.QRectF(0, 0, width, height))
+
+
+def noticeCudaCheck():
+ global xp, cache
+ cache = {}
+ if ui.cudaCheck.isChecked():
+ if _has_cupy:
+ xp = cp
+ else:
+ xp = np
+ ui.cudaCheck.setChecked(False)
+ else:
+ xp = np
+ mkData()
+
+
+def noticeNumbaCheck():
+ pg.setConfigOption('useNumba', _has_numba and ui.numbaCheck.isChecked())
+
+
+mkData()
+
+
+ui.dtypeCombo.currentIndexChanged.connect(mkData)
+ui.rgbCheck.toggled.connect(mkData)
+ui.widthSpin.editingFinished.connect(mkData)
+ui.heightSpin.editingFinished.connect(mkData)
+ui.framesSpin.editingFinished.connect(mkData)
+
+ui.widthSpin.valueChanged.connect(updateSize)
+ui.heightSpin.valueChanged.connect(updateSize)
+ui.framesSpin.valueChanged.connect(updateSize)
+ui.cudaCheck.toggled.connect(noticeCudaCheck)
+ui.numbaCheck.toggled.connect(noticeNumbaCheck)
+
+
+ptr = 0
+lastTime = perf_counter()
+fps = None
+def update():
+ global ui, ptr, lastTime, fps, LUT, pg_img
+ if ui.lutCheck.isChecked():
+ useLut = LUT
+ else:
+ useLut = None
+
+ downsample = ui.downsampleCheck.isChecked()
+
+ if ui.scaleCheck.isChecked():
+ if ui.rgbLevelsCheck.isChecked():
+ useScale = [
+ [ui.minSpin1.value(), ui.maxSpin1.value()],
+ [ui.minSpin2.value(), ui.maxSpin2.value()],
+ [ui.minSpin3.value(), ui.maxSpin3.value()]]
+ else:
+ useScale = [ui.minSpin1.value(), ui.maxSpin1.value()]
+ else:
+ useScale = None
+
+ #read image from camera
+ success, image = cap.read()
+ assert success, 'Camera Failed to load image'
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #convert image from BGR to RGB color format
+
+ if ui.rawRadio.isChecked():
+ ui.rawImg.setImage(image, lut=useLut, levels=useScale)
+ ui.stack.setCurrentIndex(1)
+ elif ui.rawGLRadio.isChecked():
+ ui.rawGLImg.setImage(image, lut=useLut, levels=useScale)
+ ui.stack.setCurrentIndex(2)
+ else:
+ pg_img.setImage(cv2.rotate(image, cv2.ROTATE_180), autoLevels=False, levels=useScale, lut=useLut, autoDownsample=downsample)
+ ui.stack.setCurrentIndex(0)
+ #img.setImage(data[ptr%data.shape[0]], autoRange=False)
+
+ ptr += 1
+ now = perf_counter()
+ dt = now - lastTime
+ lastTime = now
+ if fps is None:
+ fps = 1.0/dt
+ else:
+ s = np.clip(dt*3., 0, 1)
+ fps = fps * (1-s) + (1.0/dt) * s
+ ui.fpsLabel.setText('%0.2f fps' % fps)
+ app.processEvents() ## force complete redraw for every plot
+timer = QtCore.QTimer()
+timer.timeout.connect(update)
+timer.start(0)
+
+if __name__ == '__main__':
+ pg.exec()
diff --git a/freemocap/dev_scratchpad/dev_alpha/scratch/jsm_cam_VideoSpeedTest_minimal.py b/freemocap/dev_scratchpad/dev_alpha/scratch/jsm_cam_VideoSpeedTest_minimal.py
new file mode 100644
index 00000000..94000f98
--- /dev/null
+++ b/freemocap/dev_scratchpad/dev_alpha/scratch/jsm_cam_VideoSpeedTest_minimal.py
@@ -0,0 +1,97 @@
+#jsm - 2021-Oct-23 - based on pyqtgrph.example VideoSpeedTest (gutted to simplest form)
+
+import sys
+
+import numpy as np
+
+import pyqtgraph as pg
+from pyqtgraph.Qt import QtGui, QtCore, QT_LIB
+from time import perf_counter
+
+import cv2
+
+pg.setConfigOption('imageAxisOrder', 'row-major')
+
+import importlib
+ui_template = importlib.import_module(f'VideoTemplate_{QT_LIB.lower()}')
+
+try:
+ from pyqtgraph.widgets.RawImageWidget import RawImageGLWidget
+except ImportError:
+ RawImageGLWidget = None
+
+
+
+if RawImageGLWidget is not None:
+ # don't limit frame rate to vsync
+ sfmt = QtGui.QSurfaceFormat()
+ sfmt.setSwapInterval(0)
+ QtGui.QSurfaceFormat.setDefaultFormat(sfmt)
+
+app = pg.mkQApp("Simple QT Webcam Viewer")
+
+win = QtGui.QMainWindow()
+win.setWindowTitle(' based on - pyqtgraph example: VideoSpeedTest')
+ui = ui_template.Ui_MainWindow()
+ui.setupUi(win)
+win.show()
+
+if RawImageGLWidget is None:
+ ui.rawGLRadio.setEnabled(False)
+ ui.rawGLRadio.setText(ui.rawGLRadio.text() + " (OpenGL not available)")
+else:
+ ui.rawGLImg = RawImageGLWidget()
+ ui.stack.addWidget(ui.rawGLImg)
+
+vb = pg.ViewBox()
+ui.graphicsView.setCentralItem(vb)
+vb.setAspectLocked()
+pg_img = pg.ImageItem()
+vb.addItem(pg_img)
+
+
+cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
+success, image = cap.read()
+assert success, 'Camera Failed to load image'
+vidWidth, vidHeight, vidNumColorChannels = image.shape
+
+
+
+ptr = 0
+lastTime = perf_counter()
+fps = None
+def update():
+ global ui, lastTime, fps, pg_img
+
+ #read image from camera
+ success, image = cap.read()
+ assert success, 'Camera Failed to load image'
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #convert image from BGR to RGB color format
+
+ if ui.rawRadio.isChecked():
+ ui.rawImg.setImage(image)
+ ui.stack.setCurrentIndex(1)
+ elif ui.rawGLRadio.isChecked():
+ ui.rawGLImg.setImage(image)
+ ui.stack.setCurrentIndex(2)
+ else:
+ pg_img.setImage(cv2.rotate(image, cv2.ROTATE_180))
+ ui.stack.setCurrentIndex(0)
+
+
+ now = perf_counter()
+ dt = now - lastTime
+ lastTime = now
+ if fps is None:
+ fps = 1.0/dt
+ else:
+ s = np.clip(dt*3., 0, 1)
+ fps = fps * (1-s) + (1.0/dt) * s
+ ui.fpsLabel.setText('%0.2f fps' % fps)
+ app.processEvents() ## force complete redraw for every plot
+timer = QtCore.QTimer()
+timer.timeout.connect(update)
+timer.start(0)
+
+if __name__ == '__main__':
+ pg.exec()