Free Motion Capture for Everyone πβ¨
TypeScript
create timestamp diagnostic plot
Jon4aa60dd3e2d0
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest.pyindex aeb4ab1d..32723a88 100644--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest.py+++ b/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest.py@@ -303,7 +303,7 @@ def update():else:s = np.clip(dt*3., 0, 1)fps = fps * (1-s) + (1.0/dt) * s- ui.fpsLabel.setText('%0.2f fps' % fps)+ ui.fpsLabel.setText('%0.2f timestamp_manager' % fps)app.processEvents() ## force complete redraw for every plottimer = QtCore.QTimer()timer.timeout.connect(update)diff --git a/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest_minimal.py b/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest_minimal.pyindex 302e0842..c043dbb3 100644--- a/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest_minimal.py+++ b/freemocap/dev_scratchpad/dev_alpha_old/scratch/jsm_cam_VideoSpeedTest_minimal.py@@ -95,7 +95,7 @@ def update():else:s = np.clip(dt*3., 0, 1)fps = fps * (1-s) + (1.0/dt) * s- ui.fpsLabel.setText('%0.2f fps' % fps)+ ui.fpsLabel.setText('%0.2f timestamp_manager' % fps)app.processEvents() ## force complete redraw for every plottimer = QtCore.QTimer()timer.timeout.connect(update)diff --git a/src/cameras/multicam_manager/cv_camera_manager.py b/src/cameras/multicam_manager/cv_camera_manager.pyindex d0e7732d..a9cd6703 100644--- a/src/cameras/multicam_manager/cv_camera_manager.py+++ b/src/cameras/multicam_manager/cv_camera_manager.py@@ -12,7 +12,7 @@ from src.cameras.capture.opencv_camera.opencv_camera import OpenCVCamerafrom src.cameras.detection.cam_singleton import get_or_create_camsfrom src.cameras.persistence.video_writer.video_recorder import VideoRecorderfrom src.config.webcam_config import WebcamConfig-from src.core_processor.fps.timestamp_manager import TimestampManager+from src.core_processor.timestamp_manager.timestamp_manager import TimestampManagerfrom src.pipelines.session_pipeline.data_classes.multi_frame_payload import MultiFramePayloadlogger = logging.getLogger(__name__)@@ -51,7 +51,7 @@ class OpenCVCameraManager:return [cam_id.webcam_id for cam_id in get_or_create_cams().cameras_found_list]@property- def latest_multi_frame(self) -> Union[MultiFramePayload,None]:+ def latest_multi_frame(self) -> Union[MultiFramePayload, None]:if not self.new_multi_frame_ready():logging.error("a multi_frame was requested before it was ready!")raise Exception@@ -64,19 +64,20 @@ class OpenCVCameraManager:self._timestamp_manager.log_new_multi_frame_timestamp_ns(time.perf_counter_ns())if not self._timestamp_manager.verify_multi_frame_is_synchronized(this_multi_frame_dict,- self._expected_framerate):+ self._expected_framerate):m_f_interval = self._timestamp_manager.latest_multi_frame_intervalm_f_number = self._timestamp_manager.multi_frame_timestamp_logger.number_of_frames- logger.error(f"Multi frame is not synchronized!! Skipping this one - multi_frame_frame_number|interval: {m_f_number}|{m_f_interval:.3f}")+ logger.error(+ f"Multi frame is not synchronized!! Skipping this one - multi_frame_frame_number|interval: {m_f_number}|{m_f_interval:.3f}")# raise Exceptionreturn Nonereturn MultiFramePayload(frames_dict=this_multi_frame_dict,- multi_frame_number=self._timestamp_manager.multi_frame_timestamp_logger.number_of_frames,- intra_frame_interval=self._timestamp_manager.latest_multi_frame_interval,- each_frame_timestamp=self._timestamp_manager.latest_multi_frame_timestamp_list,- multi_frame_timestamp=self._timestamp_manager.multi_frame_timestamp_logger.latest_timestamp,- )+ multi_frame_number=self._timestamp_manager.multi_frame_timestamp_logger.number_of_frames,+ intra_frame_interval=self._timestamp_manager.latest_multi_frame_interval,+ each_frame_timestamp=self._timestamp_manager.latest_multi_frame_timestamp_list,+ multi_frame_timestamp=self._timestamp_manager.multi_frame_timestamp_logger.latest_timestamp,+ )def new_multi_frame_ready(self):"""cycle through connected cameras and return false if one isn't read yet@@ -147,7 +148,8 @@ class OpenCVCameraManager:def _initialize_timestamp_logger(self):self._session_start_time_unix_ns = time.time_ns()self._session_start_time_perf_counter_ns = time.perf_counter_ns()- self._timestamp_manager = TimestampManager(self.available_webcam_ids,+ self._timestamp_manager = TimestampManager(self._session_id,+ self.available_webcam_ids,self._session_start_time_unix_ns,self._session_start_time_perf_counter_ns)diff --git a/src/core_processor/experiments/threading_single_cam.py b/src/core_processor/experiments/threading_single_cam.pyindex f9eca6c2..92dda808 100644--- a/src/core_processor/experiments/threading_single_cam.py+++ b/src/core_processor/experiments/threading_single_cam.py@@ -92,7 +92,7 @@ end = time.time()webcam_stream1.stop() # stop the webcam streamwebcam_stream2.stop() # stop the webcam stream-# printing time elapsed and fps+# printing time elapsed and timestamp_managerelapsed = end - startfps = num_frames_processed / elapsedprint(diff --git a/src/core_processor/show_cam_window.py b/src/core_processor/show_cam_window.pyindex 779b0ab8..c931721d 100644--- a/src/core_processor/show_cam_window.py+++ b/src/core_processor/show_cam_window.py@@ -3,7 +3,7 @@ import loggingimport cv2import numpy as np-from src.core_processor.fps.timestamp_manager import TimestampManager+from src.core_processor.timestamp_manager.timestamp_manager import TimestampManagerfrom src.core_processor.utils.image_fps_writer import write_fps_to_imagelogger = logging.getLogger(__name__)diff --git a/src/core_processor/fps/timestamp_manager.py b/src/core_processor/timestamp_manager/timestamp_manager.pysimilarity index 63%rename from src/core_processor/fps/timestamp_manager.pyrename to src/core_processor/timestamp_manager/timestamp_manager.pyindex e2d3445e..fd2edd70 100644--- a/src/core_processor/fps/timestamp_manager.py+++ b/src/core_processor/timestamp_manager/timestamp_manager.py@@ -1,7 +1,12 @@import logging+from pathlib import Pathfrom typing import Dict, List, Unionimport numpy as np+from matplotlib import pyplot as plt+++from src.config.home_dir import get_session_folder_pathlogger = logging.getLogger(__name__)@@ -56,9 +61,11 @@ class TimestampLogger:class TimestampManager:def __init__(self,+ session_id:str,webcam_ids: List[str],session_start_time_unix_ns: int,_session_start_time_perf_counter_ns:int):+ self._session_id = session_idself._session_start_time_unix_ns = session_start_time_unix_ns #time.time_ns(), UNIX epoch time, nanosecondsself._session_start_time_perf_counter_ns = _session_start_time_perf_counter_ns #time.perf_counter_ns, arbitrary timebase, nanoseconds - corresponds to self.session_start_time_nsself._webcam_ids = webcam_ids@@ -69,6 +76,13 @@ class TimestampManager:self._multi_frame_timestamps_list = []self._multi_frame_interval_list = []+ @property+ def webcam_timestamp_loggers(self):+ return self._webcam_timestamp_loggers+ @property+ def number_of_cameras(self):+ return len(self._webcam_timestamp_loggers)+@propertydef multi_frame_timestamp_logger(self):return self._multi_frame_timestamp_logger@@ -150,3 +164,102 @@ class TimestampManager:return Falsereturn True++ def create_diagnostic_plots(self):+ """plot some diagnostics to assess quality of camera sync"""++ multi_frame_timestamp_list = self.multi_frame_timestamp_logger.timestamps_in_seconds_from_session_start+ multi_frame_interval_list = self.multi_frame_interval_list++ plt.ion()+ fig = plt.figure(figsize=(18, 10))+ max_frame_duration = 0.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 this_camera_id, this_camera_timestamp_logger in self.webcam_timestamp_loggers.items():+ this_camera_timestamps = this_camera_timestamp_logger.timestamps_in_seconds_from_session_start+ ax1.plot(this_camera_timestamps, label=f"Camera# {this_camera_id}")+ ax1.legend()+ ax2.plot(np.diff(this_camera_timestamps), ".")+ ax3.hist(+ np.diff(this_camera_timestamps),+ bins=np.arange(0, max_frame_duration, 0.0025),+ alpha=0.5,+ )++ ax4.plot(+ multi_frame_timestamp_list,+ color="darkslategrey",+ label=f"MultiFrame"+ )+ ax5.plot(+ np.diff(multi_frame_timestamp_list),+ ".",+ color="darkslategrey",+ label="Multi Frame Duration",+ )+ ax5.plot(+ multi_frame_interval_list, ".", color="orangered", label="Frame TimeSpan"+ )+ ax5.legend()+ ax6.hist(+ np.diff(multi_frame_timestamp_list),+ bins=np.arange(0, max_frame_duration, 0.0025),+ density=True,+ alpha=0.5,+ color="darkslategrey",+ label="Frame Duration",+ )+ ax6.hist(+ np.diff(multi_frame_interval_list),+ bins=np.arange(0, max_frame_duration, 0.0025),+ density=True,+ alpha=0.5,+ color="orangered",+ label="Frame Timespan",+ )+ ax5.legend()++ fig_save_path = Path(get_session_folder_path(self._session_id)) / "camera_timestamp_diagnostics.png"+ plt.savefig(str(fig_save_path))+ logger.info(f"Saving diagnostic figure to - {str(fig_save_path)}")+ plt.show()diff --git a/src/pipelines/calibration_pipeline/anipose_camera_calibration/anipose_camera_calibration.py b/src/pipelines/calibration_pipeline/anipose_camera_calibration/anipose_camera_calibration.pyindex d482e8aa..9a23e657 100644--- a/src/pipelines/calibration_pipeline/anipose_camera_calibration/anipose_camera_calibration.py+++ b/src/pipelines/calibration_pipeline/anipose_camera_calibration/anipose_camera_calibration.py@@ -36,7 +36,7 @@ class AniposeCameraCalibrator:def get_paths_and_whatnot(self):self.session_folder_path = Path(get_session_folder_path(self._session_id))- calibration_videos_folder = Path(get_calibration_videos_folder_path())+ calibration_videos_folder = Path(get_calibration_videos_folder_path(self._session_id))self._list_of_video_paths = [this_video_path for this_video_path incalibration_videos_folder.glob('*.mp4'.lower())]diff --git a/src/pipelines/calibration_pipeline/calibration_pipeline_orchestrator.py b/src/pipelines/calibration_pipeline/calibration_pipeline_orchestrator.pyindex f5acf0b4..70c73d22 100644--- a/src/pipelines/calibration_pipeline/calibration_pipeline_orchestrator.py+++ b/src/pipelines/calibration_pipeline/calibration_pipeline_orchestrator.py@@ -8,7 +8,7 @@ import cv2from src.cameras.multicam_manager.cv_camera_manager import OpenCVCameraManagerfrom src.config.home_dir import create_session_id, get_session_folder_path, get_freemocap_data_folder_path-from src.core_processor.fps.timestamp_manager import TimestampManager+from src.core_processor.timestamp_manager.timestamp_manager import TimestampManagerfrom src.core_processor.show_cam_window import show_cam_windowfrom src.core_processor.utils.image_fps_writer import write_fps_to_imagefrom src.pipelines.calibration_pipeline.anipose_camera_calibration import freemocap_aniposediff --git a/src/pipelines/calibration_pipeline/charuco_board_detection/charuco_board_detector.py b/src/pipelines/calibration_pipeline/charuco_board_detection/charuco_board_detector.pyindex 31f1c412..891e867b 100644--- a/src/pipelines/calibration_pipeline/charuco_board_detection/charuco_board_detector.py+++ b/src/pipelines/calibration_pipeline/charuco_board_detection/charuco_board_detector.py@@ -1,6 +1,8 @@import logging+from typing import Dictimport cv2+import numpy as npfrom src.cameras.capture.dataclasses.frame_payload import FramePayloadfrom src.pipelines.calibration_pipeline.charuco_board_detection.dataclasses.charuco_board_definition import CharucoBoardDataClass@@ -106,6 +108,25 @@ class CharucoBoardDetector:image_width=image_width,image_height=image_height)+ def format_charuco2d_data(self, this_multi_frame_charuco_data) -> Dict:++ number_of_tracked_points = this_multi_frame_charuco_data[+ 0].charuco_view_data.charuco_board_object.number_of_charuco_corners++ charuco2d_data_per_cam_dict = {}+ base_charuco_data_npy_with_nans_for_missing_data_xy = np.zeros((number_of_tracked_points, 2))+ base_charuco_data_npy_with_nans_for_missing_data_xy[:] = np.nan+ for this_cam_data in this_multi_frame_charuco_data:+ if this_cam_data.charuco_view_data.some_charuco_corners_found:+ this_frame_charuco_data_xy = base_charuco_data_npy_with_nans_for_missing_data_xy.copy()+ charuco_ids_in_this_frame_idx = this_cam_data.charuco_view_data.charuco_ids+ charuco_corners_in_this_frame_xy = this_cam_data.charuco_view_data.charuco_corners+ this_frame_charuco_data_xy[charuco_ids_in_this_frame_idx, :] = charuco_corners_in_this_frame_xy++ this_webcam_id = this_cam_data.raw_frame_payload.webcam_id+ charuco2d_data_per_cam_dict[this_webcam_id] = this_frame_charuco_data_xy++ return charuco2d_data_per_cam_dictif __name__ == "__main__":passdiff --git a/src/pipelines/session_pipeline/session_pipeline_orchestrator.py b/src/pipelines/session_pipeline/session_pipeline_orchestrator.pyindex 1ce30c3a..8561e602 100644--- a/src/pipelines/session_pipeline/session_pipeline_orchestrator.py+++ b/src/pipelines/session_pipeline/session_pipeline_orchestrator.py@@ -12,7 +12,7 @@ from src.cameras.persistence.video_writer.save_options_dataclass import SaveOptifrom src.config.data_paths import freemocap_data_pathfrom src.config.home_dir import create_session_id, get_session_folder_pathfrom src.core_processor.camera_calibration.camera_calibrator import CameraCalibrator-from src.core_processor.fps.timestamp_manager import TimestampManager+from src.core_processor.timestamp_manager.timestamp_manager import TimestampManagerfrom src.core_processor.mediapipe_skeleton_detector.mediapipe_skeleton_detector import MediaPipeSkeletonDetectorfrom src.core_processor.show_cam_window import show_cam_windowfrom src.core_processor.utils.image_fps_writer import write_fps_to_image@@ -59,9 +59,6 @@ class SessionPipelineOrchestrator:def session_folder_path(self):return freemocap_data_path / self._session_id- @property- def mediapipe_skeleton_detector(self):- return self._mediapipe_skeleton_detectorasync def process_by_cam_id(self, webcam_id: str, cb):with self._open_cv_camera_manager.start_capture_session_single_cam(@@ -123,16 +120,16 @@ class SessionPipelineOrchestrator:charuco_square_size=charuco_square_size,pin_camera_0_to_origin=pin_camera_0_to_origin)- def run_main_frame_loop(+ def record_new_session(self,show_visualizer_gui=True,show_camera_views_in_windows=False,- detect_mediapipe=False,- detect_charuco=False,):with self._open_cv_camera_manager.start_capture_session_all_cams() as connected_cameras_dict:+ self._number_of_cameras = len(connected_cameras_dict)+timestamp_manager = self._open_cv_camera_manager.timestamp_managertry:@@ -174,15 +171,6 @@ class SessionPipelineOrchestrator:# can handle large numbers of cameras, but will eventually fill up RAM and cause a crashthis_open_cv_camera.video_recorder.append_frame_payload_to_list(this_cam_latest_frame)- if detect_mediapipe:- image_to_display = self._mediapipe_skeleton_detector.detect_skeleton_in_image(- image_to_display)-- if detect_charuco:- charuco_frame_payload = self._charuco_board_detector.detect_charuco_board(- this_cam_latest_frame)- image_to_display = charuco_frame_payload.annotated_image-if show_camera_views_in_windows:should_continue = show_cam_window(this_webcam_id, image_to_display, timestamp_manager@@ -212,7 +200,6 @@ class SessionPipelineOrchestrator:traceback.print_exc()finally:for this_open_cv_camera in connected_cameras_dict.values():-this_open_cv_camera.video_recorder.save_frame_payload_list_to_disk()if show_camera_views_in_windows:@@ -222,6 +209,8 @@ class SessionPipelineOrchestrator:if show_visualizer_gui:self._visualizer_gui.close()+ timestamp_manager.create_diagnostic_plots()+def _reconstruct_3d_charuco(self, incoming_charuco_frame_data_per_camera_dict) -> \Union[None, Data3dSingleFramePayload]:@@ -258,25 +247,6 @@ class SessionPipelineOrchestrator:x = charuco_3d_data_payload.data3d_trackedPointNum_xyz[:, 0]return charuco_3d_data_payload- def format_charuco2d_data(self, this_multi_frame_charuco_data) -> Dict:-- number_of_tracked_points = this_multi_frame_charuco_data[- 0].charuco_view_data.charuco_board_object.number_of_charuco_corners-- charuco2d_data_per_cam_dict = {}- base_charuco_data_npy_with_nans_for_missing_data_xy = np.zeros((number_of_tracked_points, 2))- base_charuco_data_npy_with_nans_for_missing_data_xy[:] = np.nan- for this_cam_data in this_multi_frame_charuco_data:- if this_cam_data.charuco_view_data.some_charuco_corners_found:- this_frame_charuco_data_xy = base_charuco_data_npy_with_nans_for_missing_data_xy.copy()- charuco_ids_in_this_frame_idx = this_cam_data.charuco_view_data.charuco_ids- charuco_corners_in_this_frame_xy = this_cam_data.charuco_view_data.charuco_corners- this_frame_charuco_data_xy[charuco_ids_in_this_frame_idx, :] = charuco_corners_in_this_frame_xy-- this_webcam_id = this_cam_data.raw_frame_payload.webcam_id- charuco2d_data_per_cam_dict[this_webcam_id] = this_frame_charuco_data_xy-- return charuco2d_data_per_cam_dictdef _triangulate_2d_data(self, data2d_per_cam_dict: Dict,number_of_tracked_points: int) -> Data3dSingleFramePayload:@@ -306,10 +276,27 @@ class SessionPipelineOrchestrator:data3d_trackedPointNum_xyz=data3d_trackedPointNum_xyz,data3d_trackedPointNum_reprojectionError=data3d_trackedPointNum_reprojectionError, )- def mediapipe_track_skeletons(self):- self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY = self.mediapipe_skeleton_detector.process_session_folder(save_annotated_videos=True)- pass+ def mediapipe_track_skeletons_offline(self):+ self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY = self._mediapipe_skeleton_detector.process_session_folder(save_annotated_videos=True)++ def reconstruct3d_from_2d_data_offline(self):++ dataFlat_nCams_nTotalPoints_XY = self._mediapipe2d_numCams_numFrames_numTrackedPoints_XY.reshape(self._number_of_cameras, -1,+ 2) # reshape data to collapse across 'frames' so it becomes [numCams, numFrames*numPoints, XY]+ logger.info('Reconstructing 3d points...')+ data3d_flat = self._anipose_camera_calibration_object.triangulate(dataFlat_nCams_nTotalPoints_XY, progress=True)++ dataReprojerr_flat = self._anipose_camera_calibration_object.reprojection_error(data3d_flat,+ dataFlat_nCams_nTotalPoints_XY,+ mean=True)+ #+ # ##return:+ # data_fr_mar_xyz = data3d_flat.reshape(num_frames, num_img_points, 3)+ # dataReprojErr = dataReprojerr_flat.reshape(num_frames, num_img_points)+ #+ # return data_fr_mar_xyz, dataReprojErr+ #if __name__ == "__main__":print('running `session_pipeline_orchestrator` as `__main__')@@ -326,8 +313,9 @@ if __name__ == "__main__":charuco_square_size=length_of_one_edge_of_a_black_square_on_the_charuco_board_in_mm,pin_camera_0_to_origin=True)- this_session_orchestrator.run_main_frame_loop(show_camera_views_in_windows=False,- show_visualizer_gui=True,- )+ this_session_orchestrator.record_new_session()++ this_session_orchestrator.mediapipe_track_skeletons_offline()++ this_session_orchestrator.reconstruct3d_mediapipe_offline()- this_session_orchestrator.mediapipe_track_skeletons()diff --git a/src/pipelines/session_pipeline/timestamp_handler.py b/src/pipelines/session_pipeline/timestamp_handler.pydeleted file mode 100644index 98eae34f..00000000--- a/src/pipelines/session_pipeline/timestamp_handler.py+++ /dev/null@@ -1,22 +0,0 @@-import numpy as np---class TimestampLogger:- pass- # def __init__(self, _camera_id_list: list[str], camera0_id: str = '0'):- # self._camera0_id = camera0_id- # self._number_of_cameras = len(_camera_id_list)- # self._camera_timestamp_dict = {}- #- # for this_cam_id in _camera_id_list:- # self._camera_timestamp_dict[this_cam_id] = np.ndarray(0)- #- # def update(self, this_webcam_id, new_timestamp):- # self._camera_timestamp_dict[this_webcam_id] = np.append(self._camera_timestamp_dict[this_webcam_id],- # new_timestamp)- #- # timestamp_array_lengths = [this_timestamp_array.shape[0] for this_timestamp_array in self._camera_timestamp_dict.values()]- #- # if np.sum(np.diff(timestamp_array_lengths)) == 0: # if timestamp arrays are all the same length- # self._update_timestamp_differences_from_camera()- #diff --git a/src/qt_visualizer_and_gui/qt_visualizer_and_gui.py b/src/qt_visualizer_and_gui/qt_visualizer_and_gui.pyindex 3ecd64d6..dc1ba821 100644--- a/src/qt_visualizer_and_gui/qt_visualizer_and_gui.py+++ b/src/qt_visualizer_and_gui/qt_visualizer_and_gui.py@@ -10,7 +10,7 @@ from pyqtgraph.dockarea.Dock import Dockfrom pyqtgraph.dockarea.DockArea import DockAreafrom pyqtgraph.Qt import QtWidgets-from src.core_processor.fps.timestamp_manager import TimestampManager+from src.core_processor.timestamp_manager.timestamp_manager import TimestampManagerfrom src.pipelines.session_pipeline.data_classes.data_3d_single_frame_payload import Data3dSingleFramePayloadlogger = logging.getLogger(__name__)