Free Motion Capture for Everyone πβ¨
TypeScript
Benchmark anipose (#643)
philipqueenb6608ab5664d
diff --git a/experimental/benchmark/README.md b/experimental/benchmark/README.mdnew file mode 100644index 00000000..9b0ab8bc--- /dev/null+++ b/experimental/benchmark/README.md@@ -0,0 +1,20 @@+# Benchmarks++## Run Benchmarks+The different benchmarks are in the `experimental/benchmark` folder.++You will need to change the path to the data you would like to benchmark on. You can download the data test data from within the Freemocap GUI.++The benchmark code is in the `if __name__ == "__main__":` block, so the benchmark can be run with `python experimental/benchmark/{PATH TO BENCHMARK FILE}.py`.++When making changes to the code you want to benchmark, be sure to do a comparison in the GUI as well to see if the change is significant within the context of Freemocap as a whole.++## Flame Graphs++[Py-Spy](https://github.com/benfred/py-spy) can be used to generate [speedscope](https://www.speedscope.app/) compatible flame graphs.++Install py-spy through pip or your system package manager, and run with:++```+sudo py-spy record -f speedscope -- python experimental/benchmark/{PATH TO BENCHMARK FILE}.py+```diff --git a/experimental/benchmark/anipose/benchmark_calibrate_videos.py b/experimental/benchmark/anipose/benchmark_calibrate_videos.pynew file mode 100644index 00000000..a1428894--- /dev/null+++ b/experimental/benchmark/anipose/benchmark_calibrate_videos.py@@ -0,0 +1,50 @@+from pathlib import Path+import numpy as np+from time import perf_counter_ns++from freemocap.core_processes.capture_volume_calibration.anipose_camera_calibration.freemocap_anipose import (+ CameraGroup,+ AniposeCharucoBoard,+)+from freemocap.core_processes.capture_volume_calibration.charuco_stuff.charuco_board_definition import (+ CharucoBoardDefinition,+)+from freemocap.utilities.get_video_paths import get_video_paths+++if __name__ == "__main__":+ # TODO: do all this setup with recording_info object+ recording_folder = Path("/Users/philipqueen/freemocap_data/recording_sessions/freemocap_test_data/")+ synchronized_folder = recording_folder / "synchronized_videos"++ video_paths = get_video_paths(synchronized_folder)+ list_of_camera_names = [video_path.stem for video_path in video_paths]+ video_paths_list_of_list_of_strings = [[str(this_path)] for this_path in video_paths]++ calibration = CameraGroup.from_names(list_of_camera_names)+ charuco_square_size = 39++ calibration.metadata["charuco_square_size"] = charuco_square_size+ calibration.metadata["charuco_board_object"] = str(CharucoBoardDefinition)+ calibration.metadata["path_to_recorded_videos"] = str(synchronized_folder)+ calibration.metadata["date_time_calibrated"] = str(np.datetime64("now"))++ anipose_charuco_board = AniposeCharucoBoard(+ 7,+ 6,+ square_length=charuco_square_size, # mm+ marker_length=charuco_square_size * 0.8,+ marker_bits=4,+ dict_size=250,+ )++ num_trials = 5+ print("Benchmarking calibrate_videos:\n")+ times = []+ for i in range(num_trials):+ start = perf_counter_ns()+ calibration.calibrate_videos(video_paths_list_of_list_of_strings, anipose_charuco_board)+ end = perf_counter_ns()+ times.append((end - start) / 1e9)+ print(f"This round calibration time is: {(end - start) / 1e9} seconds")+ print(f"\tAverage calibration time across trials is: {np.mean(times)} seconds over {num_trials} runs")diff --git a/experimental/benchmark/anipose/benchmark_reprojection_error.py b/experimental/benchmark/anipose/benchmark_reprojection_error.pynew file mode 100644index 00000000..180879db--- /dev/null+++ b/experimental/benchmark/anipose/benchmark_reprojection_error.py@@ -0,0 +1,57 @@+from pathlib import Path+import numpy as np+from time import perf_counter_ns++from freemocap.core_processes.capture_volume_calibration.anipose_camera_calibration.freemocap_anipose import CameraGroup+++if __name__ == "__main__":+ # TODO: do all this setup with recording_info object+ recording_folder = Path("/Users/philipqueen/freemocap_data/recording_sessions/freemocap_test_data/")++ calibration_toml_path = list(recording_folder.glob("*calibration.toml"))[0]+ calibration = CameraGroup.load(calibration_toml_path)++ data_2d_path = (+ recording_folder+ / "output_data"+ / "raw_data"+ / "mediapipe_2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"+ )+ data_2d = np.load(data_2d_path)+ data_2d_flat = data_2d.reshape(data_2d.shape[0], -1, 2)++ data_3d = calibration.triangulate(data_2d_flat, progress=False)+ print(f"data_3d shape: {data_3d.shape}")+ print(f"data_2d_flat shape: {data_2d_flat.shape}")++ num_trials = 5++ print("Benchmarking reprojection error with mean=True:\n")+ times = []+ for i in range(num_trials):+ start = perf_counter_ns()+ calibration.reprojection_error(points_3d=data_3d, points_2d=data_2d_flat, mean=True)+ end = perf_counter_ns()+ times.append((end - start) / 1e9)+ print(f"This round reprojection error time is: {(end - start) / 1e9} seconds for {data_2d.shape[1]} frames")+ print(f"This round average time per frame is: {(end - start) / 1e9 / data_2d.shape[1]} seconds\n")++ print(+ f"\tAverage reprojection error time across trials is: {np.mean(times)} seconds for {data_2d.shape[1]} frames over {num_trials} runs"+ )+ print(f"\tAverage time per frame is: {np.mean(times) / (data_2d.shape[1] * num_trials)} seconds\n")++ print("Benchmarking reprojection error with mean=False:\n")+ times = []+ for i in range(num_trials):+ start = perf_counter_ns()+ calibration.reprojection_error(points_3d=data_3d, points_2d=data_2d_flat, mean=False)+ end = perf_counter_ns()+ times.append((end - start) / 1e9)+ print(f"This round reprojection error time is: {(end - start) / 1e9} seconds for {data_2d.shape[1]} frames")+ print(f"This round average time per frame is: {(end - start) / 1e9 / data_2d.shape[1]} seconds\n")+ print(+ f"\tAverage reprojection error time across trials is: {np.mean(times)} seconds for {data_2d.shape[1]} frames over {num_trials} runs"+ )+ print(f"\tAverage time per frame is: {np.mean(times) / (data_2d.shape[1] * num_trials)} seconds\n")diff --git a/experimental/benchmark/anipose/benchmark_triangulate.py b/experimental/benchmark/anipose/benchmark_triangulate.pynew file mode 100644index 00000000..a30b85ec--- /dev/null+++ b/experimental/benchmark/anipose/benchmark_triangulate.py@@ -0,0 +1,41 @@+from pathlib import Path+import numpy as np+from time import perf_counter_ns++from freemocap.core_processes.capture_volume_calibration.anipose_camera_calibration.freemocap_anipose import CameraGroup+++def direct_triangulate(anipose_calibration_object: CameraGroup, data_2d: np.ndarray):+ return anipose_calibration_object.triangulate(data_2d, progress=False)+++if __name__ == "__main__":+ # TODO: do all this setup with recording_info object+ recording_folder = Path("/Users/philipqueen/freemocap_data/recording_sessions/freemocap_test_data/")++ calibration_toml_path = list(recording_folder.glob("*calibration.toml"))[0]+ calibration = CameraGroup.load(calibration_toml_path)++ data_2d_path = (+ recording_folder+ / "output_data"+ / "raw_data"+ / "mediapipe_2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"+ )+ data_2d = np.load(data_2d_path)+ data_2d_flat = data_2d.reshape(data_2d.shape[0], -1, 2)++ num_trials = 5++ times = []+ for i in range(num_trials):+ start = perf_counter_ns()+ direct_triangulate(calibration, data_2d_flat)+ end = perf_counter_ns()+ times.append((end - start) / 1e9)+ print(f"This round triangulation time is: {(end - start) / 1e9} seconds for {data_2d.shape[1]} frames")+ print(f"This round average time per frame is: {(end - start) / 1e9 / data_2d.shape[1]} seconds\n")+ print(+ f"\tTotal triangulation time is: {np.mean(times)} seconds for {data_2d.shape[1]} frames over {num_trials} runs"+ )+ print(f"\tAverage time per frame is: {np.mean(times) / (data_2d.shape[1] * num_trials)} seconds")diff --git a/freemocap/core_processes/capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.py b/freemocap/core_processes/capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.pyindex 549b0116..f6d5afde 100644--- a/freemocap/core_processes/capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.py+++ b/freemocap/core_processes/capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.py@@ -12,7 +12,9 @@ from freemocap.system.paths_and_filenames.path_getters import get_last_successfulogger = logging.getLogger(__name__)-def load_most_recent_anipose_calibration_toml(save_copy_of_calibration_to_this_path: Union[str, Path] = None):+def load_most_recent_anipose_calibration_toml(+ save_copy_of_calibration_to_this_path: Union[str, Path, None] = None+) -> freemocap_anipose.CameraGroup:most_recent_calibration_toml_path = get_last_successful_calibration_toml_path()logger.info(f"loading `most recent calibration from:{str(most_recent_calibration_toml_path)}")if save_copy_of_calibration_to_this_path is not None:@@ -33,18 +35,23 @@ def load_most_recent_anipose_calibration_toml(save_copy_of_calibration_to_this_pdef load_anipose_calibration_toml_from_path(camera_calibration_data_toml_path: Union[str, Path],- save_copy_of_calibration_to_this_path: Union[str, Path],-):+ save_copy_of_calibration_to_this_path: Union[str, Path, None] = None,+) -> freemocap_anipose.CameraGroup:logger.info(f"loading camera calibration file from:{str(camera_calibration_data_toml_path)}")try:anipose_calibration_object = freemocap_anipose.CameraGroup.load(str(camera_calibration_data_toml_path))- copy_toml_path = str(Path(save_copy_of_calibration_to_this_path) / Path(camera_calibration_data_toml_path).name)-- if Path(copy_toml_path).is_file() and not filecmp.cmp(str(camera_calibration_data_toml_path), copy_toml_path):- logger.info(- f"Saving copy of {camera_calibration_data_toml_path} to {save_copy_of_calibration_to_this_path}"+ if save_copy_of_calibration_to_this_path is not None:+ copy_toml_path = str(+ Path(save_copy_of_calibration_to_this_path) / Path(camera_calibration_data_toml_path).name)- shutil.copyfile(str(camera_calibration_data_toml_path), copy_toml_path)++ if Path(copy_toml_path).is_file() and not filecmp.cmp(+ str(camera_calibration_data_toml_path), copy_toml_path+ ):+ logger.info(+ f"Saving copy of {camera_calibration_data_toml_path} to {save_copy_of_calibration_to_this_path}"+ )+ shutil.copyfile(str(camera_calibration_data_toml_path), copy_toml_path)return anipose_calibration_objectexcept Exception as e:@@ -54,7 +61,7 @@ def load_anipose_calibration_toml_from_path(def load_calibration_from_session_id(session_calibration_file_path: Union[str, Path],-):+) -> freemocap_anipose.CameraGroup:logger.info(f"loading camera calibration file from:{str(session_calibration_file_path)}")try:return freemocap_anipose.CameraGroup.load(str(session_calibration_file_path))diff --git a/freemocap/core_processes/capture_volume_calibration/triangulate_3d_data.py b/freemocap/core_processes/capture_volume_calibration/triangulate_3d_data.pyindex a411bec0..350d113f 100644--- a/freemocap/core_processes/capture_volume_calibration/triangulate_3d_data.py+++ b/freemocap/core_processes/capture_volume_calibration/triangulate_3d_data.py@@ -4,6 +4,7 @@ from pathlib import Pathimport numpy as np+from freemocap.core_processes.capture_volume_calibration.anipose_camera_calibration.freemocap_anipose import CameraGroupfrom freemocap.core_processes.capture_volume_calibration.save_3d_data_to_npy import (save_3d_data_to_npy,)@@ -12,7 +13,7 @@ logger = logging.getLogger(__name__)def triangulate_3d_data(- anipose_calibration_object,+ anipose_calibration_object: CameraGroup,image_2d_data: np.ndarray,use_triangulate_ransac: bool = False,kill_event: multiprocessing.Event = None,diff --git a/freemocap/utilities/get_video_paths.py b/freemocap/utilities/get_video_paths.pyindex 5e79bcd0..8f91bd56 100644--- a/freemocap/utilities/get_video_paths.py+++ b/freemocap/utilities/get_video_paths.py@@ -1,8 +1,8 @@from pathlib import Path-from typing import Union+from typing import Union, List-def get_video_paths(path_to_video_folder: Union[str, Path]) -> list:+def get_video_paths(path_to_video_folder: Union[str, Path]) -> List[Path]:"""Search the folder for 'mp4' files (case insensitive) and return them as a list"""list_of_video_paths = list(Path(path_to_video_folder).glob("*.mp4")) + list(