Free Motion Capture for Everyone πβ¨
TypeScript
eod commit - added timestamp line plots to viz gui (hist not working)
Jon4dbd299311af
diff --git a/src/cameras/capture/opencv_camera/opencv_camera.py b/src/cameras/capture/opencv_camera/opencv_camera.pyindex 39d8e820..f7240b48 100644--- a/src/cameras/capture/opencv_camera/opencv_camera.py+++ b/src/cameras/capture/opencv_camera/opencv_camera.py@@ -22,6 +22,14 @@ class OpenCVCamera:self._name = f"Camera_ {self._config.webcam_id}"self._opencv_video_capture_object: cv2.VideoCapture = Noneself._running_thread: CameraStreamThreadHandler = None+ self._new_frame = False++ @property+ def new_frame(self):+ """+ can be called to determine if the frame returned from `self.latest_frame` is new or if it has been called before+ """+ return self._new_frame@propertydef name(self):@@ -49,6 +57,7 @@ class OpenCVCamera:@propertydef latest_frame(self):+ self._new_frame = Falsereturn self._running_thread.latest_frame@property@@ -135,7 +144,7 @@ class OpenCVCamera:def get_next_frame(self):timestamp_ns_pre_grab = time.time_ns()- # Why grab not read? see ->+ # Why `grab()` not `read()`? see -># https://stackoverflow.com/questions/57716962/difference-between-video-capture-read-and# -grabif not self._opencv_video_capture_object.grab():@@ -145,6 +154,7 @@ class OpenCVCamera:timestamp_ns = (timestamp_ns_pre_grab + timestamp_ns_post_grab) / 2success, image = self._opencv_video_capture_object.retrieve()+ self._new_frame = successreturn FramePayload(success, image, timestamp_ns)def stop_frame_capture(self):diff --git a/src/core_processor/session/session_pipeline_orchestrator.py b/src/core_processor/session/session_pipeline_orchestrator.pyindex 563521e5..bd8f85da 100644--- a/src/core_processor/session/session_pipeline_orchestrator.py+++ b/src/core_processor/session/session_pipeline_orchestrator.py@@ -4,6 +4,7 @@ import tracebackfrom pathlib import Pathimport cv2+import numpy as npfrom src.cameras.multicam_manager.cv_camera_manager import OpenCVCameraManagerfrom src.cameras.persistence.video_writer.save_options import SaveOptions@@ -14,18 +15,19 @@ from src.qt_visualizer_and_gui.qt_visualizer_and_gui import QTVisualizerAndGuilogger = logging.getLogger(__name__)+def get_canonical_time_str():return time.strftime("%m-%d-%Y-%H_%M_%S")+class SessionPipelineOrchestrator:def __init__(self):- self._session_start_time = time.time()- self._session_id = 'session_'+time.strftime("%m-%d-%Y-%H_%M_%S")+ self._session_start_time = time.time_ns()+ self._session_id = 'session_' + time.strftime("%m-%d-%Y-%H_%M_%S")self._visualizer_gui = QTVisualizerAndGui()self._open_cv_camera_manager = OpenCVCameraManager(session_id=self._session_id)self._camera_calibrator = CameraCalibrator()-async def process_by_cam_id(self, webcam_id: str, cb):with self._open_cv_camera_manager.start_capture_session_single_cam(webcam_id=webcam_id,@@ -67,8 +69,8 @@ class SessionPipelineOrchestrator:def run(self,show_camera_views_in_windows=True,- show_camera_views_in_gui=True,- calibrate_cameras = True,+ show_visualizer_gui=True,+ calibrate_cameras=True,save_video=True,):"""@@ -86,14 +88,25 @@ class SessionPipelineOrchestrator:try:should_continue = Truewhile should_continue:+ each_camera_timestamp_on_this_frame_dict = {}for this_response in cam_and_writer_response_list:this_open_cv_camera = this_response.cv_camthis_video_writer_object = this_response.writer+ if self._visualizer_gui.pause_button_pressed:+ continue++ new_frame = this_open_cv_camera.new_frame+ if not new_frame:+ continue+this_webcam_id_as_str = this_open_cv_camera.webcam_id_as_strthis_cam_latest_frame = this_open_cv_camera.latest_frame+ each_camera_timestamp_on_this_frame_dict[+ this_webcam_id_as_str] = this_cam_latest_frame.timestamp+if this_cam_latest_frame.image is None:continue@@ -112,8 +125,21 @@ class SessionPipelineOrchestrator:this_webcam_id_as_str, image_to_display, fps_manager)- if show_camera_views_in_gui:+ if show_visualizer_gui:self._visualizer_gui.update_camera_view_image(this_webcam_id_as_str, image_to_display)+ self._visualizer_gui.update_timestamp_plot(this_webcam_id_as_str,+ this_cam_latest_frame.timestamp - self._session_start_time)+ if show_visualizer_gui and new_frame:+ cam0_timestamp = np.nan+ try:+ cam0_timestamp = each_camera_timestamp_on_this_frame_dict['0']+ except:+ logger.debug('no timestamp logged for camera 0')++ for this_cam_id, this_cam_timestamp in each_camera_timestamp_on_this_frame_dict.items():+ self._visualizer_gui.update_timestamp_difference_plot(this_cam_id,+ this_cam_timestamp - cam0_timestamp - self._session_start_time)+except:logger.error("Printing traceback")traceback.print_exc()@@ -139,8 +165,6 @@ class SessionPipelineOrchestrator:self._visualizer_gui.close()--if __name__ == "__main__":print('start main')diff --git a/src/qt_visualizer_and_gui/qt_visualizer_and_gui.py b/src/qt_visualizer_and_gui/qt_visualizer_and_gui.pyindex f67095ff..a153169d 100644--- a/src/qt_visualizer_and_gui/qt_visualizer_and_gui.py+++ b/src/qt_visualizer_and_gui/qt_visualizer_and_gui.py@@ -1,6 +1,9 @@import logging+import time+from typing import Dictimport cv2+import numpy as npimport pyqtgraph as pgfrom pyqtgraph.dockarea.Dock import Dockfrom pyqtgraph.dockarea.DockArea import DockArea@@ -8,19 +11,80 @@ from pyqtgraph.Qt import QtWidgetslogger = logging.getLogger(__name__)+class QTVisualizerAndGui:def __init__(self):# https://pyqtgraph.readthedocs.io/en/latest/config_options.htmlpg.setConfigOptions(imageAxisOrder='row-major')self.pyqtgraph_app = pg.mkQApp("FreeMoCap! :O ")+self._dict_of_camera_image_item_widgets = {}+ self._dict_of_timestamp_line_plots = {}+ self._dict_of_cam_timestamps = {}+ self._dict_of_timestamp_difference_line_plots = {}+ self._dict_of_cam_timestamp_differences = {}+ self._dict_of_timestamp_difference_histograms = {}++ self._is_paused = False++ @property+ def pause_button_pressed(self):+ return self._is_paused++ def close(self):+ self._main_window_widget.close()def setup_and_launch(self, cam_and_writer_response_list):- print('beep')+ logger.info('setting up QT Visualizer and GUI')self._setup_main_window()- self._setup_camera_views(cam_and_writer_response_list)- self._display_app_window()- print('boop')+ self._setup_control_panel()+ self._setup_camera_views_dock(cam_and_writer_response_list)+ self._setup_timestamp_plot(cam_and_writer_response_list)+ self._setup_time_difference_from_cam0_line_plot(cam_and_writer_response_list)+ self._setup_time_difference_from_cam0_histogram_plot(cam_and_writer_response_list)+ logger.info('launching QT Visualizer and GUI window')+ self._main_window_widget.show()++ def update_camera_view_image(self, webcam_id, image_to_display):+ try:+ camera_image_item_widget = self._dict_of_camera_image_item_widgets[webcam_id]+ except Exception as e:+ logger.warning(f'Could not find ViewBoxWidget for camera {webcam_id}')+ raise e+ camera_image_item_widget.setImage(cv2.cvtColor(image_to_display, cv2.COLOR_BGR2RGB))++ def update_timestamp_plot(self, webcam_id, new_timestamp):+ try:+ timestamp_line_plot = self._dict_of_timestamp_line_plots[webcam_id]+ self._dict_of_cam_timestamps[webcam_id] = np.append(self._dict_of_cam_timestamps[webcam_id], new_timestamp)+ except Exception as e:+ logger.warning(f'Could not find timestamp line plot widget for camera {webcam_id}')+ raise e++ timestamp_line_plot.setData(self._dict_of_cam_timestamps[webcam_id])++ def update_timestamp_difference_plot(self, webcam_id, new_timestamp_difference):+ try:+ self._dict_of_cam_timestamp_differences[webcam_id] = np.append(+ self._dict_of_cam_timestamp_differences[webcam_id],+ new_timestamp_difference)+ self._dict_of_timestamp_difference_line_plots[webcam_id].setData(+ self._dict_of_cam_timestamp_differences[webcam_id])+ self._update_timestamp_difference_histogram(webcam_id)+ except Exception as e:+ logger.warning(f'Could not find timestamp difference line plot widget for camera {webcam_id}')+ raise e++ def _update_timestamp_difference_histogram(self, webcam_id):+ counts, bin_edges = np.histogram(self._dict_of_cam_timestamp_differences[webcam_id],+ bins=np.linspace(-5, 5, 500))+ try:+ self._dict_of_timestamp_difference_histograms[webcam_id].setData(+ x=bin_edges,+ y=counts)+ except Exception as e:+ logger.warning(f'Could not find timestamp difference line plot widget for camera {webcam_id}')+ raise edef _setup_main_window(self, window_width: int = 1000, window_height: int = 1000):"""@@ -34,27 +98,32 @@ class QTVisualizerAndGui:self._main_window_widget.setCentralWidget(self._main_dock_area)self._main_window_widget.setWindowTitle('Main Window ;D')- self._camera_graphics_layout_window = pg.GraphicsLayoutWidget()- self._camera_views_dock = Dock('Camera Views')- self._camera_views_dock.addWidget(self._camera_graphics_layout_window)- self._main_dock_area.addDock(self._camera_views_dock, position='top')+ def _setup_control_panel(self):+ self._control_panel_dock = Dock('Control Panel', size=(1, 1))+ control_panel_layout_widget = pg.LayoutWidget()+ self._control_panel_dock.addWidget(control_panel_layout_widget)- def _display_app_window(self):- self._main_window_widget.show()+ label = QtWidgets.QLabel("Blah Blah Blah put words here ")+ control_panel_layout_widget.addWidget(label, row=0, col=0)- def close(self):- self._main_window_widget.close()+ self._pause_button = QtWidgets.QPushButton('Pause Frame Loop (Don\'t press this lol)')+ self._pause_button.setEnabled(True)+ self._pause_button.clicked.connect(self._pause)+ control_panel_layout_widget.addWidget(self._pause_button, row=1, col=0)- def update_camera_view_image(self, webcam_id, image_to_display):- try:- camera_image_item_widget = self._dict_of_camera_image_item_widgets[webcam_id]- except Exception as e:- logger.warning(f'Could not find ViewBoxWidget for camera {webcam_id}')- raise e- camera_image_item_widget.setImage(cv2.cvtColor(image_to_display, cv2.COLOR_BGR2RGB))+ self._play_button = QtWidgets.QPushButton('Resume Frame Loop')+ self._play_button.setEnabled(False)+ self._play_button.clicked.connect(self._play)+ control_panel_layout_widget.addWidget(self._play_button, row=2, col=0)+ self._main_dock_area.addDock(self._control_panel_dock, position='left')++ def _setup_camera_views_dock(self, cam_and_writer_response_list):+ self._camera_graphics_layout_window = pg.GraphicsLayoutWidget()+ self._camera_views_dock = Dock('Camera Views')+ self._camera_views_dock.addWidget(self._camera_graphics_layout_window)+ self._main_dock_area.addDock(self._camera_views_dock, 'right', self._control_panel_dock)- def _setup_camera_views(self, cam_and_writer_response_list):for this_response in cam_and_writer_response_list:this_webcam_id = this_response.cv_cam.webcam_id_as_strself._dict_of_camera_image_item_widgets[this_webcam_id] = self._create_camera_view_widget(this_webcam_id)@@ -65,3 +134,82 @@ class QTVisualizerAndGui:camera_view_box_widget.addItem(camera_image_item)self._camera_graphics_layout_window.addItem(camera_view_box_widget)return camera_image_item++ def _setup_timestamp_plot(self, cam_and_writer_response_list):+ # create widget/dock for reprojection error subplot+ timestamp_plot_widget = pg.PlotWidget(title="Timestamp vs Frame#")+ timestamp_plot_widget.setLabel('left', "timestamp", units='seconds')+ timestamp_plot_widget.setLabel('bottom', "Frame#", units='Frame')+ timestamp_plot_widget.addLegend()++ for this_cam_num, this_response in enumerate(cam_and_writer_response_list):+ num_cams = len(cam_and_writer_response_list)+ this_webcam_id = this_response.cv_cam.webcam_id_as_str+ this_timestamp_plot_line = timestamp_plot_widget.plot(np.empty(0),+ pen=(this_cam_num, num_cams),+ name="camera " + this_webcam_id)++ self._dict_of_timestamp_line_plots[this_webcam_id] = this_timestamp_plot_line+ self._dict_of_cam_timestamps[this_webcam_id] = np.ndarray(0)++ self._timestamp_plot_dock = Dock("Camera Timestamps")+ self._timestamp_plot_dock.addWidget(timestamp_plot_widget)+ self._main_dock_area.addDock(self._timestamp_plot_dock, 'bottom')++ def _setup_time_difference_from_cam0_line_plot(self, cam_and_writer_response_list):+ # create widget/dock for reprojection error subplot+ timestamp_difference_plot_widget = pg.PlotWidget(title="Timestamp difference from Camera0 on each frame")+ timestamp_difference_plot_widget.setLabel('left', "this_camera timestamp - cam0 timestamp", units='seconds')+ timestamp_difference_plot_widget.setLabel('bottom', "Frame#", units='Frame')+ timestamp_difference_plot_widget.addLegend()++ for this_cam_num, this_response in enumerate(cam_and_writer_response_list):+ num_cams = len(cam_and_writer_response_list)+ this_webcam_id = this_response.cv_cam.webcam_id_as_str+ this_plot_line = timestamp_difference_plot_widget.plot(np.empty(0),+ pen=(this_cam_num, num_cams),+ name="camera " + this_webcam_id)++ self._dict_of_timestamp_difference_line_plots[this_webcam_id] = this_plot_line+ self._dict_of_cam_timestamp_differences[this_webcam_id] = np.ndarray(0)++ self._timestamp_difference_plot_dock = Dock("Camera Timestamps")+ self._timestamp_difference_plot_dock.addWidget(timestamp_difference_plot_widget)+ self._main_dock_area.addDock(self._timestamp_difference_plot_dock, 'right', self._timestamp_plot_dock)++ def _setup_time_difference_from_cam0_histogram_plot(self, cam_and_writer_response_list):+ timestamp_difference_histogram_plot_widget = pg.PlotWidget(+ title="Timestamp difference from Camera0 on each frame")+ timestamp_difference_histogram_plot_widget.setLabel('left', "Proportion")+ timestamp_difference_histogram_plot_widget.setLabel('bottom', "milliseconds")+ timestamp_difference_histogram_plot_widget.addLegend()++ for this_cam_num, this_response in enumerate(cam_and_writer_response_list):+ num_cams = len(cam_and_writer_response_list)+ this_webcam_id = this_response.cv_cam.webcam_id_as_str+ this_histogram_plot_item = timestamp_difference_histogram_plot_widget.plot(np.empty(0),+ np.empty(0),+ stepMode="center",+ fillLevel=0,+ fillOutline=True,+ brush=pg.mkBrush(color=(+ this_cam_num, num_cams),+ alpha=.5),+ name="camera " + this_webcam_id)++ self._dict_of_timestamp_difference_histograms[this_webcam_id] = this_histogram_plot_item++ timestamp_plot_dock = Dock("Camera Timestamp Difference histogram")+ timestamp_plot_dock.addWidget(timestamp_difference_histogram_plot_widget)+ self._main_dock_area.addDock(timestamp_plot_dock, 'right', self._timestamp_difference_plot_dock)++ def _pause(self):+ self._is_paused = True+ self._play_button.setEnabled(True)+ self._play_button.setText("I warned you!")+ self._pause_button.setEnabled(False)++ def _play(self):+ self._is_paused = False+ self._play_button.setEnabled(False)+ self._pause_button.setEnabled(True)