Free Motion Capture for Everyone πβ¨
TypeScript
Jon/post process data (#249)
jonmatthisca17b5d48924
diff --git a/.github/workflows/python-testing.yml b/.github/workflows/python-testing.ymlindex ec8fdbde..2adbfa28 100755--- a/.github/workflows/python-testing.yml+++ b/.github/workflows/python-testing.yml@@ -31,5 +31,5 @@ jobs:with:name: pytest-results-3.9path: junit/test-results-3.9.xml- # Use always() to always run this step to publish test results when there are test failures+ # Use always() to always calculate_center_of_mass this step to publish test results when there are test failuresif: ${{ always() }}\ No newline at end of filediff --git a/.gitignore b/.gitignoreindex e2d485c8..8f381f13 100644--- a/.gitignore+++ b/.gitignore@@ -152,3 +152,7 @@ freemocap_runme_script_jsm.pyfreemocap/fmc_calibration/previous_calibration.tomlfreemocap/fmc_calibration/++.DS_Store++desktop.inidiff --git a/bin/linux/build.sh b/bin/linux/build.shindex 02ae771c..4336b0e6 100755--- a/bin/linux/build.sh+++ b/bin/linux/build.sh@@ -1,6 +1,6 @@#!/usr/bin/env bash#-# Run tests meant to run in CI+# Run tests meant to calculate_center_of_mass in CI# https://github.com/moby/moby/issues/39003#issuecomment-852915070 - use buildkit inline cache with --build-arg (in docker-compose file)COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker-compose builddiff --git a/freemocap-ui/public/index.html b/freemocap-ui/public/index.htmlindex b8c495c0..43af94cc 100644--- a/freemocap-ui/public/index.html+++ b/freemocap-ui/public/index.html@@ -22,7 +22,7 @@Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" willwork correctly both with client-side routing and a non-root public URL.- Learn how to configure a non-root public URL by running `npm run build`.+ Learn how to configure a non-root public URL by running `npm calculate_center_of_mass build`.--><title>React Redux App</title></head>@@ -36,8 +36,8 @@You can add webfonts, meta tags, or analytics to this file.The build step will place the bundled scripts into the <body> tag.- To begin the development, run `npm start` or `yarn start`.- To create a production bundle, use `npm run build` or `yarn build`.+ To begin the development, calculate_center_of_mass `npm start` or `yarn start`.+ To create a production bundle, use `npm calculate_center_of_mass build` or `yarn build`.--></body><script type="text/javascript" src="https://unpkg.com/[email protected]/lib/opencv.js"></script>diff --git a/ipython_jupyter_notebooks/batch_process_session_folders.ipynb b/ipython_jupyter_notebooks/batch_process_session_folders.ipynbnew file mode 100644index 00000000..10bc6a63--- /dev/null+++ b/ipython_jupyter_notebooks/batch_process_session_folders.ipynb@@ -0,0 +1,213 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "source": [+ "# Batch Process multiple freemocap session folders\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "outputs": [],+ "source": [+ "#get paths to folder full of session folders\n",+ "list_of_session_folders = list(path_to_folder_of_session_folders.glob('ses*'))\n",+ "print(list_of_session_folders)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "#import stuff\n",+ "from pathlib import Path\n",+ "\n",+ "\n",+ "from src.core_processes.batch_process_session_folders import process_session_folder\n",+ "from src.core_processes.capture_volume_calibration.anipose_camera_calibration import freemocap_anipose\n"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## input `Path to folder of session folders` HERE\n"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "\n",+ "path_to_folder_of_session_folders = Path(\n",+ " r'D:\\Dropbox\\Northeastern\\Courses\\Biol2299\\2022_09_Fall_Biol2299_Inquiries_NeuralControlOfRealWorldBehavior\\freemocap_bos_com_standing_data\\FreeMocap_Data')\n"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Input `path_to_camrera_calibration_toml` HERE"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "\n",+ "path_to_camera_calibration_toml = Path(\n",+ " r\"D:\\Dropbox\\Northeastern\\Courses\\Biol2299\\2022_09_Fall_Biol2299_Inquiries_NeuralControlOfRealWorldBehavior\\freemocap_bos_com_standing_data\\FreeMocap_Data\\sesh_2022-09-28_15_57_08_calibration\\sesh_2022-09-28_15_57_08_calibration_calibration.toml\"\n",+ ")\n"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Input `path_to_blender_executable` HERE"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "path_to_blender_executable = Path(r\"C:\\Program Files\\Blender Foundation\\Blender 3.2\\blender.exe\")"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "# load anipose calibration object\n",+ "anipose_calibration_object = freemocap_anipose.CameraGroup.load(str(path_to_camera_calibration_toml))"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ }+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "outputs": [],+ "source": [+ "for session_folder_path in list_of_session_folders:\n",+ " print(f'-------------------------Processing {session_folder_path}-------------------------')\n",+ " if Path(session_folder_path / \"synchronized_videos\").exists(): # freemocap version > v0.0.54 (aka `alpha`)\n",+ " synchronized_videos_folder = Path(session_folder_path) / 'synchronized_videos'\n",+ " if Path(session_folder_path / \"SyncedVideos\").exists(): # freemocap version <= v0.0.54 (aka `pre-alpha`)\n",+ " synchronized_videos_folder = Path(session_folder_path) / 'SyncedVideos'\n",+ " else:\n",+ " print(f'No folder full of synchronized videos found for {session_folder_path}')\n",+ " continue\n",+ "\n",+ " output_data_folder = Path(session_folder_path) / 'output_data'\n",+ " output_data_folder.mkdir(exist_ok=True, parents=True)\n",+ "\n",+ " # process session folder via 'standard' freemocap pipeline\n",+ " process_session_folder(synchronized_videos_folder=synchronized_videos_folder,\n",+ " output_data_folder=output_data_folder,)\n",+ "\n",+ "print(\"Done!\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ }+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 2+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython2",+ "version": "2.7.6"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0+}\ No newline at end of filediff --git a/requirements.txt b/requirements.txtindex 8be9bbb6..daf09be5 100644--- a/requirements.txt+++ b/requirements.txt@@ -30,4 +30,5 @@ pyinstaller-hooks-contrib==2022.8black[d]==22.6.0mkdocs-material==8.3.9qtconsole==5.3.0-qtpy==2.0.1\ No newline at end of file+qtpy==2.0.1+rich==12.6.0\ No newline at end of filediff --git a/src/export_stuff/__init__.py b/src/blender_stuff/__init__.pysimilarity index 100%rename from src/export_stuff/__init__.pyrename to src/blender_stuff/__init__.pydiff --git a/src/export_stuff/blender_stuff/alpha_freemocap_blender_megascript.py b/src/blender_stuff/alpha_freemocap_blender_megascript.pysimilarity index 97%rename from src/export_stuff/blender_stuff/alpha_freemocap_blender_megascript.pyrename to src/blender_stuff/alpha_freemocap_blender_megascript.pyindex c2f90ce3..699e42ef 100644--- a/src/export_stuff/blender_stuff/alpha_freemocap_blender_megascript.py+++ b/src/blender_stuff/alpha_freemocap_blender_megascript.py@@ -35,27 +35,51 @@ except:print(str(session_path))session_path = Path(session_path)-path_to_mediapipe_npy = (- session_path- / "output_data"- / "mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"-)-path_to_mediapipe_3d_reproj = (- session_path- / "output_data"- / "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"-)+if Path(+ session_path / "output_data" / "partially_processed_data"+).exists(): # freemocap version > v0.0.54+ path_to_data_arrays_folder = session_path / "output_data"++ path_to_mediapipe_npy = (+ path_to_data_arrays_folder+ / "partially_processed_data"+ / "mediaPipeSkel_3d_origin_aligned.npy"+ )++ path_to_mediapipe_3d_reproj = (+ path_to_data_arrays_folder+ / "raw_data"+ / "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"+ )++else:+ path_to_data_arrays_folder = (+ session_path / "DataArrays"+ ) # freemocap version <= v0.0.54+ path_to_mediapipe_npy = path_to_data_arrays_folder / "mediaPipeSkel_3d_smoothed.npy"++ path_to_mediapipe_3d_reproj = (+ path_to_data_arrays_folder / "mediaPipeSkel_reprojErr.npy"+ )++ print(f"Loading mediapipe data from {path_to_mediapipe_npy}")######################################################################## %% load mediapipe data# %%print("loading data")# %%+print(f"Loading mediapipe data from {path_to_mediapipe_npy}")mediapipe_skel_fr_mar_dim = np.load(str(path_to_mediapipe_npy))+print("mediapipe_skel_fr_mar_dim.shape", mediapipe_skel_fr_mar_dim.shape)mediapipe_skel_fr_mar_dim = mediapipe_skel_fr_mar_dim / 1000 # convert to meters-mediapipe_reproj_fr_mar = np.load(str(path_to_mediapipe_3d_reproj))-mediapipe_reproj_fr_mar = mediapipe_reproj_fr_mar / 1000 # convert to meters+print(f"Loading mediapipe reprojection error data from {path_to_mediapipe_3d_reproj}")+mediapipe_reprojection_error_fr_mar = np.load(str(path_to_mediapipe_3d_reproj))+print(+ f"mediapipe_reprojection_error_fr_mar.shape = {mediapipe_reprojection_error_fr_mar.shape}"+)+body_marker_range = np.arange(0, 33)right_hand_marker_range = np.arange(33, 33 + 21)@@ -104,7 +128,7 @@ if good_clean_frame_number == 0:np.sum(np.isnan(mediapipe_skel_fr_mar_dim[this_frame, :, 0])))frame_mean_reproj_error.append(- np.nanmean(mediapipe_reproj_fr_mar[this_frame, :])+ np.nanmean(mediapipe_reprojection_error_fr_mar[this_frame, :]))nan_times_vis = np.array(frame_nan_counts) * np.array(frame_mean_reproj_error)diff --git a/src/blender_stuff/bind_rigify_meta_rig_to_freemocap_data.py b/src/blender_stuff/bind_rigify_meta_rig_to_freemocap_data.pynew file mode 100644index 00000000..87433095--- /dev/null+++ b/src/blender_stuff/bind_rigify_meta_rig_to_freemocap_data.py@@ -0,0 +1,892 @@+from typing import List++import bpy+import addon_utils++import numpy as np+from pathlib import Path+import json++import sys++print("Running script to create Blender file from freemocap session data: " + __file__)+###############################################################+### parse arguments from command line++try:+ ##% Session path+ # #get session path as command line argument+ argv = sys.argv+ argv = argv[argv.index("--") + 1 :]++ session_path = Path(argv[0])+ print(f"session_path: {session_path}")++ if len(argv) > 1:+ good_clean_frame_number = int(argv[1])+ else:+ good_clean_frame_number = 0++ print(f" user specified `good clean frame number`: {good_clean_frame_number}")+except Exception as e:+ print(e)+ print(+ "we appear to be running from the Blender Scripting tab! Manually enter your `session_path` at line 23"+ )+ # TODO - This should point to some kinda online-hosted demo session data or something+ session_path = Path(+ r"D:\Dropbox\FreeMoCapProject\teddy_animation\FreeMocap_Data\sesh_2022-10-01_13_38_04_paul_dance_2"+ )+ good_clean_frame_number = (+ 0 # pick a frame where subject is in a good pose (e.g. T- or A-pose+ )++############+## Define some things that we'll need later++# Mediapipe Tracked Point Names+mediapipe_body_trajectory_names = [+ "nose",+ "left_eye_inner",+ "left_eye",+ "left_eye_outer",+ "right_eye_inner",+ "right_eye",+ "right_eye_outer",+ "left_ear",+ "right_ear",+ "mouth_left",+ "mouth_right",+ "left_shoulder",+ "right_shoulder",+ "left_elbow",+ "right_elbow",+ "left_wrist",+ "right_wrist",+ "left_pinky",+ "right_pinky",+ "left_index",+ "right_index",+ "left_thumb",+ "right_thumb",+ "left_hip",+ "right_hip",+ "left_knee",+ "right_knee",+ "left_ankle",+ "right_ankle",+ "left_heel",+ "right_heel",+ "left_foot_index",+ "right_foot_index",+]++mediapipe_virtual_marker_definitions_dict = {+ "head_center": {+ "marker_names": ["left_ear", "right_ear"],+ "marker_weights": [0.5, 0.5],+ },+ "neck_center": {+ "marker_names": ["left_shoulder", "right_shoulder"],+ "marker_weights": [0.5, 0.5],+ },+ "hips_center": {+ "marker_names": ["left_hip", "right_hip"],+ "marker_weights": [0.5, 0.5],+ },+ "trunk_center": {+ "marker_names": ["left_shoulder", "right_shoulder", "left_hip", "right_hip"],+ "marker_weights": [0.25, 0.25, 0.25, 0.25],+ },+}++# Skeleton segments names and the rigify bone names that they correspond to+rigify_bone_to_skeleton_segment_name_correspondance = {+ "lower_spine": ["spine", "spine.001"],+ "upper_spine": ["spine.002", "spine.003"],+ "head": ["spine.004", "spine.005", "spine.006"],+ "left_hand": ["hand.L"],+ "left_forearm": ["forearm.L"],+ "left_upper_arm": ["upper_arm.L"],+ "right_hand": ["hand.R"],+ "right_forearm": ["forearm.R"],+ "right_upper_arm": ["upper_arm.R"],+ "left_thigh": ["thigh.L"],+ "left_calf": ["shin.L"],+ "left_foot": ["foot.L"],+ "right_thigh": ["thigh.R"],+ "right_calf": ["shin.R"],+ "right_foot": ["foot.R"],+}++# A dictionary where the `keys` are rigify bone names and the `values` are bone constraints and their parameters.+# NOTE - the `targets` must correspond to the `mediapipe_body_names` list above (or one of the virtural markers we'll make later)+rig_constraint_dict_of_dicts = {+ "spine": {+ "COPY_LOCATION": {"target": "hips_center"},+ },+ "spine.003": {+ "IK": {"target": "neck_center", "chain_length": 4},+ },+ "spine.004": {+ "COPY_LOCATION": {"target": "neck_center"},+ },+ "spine.006": {+ "IK": {"target": "head_center", "chain_length": 2},+ },+ "face": {+ "COPY_LOCATION": {"target": "armature", "subtarget": "spine.006"},+ "DAMPED_TRACK": {+ "target": "head_center",+ },+ "LOCKED_TRACK": {+ "target": "nose",+ "track_axis": "TRACK_Z",+ "lock_axis": "LOCK_Y",+ "influence": 1.0,+ },+ "LOCKED_TRACK.001": {+ "target": "left_ear",+ "track_axis": "TRACK_Z",+ "lock_axis": "LOCK_Z",+ "influence": 1.0,+ },+ },+ "shoulder.R": {+ "COPY_LOCATION": {"target": "neck_center"},+ "DAMPED_TRACK": {"target": "right_shoulder"},+ },+ "upper_arm.R": {+ "DAMPED_TRACK": {"target": "right_elbow"},+ },+ "forearm.R": {+ "DAMPED_TRACK": {"target": "right_wrist"},+ },+ "hand.R": {+ "DAMPED_TRACK": {"target": "right_index"},+ },+ "shoulder.L": {+ "COPY_LOCATION": {"target": "neck_center"},+ "DAMPED_TRACK": {"target": "left_shoulder"},+ },+ "upper_arm.L": {+ "DAMPED_TRACK": {"target": "left_elbow"},+ },+ "forearm.L": {+ "DAMPED_TRACK": {"target": "left_wrist"},+ },+ "hand.L": {+ "DAMPED_TRACK": {"target": "left_index"},+ },+ "thigh.R": {+ "COPY_LOCATION": {"target": "right_hip"},+ "DAMPED_TRACK": {"target": "right_knee"},+ },+ "shin.R": {+ "DAMPED_TRACK": {"target": "right_ankle"},+ },+ "foot.R": {+ "DAMPED_TRACK": {"target": "right_foot_index"},+ },+ "thigh.L": {+ "COPY_LOCATION": {"target": "left_hip"},+ "DAMPED_TRACK": {"target": "left_knee"},+ },+ "shin.L": {+ "DAMPED_TRACK": {"target": "left_ankle"},+ },+ "foot.L": {+ "DAMPED_TRACK": {"target": "left_foot_index"},+ },+}++# connects the dots what for to make the stick figure friend+stick_figure_mesh_edges_list_of_lists = [+ ["head_center", "nose"],+ ["nose", "left_eye_inner"],+ ["left_eye_inner", "left_eye"],+ ["left_eye", "left_eye_outer"],+ ["left_eye_outer", "left_ear"],+ ["nose", "right_eye_inner"],+ ["right_eye_inner", "right_eye"],+ ["right_eye", "right_eye_outer"],+ ["right_eye_outer", "right_ear"],+ ["nose", "mouth_right"],+ ["mouth_right", "mouth_left"],+ ["nose", "mouth_left"],+ ["left_elbow", "left_wrist"],+ ["left_shoulder", "left_elbow"],+ ["neck_center", "left_shoulder"],+ ["right_elbow", "right_wrist"],+ ["right_shoulder", "right_elbow"],+ ["neck_center", "right_shoulder"],+ ["left_hip", "left_knee"],+ ["left_knee", "left_ankle"],+ ["left_heel", "left_ankle"],+ ["left_ankle", "left_foot_index"],+ ["left_foot_index", "left_heel"],+ ["right_hip", "right_knee"],+ ["right_knee", "right_ankle"],+ ["right_heel", "right_ankle"],+ ["right_ankle", "right_foot_index"],+ ["right_foot_index", "right_heel"],+ ["hips_center", "left_hip"],+ ["hips_center", "right_hip"],+ ["hips_center", "neck_center"],+ ["neck_center", "head_center"],+ ["head_center", "nose"],+ # right hand+ ["right_wrist", "right_hand_index_finger_mcp"],+ ["right_wrist", "right_hand_middle_finger_mcp"],+ ["right_wrist", "right_hand_ring_finger_mcp"],+ ["right_wrist", "right_hand_pinky_finger_mcp"],+ ["right_wrist", "right_hand_thumb_cmc"],+ ["right_hand_thumb_cmc", "right_hand_thumb_mcp"],+ ["right_hand_thumb_mcp", "right_hand_thumb_ip"],+ ["right_hand_thumb_ip", "right_hand_thumb_tip"],+ ["right_hand_index_finger_mcp", "right_hand_index_finger_pip"],+ ["right_hand_index_finger_pip", "right_hand_index_finger_dip"],+ ["right_hand_index_finger_dip", "right_hand_index_finger_tip"],+ ["right_hand_middle_finger_mcp", "right_hand_middle_finger_pip"],+ ["right_hand_middle_finger_pip", "right_hand_middle_finger_dip"],+ ["right_hand_middle_finger_dip", "right_hand_middle_finger_tip"],+ ["right_hand_ring_finger_mcp", "right_hand_ring_finger_pip"],+ ["right_hand_ring_finger_pip", "right_hand_ring_finger_dip"],+ ["right_hand_ring_finger_dip", "right_hand_ring_finger_tip"],+ ["right_hand_pinky_finger_mcp", "right_hand_pinky_finger_pip"],+ ["right_hand_pinky_finger_pip", "right_hand_pinky_finger_dip"],+ ["right_hand_pinky_finger_dip", "right_hand_pinky_finger_tip"],+ # left hand+ ["left_wrist", "left_hand_thumb_cmc"],+ ["left_hand_thumb_cmc", "left_hand_thumb_mcp"],+ ["left_hand_thumb_mcp", "left_hand_thumb_ip"],+ ["left_hand_thumb_ip", "left_hand_thumb_tip"],+ ["left_wrist", "left_hand_index_finger_mcp"],+ ["left_wrist", "left_hand_middle_finger_mcp"],+ ["left_wrist", "left_hand_ring_finger_mcp"],+ ["left_wrist", "left_hand_pinky_finger_mcp"],+ ["left_hand_index_finger_mcp", "left_hand_index_finger_pip"],+ ["left_hand_index_finger_pip", "left_hand_index_finger_dip"],+ ["left_hand_index_finger_dip", "left_hand_index_finger_tip"],+ ["left_hand_middle_finger_mcp", "left_hand_middle_finger_pip"],+ ["left_hand_middle_finger_pip", "left_hand_middle_finger_dip"],+ ["left_hand_middle_finger_dip", "left_hand_middle_finger_tip"],+ ["left_hand_ring_finger_mcp", "left_hand_ring_finger_pip"],+ ["left_hand_ring_finger_pip", "left_hand_ring_finger_dip"],+ ["left_hand_ring_finger_dip", "left_hand_ring_finger_tip"],+ ["left_hand_pinky_finger_mcp", "left_hand_pinky_finger_pip"],+ ["left_hand_pinky_finger_pip", "left_hand_pinky_finger_dip"],+ ["left_hand_pinky_finger_dip", "left_hand_pinky_finger_tip"],+]+++#################################################+## FUNCTIONS - We'll define some functions here and use them later+++def create_keyframed_empty_from_3d_trajectory_data(+ trajectory_fr_xyz: np.ndarray,+ trajectory_name: str,+ parent_origin: bpy.types.Object = None,+ empty_scale: float = 0.1,+ empty_type: str = "PLAIN_AXES",+):+ """+ Create a key framed empty from 3d trajectory data+ """+ print(f"Creating keyframed empty from: {trajectory_name}...")+ bpy.ops.object.empty_add(type=empty_type)+ empty_object = bpy.context.active_object+ empty_object.name = trajectory_name++ empty_object.scale = [empty_scale] * 3++ empty_object.parent = freemocap_origin_axes++ for frame_number in range(end_frame):+ empty_object.location = [+ trajectory_fr_xyz[frame_number, 0],+ trajectory_fr_xyz[frame_number, 1],+ trajectory_fr_xyz[frame_number, 2],+ ]+ bpy.context.view_layer.update()++ empty_object.keyframe_insert(data_path="location", frame=frame_number)+++def apply_constraints_to_bone(bone_name: str, bone_constraint_dict: dict, armature_rig):+ """+ Apply constraints to a bone (that exists in `armature_rig` based on a dictionary of constraints+ """+ for (+ constraint_name,+ constrain_parameters_dict,+ ) in bone_constraint_dict.items():+ constraint_name = constraint_name.split(".")[+ 0+ ] # for duplicated constraints, named `[constraint_name].001`, etc+ print(+ f"constraint: {constraint_name} with parameters:{constrain_parameters_dict}"+ )++ bone = armature_rig.pose.bones[bone_name]+ print(f"bone: {bone.name}")++ constraint = bone.constraints.new(type=constraint_name)+ print(f"constraint: {constraint.name}")++ # generic constraint settings+ if "target" in constrain_parameters_dict:++ if constrain_parameters_dict["target"] == "armature":+ constraint.target = armature_rig+ constraint.subtarget = constrain_parameters_dict["subtarget"]+ print(f"constraint.target: {constraint.target.name}")+ print(f"constraint.subtarget: {constraint.target.name}")+ else:+ constraint.target = bpy.data.objects[+ constrain_parameters_dict["target"]+ ] # point constraint at relevant empty object+ print(f"constraint.target: {constraint.target.name}")++ if "influence" in constrain_parameters_dict:+ constraint.influence = constrain_parameters_dict["influence"]+ print(f"constraint.influence: {constraint.influence}")++ # constraint-specific settings+ if constraint_name == "IK":+ constraint.chain_count = constrain_parameters_dict["chain_length"]+ print(f"constraint.chain_count: {constraint.chain_count}")++ if constraint_name == "LOCKED_TRACK":+ constraint.track_axis = constrain_parameters_dict["track_axis"]+ constraint.lock_axis = constrain_parameters_dict["lock_axis"]+ print(f"constraint.track_axis: {constraint.track_axis}")+ print(f"constraint.lock_axis: {constraint.lock_axis}")++ if constraint_name == "DAMPED_TRACK":+ if "track_axis" in constrain_parameters_dict:+ constraint.track_axis = constrain_parameters_dict["track_axis"]+ print(f"constraint.track_axis: {constraint.track_axis}")+++# Virtual marker stuff+++def test_virtual_marker_definitions(virtual_marker_definitions_dict: dict):+ """+ Validate the virtual marker definitions dictionary to ensure that there are the same number of marker names and weights, and that the weights sum to 1+ """++ for (+ virtual_marker_name,+ virtual_marker_definition,+ ) in virtual_marker_definitions_dict.items():+ assert len(virtual_marker_definition["marker_names"]) == len(+ virtual_marker_definition["marker_weights"]+ ), f"marker_names and marker_weights must be the same length for virtual marker {virtual_marker_name}"+ assert (+ sum(virtual_marker_definition["marker_weights"]) == 1+ ), f"marker_weights must sum to 1 for virtual marker {virtual_marker_name}"+++def create_virtual_marker(+ trajectory_3d_frame_marker_xyz: np.ndarray,+ all_trajectory_names: list,+ component_trajectory_names: List,+ trajectory_weights: List,+) -> np.ndarray:+ """+ Create a virtual marker from a set of component markers. A 'Virtual Marker' is a 'fake' marker created by combining the data from 'real' (measured) marker/trajectory data+ `trajectory_3d_frame_marker_xyz`: all trajectory data in a numpy array with shape [frame, marker, xyz]+ `all_trajectory_names`: list of all trajectory names+ `component_trajectory_names`: the trajectories we'll use to make this virtual marker+ `trajectory_weights`: the weights we'll use to combine the compoenent trajectories into the virtual maker+ """++ # double check that the weights scale to one, otherwise this function will return screwy results+ assert np.sum(trajectory_weights) == 1, "Error - Trajectory_weights must sum to 1!"++ virtual_marker_xyz = np.zeros((trajectory_3d_frame_marker_xyz.shape[0], 3))++ for trajectory_number, trajectory_name in enumerate(component_trajectory_names):+ # pull out the trajectory data for this component trajectory+ component_trajectory_xyz = trajectory_3d_frame_marker_xyz[+ :, all_trajectory_names.index(trajectory_name), :+ ]++ # scale it by its weight+ component_trajectory_xyz *= trajectory_weights[trajectory_number]++ # add it to the virtual marker+ virtual_marker_xyz += component_trajectory_xyz++ return virtual_marker_xyz+++def put_sphere_meshes_on_empties(+ empty_names_list: list,+ parent_object: bpy.types.Object,+ sphere_scale: float = 0.02,+):+ """+ put uv sphere meshes on the empties in `empty_names_list` with a scale of `sphere_scale`+ """++ for empty_name in empty_names_list:+ bpy.ops.mesh.primitive_uv_sphere_add(+ segments=8, ring_count=8, scale=(sphere_scale, sphere_scale, sphere_scale)+ )+ sphere = bpy.context.active_object+ sphere.name = f"{empty_name}_sphere"+ sphere.parent = parent_object++ constraint = sphere.constraints.new(type="COPY_LOCATION")+ constraint.target = bpy.data.objects[empty_name]+++def make_stick_figure_mesh(+ skel3d_frame_landmark_xyz: np.ndarray,+ stick_figure_mesh_edges: list,+ mediapipe_landmark_names: list,+ good_clean_frame_number: int,+):+ """+ Create a stick figure mesh from a skeleton 3d data set+ `skel3d_frame_landmark_xyz`: skeleton 3d data set with shape [frame, landmark, xyz]+ `stick_figure_mesh_edge`: list of edges that make up the stick figure mesh+ `good_clean_frame_number`: the frame number to use for the stick figure mesh+ """++ # create a mesh+ mesh = bpy.data.meshes.new("stick_figure_mesh")++ # create a new object with the mesh+ stick_figure_mesh = bpy.data.objects.new("stick_figure_mesh", mesh)++ # get a reference to the scene+ scene = bpy.context.scene++ # link the object to the scene so it'll appear in the scene+ scene.collection.objects.link(stick_figure_mesh)++ # select the object+ stick_figure_mesh.select_set(True)++ # create the mesh from a list of verts/edges+ stick_figure_mesh_indicies = []+ for edge in stick_figure_mesh_edges:+ try:+ stick_figure_mesh_indicies.append(+ [+ mediapipe_landmark_names.index(edge[0]),+ mediapipe_landmark_names.index(edge[1]),+ ]+ )+ except Exception as e:+ print(e)++ mesh.from_pydata(+ skel3d_frame_landmark_xyz[good_clean_frame_number, :, :],+ stick_figure_mesh_indicies,+ [],+ )++ # update mesh with new data+ mesh.update(calc_edges=True)++ return stick_figure_mesh+++def find_good_clean_frame_reprojection_error_method(+ skeleton_3d_fr_mar_xyz: np.ndarray, skeleton_reprojection_error_fr_mar: np.ndarray+):+ """+ Find the frame with the fewest nans, scaled by reprojection error (i.e. hopefully a frame where all tracked points are visible and well tracked)+ """+ print(+ "estimating good clean frame as the one where there few `nans`, reprojection error is low, and velocity is low..."+ )++ nans_per_frame = np.sum(np.isnan(skeleton_3d_fr_mar_xyz[:, :, 0]), axis=1)+ reprojection_error_per_frame = np.nanmedian(+ skeleton_reprojection_error_fr_mar, axis=1+ )+ marker_velocity_per_frame = np.nanmedian(+ np.abs(np.diff(skeleton_3d_fr_mar_xyz, axis=1)), axis=1+ )+ marker_velocity_per_frame = np.nanmean(np.abs(marker_velocity_per_frame), axis=1)++ print(f"nans_per_frame.shape: {nans_per_frame.shape}")+ print(f"reprojection_error_per_frame.shape: {reprojection_error_per_frame.shape}")+ print(f"marker_velocity_per_frame.shape: {marker_velocity_per_frame.shape}")++ # normalize errors by relevant thing+ nans_per_frame_normalized = nans_per_frame / skeleton_3d_fr_mar_xyz.shape[1]+ reprojection_error_per_frame_normalized = (+ reprojection_error_per_frame / np.nanmedian(reprojection_error_per_frame)+ )+ marker_velocity_per_frame_normalized = marker_velocity_per_frame / np.nanmedian(+ marker_velocity_per_frame+ )++ print(+ f"nans_per_frame_normalized (mean, [standard_deviation] : {np.nanmean(nans_per_frame_normalized):.3f} [{np.nanstd(nans_per_frame_normalized):.3f}]"+ )+ print(+ f"reprojection_error_per_frame_normalized (mean, [standard_deviation] : {np.nanmean(reprojection_error_per_frame_normalized):.3f} [{np.nanstd(reprojection_error_per_frame_normalized):.3f}]"+ )+ print(+ f"marker_velocity_per_frame_normalized (mean, [standard_deviation] : {np.nanmean(marker_velocity_per_frame_normalized):.3f} [{np.nanstd(marker_velocity_per_frame_normalized):.3f}]"+ )++ frame_cleanliness_score_where_low_scores_are_good = (+ nans_per_frame_normalized+ + reprojection_error_per_frame_normalized+ + marker_velocity_per_frame_normalized+ )++ good_clean_frame_number = np.nanargmin(+ frame_cleanliness_score_where_low_scores_are_good+ )+ print(f"----estimated good_clean_frame_number: {good_clean_frame_number}----")+ return good_clean_frame_number+++#######################################################################+##% Activate necessary addons+addon_utils.enable("io_import_images_as_planes")+addon_utils.enable("rigify")++#####################################################################+###%% clear the scene - Scorch the earth \o/+print("clearing scene")+try:+ bpy.ops.object.mode_set(mode="OBJECT")+except:+ pass++try:+ bpy.ops.object.select_all(action="SELECT") # select all objects+ bpy.ops.object.delete(use_global=True) # delete all objects from all scenes+except:+ pass++##################+### Getcher paths straight, lock and load yr data+# path_to_data_folder = Path("/Users/jon/Dropbox/FreeMoCapProject/FreeMocap_Data/")++print("Loading data....")+# %% load mediapipe data+# paths and whatnot+if Path(session_path / "output_data").exists(): # freemocap version > v0.0.54+ path_to_data_arrays_folder = session_path / "output_data"+ path_to_body_npy = path_to_data_arrays_folder / "mediapipe_body_3d_xyz.npy"+ path_to_reprojection_error_npy = (+ path_to_data_arrays_folder+ / "raw_data"+ / "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"+ )+ mediapipe_skel_fr_mar_xyz = np.load(str(path_to_body_npy))+ mediapipe_reprojection_error_fr_mar = np.load(str(path_to_reprojection_error_npy))++else:+ path_to_data_arrays_folder = (+ session_path / "DataArrays"+ ) # freemocap version <= v0.0.54+ if Path(+ path_to_data_arrays_folder / "mediapipe_body_3d_xyz.npy"+ ).exists(): # data has been 'post processed'+ path_to_body_npy = path_to_data_arrays_folder / "mediapipe_body_3d_xyz.npy"+ else:+ path_to_body_npy = (+ path_to_data_arrays_folder / "mediaPipeSkel_3d_smoothed.npy.npy"+ )++ path_to_reprojection_error_npy = (+ path_to_data_arrays_folder / "mediaPipeSkel_reprojErr.npy"+ )++ print(f"Loading mediapipe data from {path_to_body_npy}")++ mediapipe_skel_fr_mar_xyz = np.load(str(path_to_body_npy))+ mediapipe_reprojection_error_fr_mar = np.load(str(path_to_reprojection_error_npy))++ mediapipe_skel_fr_mar_xyz = mediapipe_skel_fr_mar_xyz[+ :, :33, :+ ] # remove the hand and face markers+ mediapipe_reprojection_error_fr_mar = mediapipe_reprojection_error_fr_mar[+ :, :33+ ] # remove the hand and face markers++# load mediapipe skeleton data++mediapipe_skel_fr_mar_xyz = mediapipe_skel_fr_mar_xyz / 1000 # convert to meters+number_of_frames = mediapipe_skel_fr_mar_xyz.shape[0]+print(f"mediapipe_skel_fr_mar_dim.shape: {mediapipe_skel_fr_mar_xyz.shape}")+print(+ f"mediapipe_reprojection_error_fr_mar.shape: {mediapipe_reprojection_error_fr_mar.shape}"+)++# get video paths (running through all iterations of our folder names+if Path(session_path / "annotated_videos").is_dir():+ video_folder_path = Path(session_path / "annotated_videos")+elif Path(session_path / "synchronized_videos").is_dir():+ video_folder_path = session_path / "synchronized_videos"+elif Path(session_path / "Annotated_Videos").is_dir():+ video_folder_path = session_path / "Annotated_Videos"+elif Path(session_path / "SyncedVideos").is_dir():+ video_folder_path = session_path / "SyncedVideos"+else:+ print("Couldn't find a video folder")++# load skeleton segment lengths+path_to_segment_length_json = (+ path_to_data_arrays_folder / "skeleton_segment_lengths.json"+)+try:+ print(+ f"loading skeleton segment lengths from `json` at - {str(path_to_segment_length_json)}"+ )+ f = open(path_to_segment_length_json)+ skeleton_segment_lengths_dict = json.load(f)+ f.close()+except Exception as e:+ print(e)+ print(+ f"Failed to load skeleton segment lengths from `json` at : {str(path_to_segment_length_json)}"+ )+ skeleton_segment_lengths_dict = None++#########################+### Create Origin Axes++bpy.ops.object.empty_add(type="ARROWS")+world_origin_axes = bpy.context.active_object+world_origin_axes.name = "world_origin" # will stay at origin++bpy.ops.object.empty_add(type="ARROWS")+freemocap_origin_axes = bpy.context.active_object+freemocap_origin_axes.name = "freemocap_origin_axes" # will translate to put skelly on ground symmetric-ish about origin++##############################+# %% Set start and end frames++start_frame = 1+end_frame = number_of_frames++if good_clean_frame_number == 0 or good_clean_frame_number is None:+ # estimate a good clean frame (ideally the T or A pose, but that's hard to pick out automatically)+ good_clean_frame_number = find_good_clean_frame_reprojection_error_method(+ skeleton_3d_fr_mar_xyz=mediapipe_skel_fr_mar_xyz,+ skeleton_reprojection_error_fr_mar=mediapipe_reprojection_error_fr_mar,+ )++bpy.context.scene.frame_start = start_frame+bpy.context.scene.frame_end = end_frame+bpy.context.scene.frame_current = good_clean_frame_number++############################+### Load body data as empty markers+empty_scale = 0.01+for trajectory_name in mediapipe_body_trajectory_names:+ this_trajectory_fr_xyz = mediapipe_skel_fr_mar_xyz[+ :, mediapipe_body_trajectory_names.index(trajectory_name), :+ ]+ create_keyframed_empty_from_3d_trajectory_data(+ trajectory_fr_xyz=this_trajectory_fr_xyz,+ trajectory_name=trajectory_name,+ parent_origin=freemocap_origin_axes,+ empty_scale=0.01,+ empty_type="SPHERE",+ )++#######################################################################+# %% create virtual markers+print("Creating virtual markers...")++# verify that the virtual marker definition dictionary is valid+test_virtual_marker_definitions(mediapipe_virtual_marker_definitions_dict)++for (+ virtual_marker_name,+ virtual_marker_dict,+) in mediapipe_virtual_marker_definitions_dict.items():+ print(+ f"Creating virtual marker: {virtual_marker_name}: "+ f"from 'real' markers: {virtual_marker_dict['marker_names']}, "+ f"with weights: {virtual_marker_dict['marker_weights']}"+ )++ mediapipe_body_trajectory_names.append(virtual_marker_name)+ virtual_marker_xyz = create_virtual_marker(+ trajectory_3d_frame_marker_xyz=mediapipe_skel_fr_mar_xyz,+ all_trajectory_names=mediapipe_body_trajectory_names,+ component_trajectory_names=virtual_marker_dict["marker_names"],+ trajectory_weights=virtual_marker_dict["marker_weights"],+ )+ create_keyframed_empty_from_3d_trajectory_data(+ trajectory_fr_xyz=virtual_marker_xyz,+ trajectory_name=virtual_marker_name,+ parent_origin=freemocap_origin_axes,+ empty_scale=empty_scale * 3,+ empty_type="PLAIN_AXES",+ )++print("____________________________________________________________________________")+print("Done loading in motion capture data - Now lets use it to drive an armature!")+print("____________________________________________________________________________")++######################+### Create Rigify human meta-rig+print(f"Creating `rigify human meta-rig`")+bpy.ops.object.armature_human_metarig_add()+human_metarig = bpy.context.active_object++##################+### Scale armature+++try:+ bpy.ops.object.mode_set(mode="EDIT")+except:+ pass++for (+ segment_name,+ rigify_bones_list,+) in rigify_bone_to_skeleton_segment_name_correspondance.items():++ for rigify_bone_name in rigify_bones_list:+ median_segment_length = skeleton_segment_lengths_dict[segment_name]["median"]+ median_segment_length *= 0.001 # scale to meters++ segment_length = median_segment_length / len(+ rigify_bones_list+ ) # divide by number of bones in segment (for now, eventually will want to set weights+ print(f"setting {rigify_bone_name} length to: {segment_length:.3f} m")+ human_metarig.data.edit_bones[rigify_bone_name].length = segment_length++####+#### Constrain bones to empties+####++# loop through dictionary applying constraints+try:+ bpy.ops.object.mode_set(mode="POSE")+except:+ pass++try:+ for bone_name, bone_constraint_dict in rig_constraint_dict_of_dicts.items():+ print(f"---Setting constraints for bone:{bone_name}---")+ apply_constraints_to_bone(+ bone_name=bone_name,+ bone_constraint_dict=bone_constraint_dict,+ armature_rig=human_metarig,+ )++except Exception as e:+ print(e)+ print("Something went wrong applying constraints to armarture bones")++print("____________________________________________________________________________")+print("Done constraining armature bones to follow keyframed empties!")+print("____________________________________________________________________________")++####################+## Create simple stick figure mesh++print("____________________________________________________________________________")+print("Creating simple stick figure mesh")+print("____________________________________________________________________________")+try:+ bpy.ops.object.mode_set(mode="OBJECT")+except:+ pass+put_sphere_meshes_on_empties(+ empty_names_list=mediapipe_body_trajectory_names,+ parent_object=freemocap_origin_axes,+ sphere_scale=0.02,+)++stick_figure_mesh = make_stick_figure_mesh(+ skel3d_frame_landmark_xyz=mediapipe_skel_fr_mar_xyz,+ stick_figure_mesh_edges=stick_figure_mesh_edges_list_of_lists,+ mediapipe_landmark_names=mediapipe_body_trajectory_names,+ good_clean_frame_number=good_clean_frame_number,+)++#####################+## Load nSynched Videos+try:+ print("loading videos as planes...")++ world_origin = bpy.data.objects["world_origin"]++ number_of_videos = len(list(video_folder_path.glob("*.mp4")))++ vid_location_scale = 1++ for (+ vid_number,+ thisVidPath,+ ) in enumerate(video_folder_path.glob("*.mp4")):+ print(thisVidPath)+ # use 'images as planes' add on to load in the video files as planes+ bpy.ops.import_image.to_plane(+ files=[{"name": thisVidPath.name}],+ directory=str(thisVidPath.parent),+ shader="EMISSION",+ )+ this_vid_as_plane = bpy.context.active_object+ this_vid_as_plane.name = "vid_" + str(vid_number)++ vid_x = (vid_number - number_of_videos / 2) * vid_location_scale++ this_vid_as_plane.location = [+ vid_x,+ vid_location_scale,+ vid_location_scale,+ ]+ this_vid_as_plane.rotation_euler = [np.pi / 2, 0, 0]+ this_vid_as_plane.scale = [vid_location_scale * 1.5] * 3+ this_vid_as_plane.parent = world_origin+ # create a light+ # bpy.ops.object.light_add(type='POINT', radius=1, align='WORLD')+except Exception as e:+ print(e)+ print(+ 'Failed to load videos to Blender scene - You might need to install the "images as planes" addon to this version of Blender'+ )++try:+ # from https://blender.stackexchange.com/a/238223++ for window in bpy.context.window_manager.windows:+ for area in window.screen.areas: # iterate through areas in current screen+ if area.type == "VIEW_3D":+ for (+ space+ ) in area.spaces: # iterate through spaces in current VIEW_3D area+ if space.type == "VIEW_3D": # check if space is a 3D view+ space.shading.type = "MATERIAL"+except Exception as e:+ print(e)+ print("Failed to set shading to material")++# save .blend file+sessionID = session_path.stem+blend_file_save_path = session_path / (sessionID + ".blend")++bpy.ops.wm.save_as_mainfile(filepath=str(blend_file_save_path))++print("____________________________________________________________________________")+print("____________________________________________________________________________")+print(+ "Done creating Blender scene!\n",+ f"Saved .blend file to: {blend_file_save_path}\n",+ "You can now open the `.blend` file in Blender and play the animation!\n",+)+print("____________________________________________________________________________")+print("____________________________________________________________________________")diff --git a/src/export_stuff/blender_stuff/create_blend_file_from_session_data.py b/src/blender_stuff/create_blend_file_from_session_data.pysimilarity index 76%rename from src/export_stuff/blender_stuff/create_blend_file_from_session_data.pyrename to src/blender_stuff/create_blend_file_from_session_data.pyindex 7cf39088..958954af 100644--- a/src/export_stuff/blender_stuff/create_blend_file_from_session_data.py+++ b/src/blender_stuff/create_blend_file_from_session_data.py@@ -20,10 +20,15 @@ def create_blend_file_from_session_data(good_clean_frame_number: int = 0,):path_to_this_py_file = Path(__file__).parent.resolve()+freemocap_blender_megascript_path = (path_to_this_py_file / "alpha_freemocap_blender_megascript.py")+ # freemocap_blender_megascript_path = (+ # path_to_this_py_file / "bind_rigify_meta_rig_to_freemocap_data.py"+ # )+try:blender_exe_path = Path(blender_exe_path)if not blender_exe_path.exists():@@ -34,21 +39,20 @@ def create_blend_file_from_session_data(logger.error(e)return- command_str = (- str(blender_exe_path)- + " --background"- + " --python "- + str(freemocap_blender_megascript_path)- + " -- "- + session_folder_path- + " "- + str(good_clean_frame_number)- )+ command_list = [+ str(blender_exe_path),+ "--background",+ "--python",+ str(freemocap_blender_megascript_path),+ "--",+ str(session_folder_path),+ str(good_clean_frame_number),+ ]- logger.info(f"Starting `blender` sub-process with this command: \n {command_str}")+ logger.info(f"Starting `blender` sub-process with this command: \n {command_list}")blender_process = subprocess.Popen(- command_str, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE+ command_list, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)while True:output = blender_process.stdout.readline()diff --git a/src/export_stuff/blender_stuff/export_to_blender.py b/src/blender_stuff/export_to_blender.pysimilarity index 89%rename from src/export_stuff/blender_stuff/export_to_blender.pyrename to src/blender_stuff/export_to_blender.pyindex 9650a795..026c0b74 100644--- a/src/export_stuff/blender_stuff/export_to_blender.py+++ b/src/blender_stuff/export_to_blender.py@@ -1,10 +1,8 @@-import os-from pathlib import Pathfrom typing import Union-from src.export_stuff.blender_stuff.create_blend_file_from_session_data import (+from src.blender_stuff.create_blend_file_from_session_data import (create_blend_file_from_session_data,)import loggingdiff --git a/src/blender_stuff/get_best_guess_of_blender_path.py b/src/blender_stuff/get_best_guess_of_blender_path.pynew file mode 100644index 00000000..6a5ce0b4--- /dev/null+++ b/src/blender_stuff/get_best_guess_of_blender_path.py@@ -0,0 +1,47 @@+import logging+import platform+from pathlib import Path+from typing import Union++from src.config.home_dir import os_independent_home_dir++logger = logging.getLogger(__name__)+++def guess_blender_exe_path_from_path(base_path: Union[str, Path]) -> Path:+ blender_folder_path = [path for path in base_path.glob("Blender*")]+ if len(blender_folder_path) > 0:+ blender_exe_path = blender_folder_path[0] / "blender.exe"+ return blender_exe_path++ return+++def get_best_guess_of_blender_path():+ if platform.system() == "Windows":++ base_path = Path("C:\Program Files\Blender Foundation")+ blender_exe_path = guess_blender_exe_path_from_path(base_path)++ if blender_exe_path is not None:+ if not blender_exe_path.is_file():+ base_path = Path(os_independent_home_dir()) / "Blender Foundation"+ blender_exe_path = guess_blender_exe_path_from_path(base_path)++ if blender_exe_path is not None and blender_exe_path.is_file():+ logger.info(+ f"Windows machine detected - guessing that `blender` is installed at: {str(blender_exe_path)}"+ )++ return str(blender_exe_path)+ else:+ logger.warning(+ f"Could not find `blender.exe` in the expected locations. Please located it manually (or install Blender, if it isn't installed)."+ )+ return None++ else:+ logger.info(+ f"Non-Windows machine detected - TODO - Test how this works on Mac/Linux"+ )+ return Nonediff --git a/src/blender_stuff/old/OLD_bind_mixamo_skeleton_to_freemocap_empties.py b/src/blender_stuff/old/OLD_bind_mixamo_skeleton_to_freemocap_empties.pynew file mode 100644index 00000000..b621256d--- /dev/null+++ b/src/blender_stuff/old/OLD_bind_mixamo_skeleton_to_freemocap_empties.py@@ -0,0 +1,113 @@+import bpy+++print(" - Starting (alpha) blender megascript - ")+++rig_name = "mixamorig"+rig_constraint_dict_of_dicts_og = {+ "Hips": {+ "COPY_LOCATION": "hip_center",+ "STRETCH_TO": "chest_center",+ },+ "Spine1": {+ "STRETCH_TO": "chest_center",+ },+ "RightShoulder": {+ "COPY_LOCATION": "neck_center",+ "STRETCH_TO": "right_shoulder",+ },+ "LeftShoulder": {+ "COPY_LOCATION": "neck_center",+ "STRETCH_TO": "left_shoulder",+ },+ "RightArm": {+ "STRETCH_TO": "right_elbow",+ },+ "LeftArm": {+ "STRETCH_TO": "left_elbow",+ },+ "RightForeArm": {+ "STRETCH_TO": "right_wrist",+ },+ "LeftForeArm": {+ "STRETCH_TO": "left_wrist",+ },+ "RightHand": {+ "STRETCH_TO": "left_hand_wrist",+ },+ "LeftHand": {+ "STRETCH_TO": "right_hand_wrist",+ },+ "Neck": {+ "STRETCH_TO": "head_center",+ },+ "RightUpLeg": {+ "COPY_LOCATION": "right_hip",+ "STRETCH_TO": "right_knee",+ },+ "LeftUpLeg": {+ "COPY_LOCATION": "left_hip",+ "STRETCH_TO": "left_knee",+ },+ "RightLeg": {+ "STRETCH_TO": "right_ankle",+ },+ "LeftLeg": {+ "STRETCH_TO": "left_ankle",+ },+ "RightFoot": {+ "DAMPED_TRACK": "right_foot_index",+ },+ "LeftFoot": {+ "DAMPED_TRACK": "left_foot_index",+ },+ "RightToeBase": {+ "STRETCH_TO": "right_foot_index",+ },+ "LeftToeBase": {+ "STRETCH_TO": "left_foot_index",+ },+ "Head": {+ "COPY_LOCATION": "head_center",+ "DAMPED_TRACK": "head_center",+ },+}+++### Pre-pend `rig_name` or whatever to bone names+rig_constraint_dict_of_dicts = {}+for key in rig_constraint_dict_of_dicts_og.keys():+ rig_constraint_dict_of_dicts[f"{rig_name}{key}"] = rig_constraint_dict_of_dicts_og[+ key+ ]++####+#### Constrain bones to empties+####+armature_name = "Armature"+armature = bpy.data.objects[armature_name]+# loop through dictionary applying constraints+try:+ bpy.ops.object.mode_set(mode="POSE")+except:+ pass++for this_bone_name, this_bone_dict in rig_constraint_dict_of_dicts.items():+ print(f"---Setting constraints for bone:{this_bone_name}---")++ for (+ this_constraint_name,+ this_constraint_target_empty_name,+ ) in this_bone_dict.items():+ print(+ f"constraint: {this_constraint_name} with target:{this_constraint_target_empty_name}"+ )+ print("grab bone")+ this_bone = armature.pose.bones[this_bone_name]+ print("apply bone")+ this_constraint = this_bone.constraints.new(type=this_constraint_name)+ this_constraint.name = this_constraint_name+ this_constraint.target = bpy.data.objects[+ this_constraint_target_empty_name+ ] # point constraint at relevant empty objectdiff --git a/src/export_stuff/blender_stuff/__init__.py b/src/blender_stuff/old/__init__.pysimilarity index 100%rename from src/export_stuff/blender_stuff/__init__.pyrename to src/blender_stuff/old/__init__.pydiff --git a/src/blender_stuff/old/bind_mixamo_rig_to_freemocap_mocap_data.py b/src/blender_stuff/old/bind_mixamo_rig_to_freemocap_mocap_data.pynew file mode 100644index 00000000..d44a0d22--- /dev/null+++ b/src/blender_stuff/old/bind_mixamo_rig_to_freemocap_mocap_data.py@@ -0,0 +1,445 @@+import bpy+import numpy as np+from pathlib import Path+import json++#####################################################################+###%% clear the scene - Scorch the earth \o/+print("clearing scene")+try:+ bpy.ops.object.mode_set(mode="OBJECT")+except:+ pass++try:+ bpy.ops.object.select_all(action="SELECT") # select all objects+ bpy.ops.object.delete(use_global=True) # delete all objects from all scenes+except:+ pass++##################+### Getcher paths straight+path_to_data_folder = Path("/Users/jon/Dropbox/FreeMoCapProject/FreeMocap_Data/")+# path_to_data_folder = Path("D:\Dropbox\FreeMoCapProject\FreeMocap_Data")++session_id = "sesh_2022-09-19_16_16_50_in_class_jsm"++session_path = path_to_data_folder / session_id+path_to_data_arrays_folder = session_path / "DataArrays"+path_to_body_npy = path_to_data_arrays_folder / "mediapipe_body_3d_xyz.npy"++annotated_videos_path = session_path / "annotated_videos"++if annotated_videos_path.is_dir():+ vidFolderPath = annotated_videos_path+else:+ vidFolderPath = session_path / "synchronized_videos"++path_to_segment_length_json = (+ path_to_data_arrays_folder / "skeleton_segment_lengths.json"+)+print(f" json path - {str(path_to_segment_length_json)}")+f = open(path_to_segment_length_json)+skeleton_segment_lengths_dict = json.load(f)++path_to_mixamo_fbx = r"/Users/jon/Dropbox/FreeMoCapProject/teddy_animation/mixamo_binding_stuff/mixamo_mannequin_fbx_Ch36_nonPBR.fbx"+# path_to_mixamo_fbx = r"D:\Dropbox\FreeMoCapProject\teddy_animation\mixamo_binding_stuff\mixamo_mannequin_fbx_Ch36_nonPBR.fbx"++#########################+### Create Origin Axes++bpy.ops.object.empty_add(type="ARROWS")+world_origin_axes = bpy.context.active_object+world_origin_axes.name = "world_origin" # will stay at origin++bpy.ops.object.empty_add(type="ARROWS")+freemocap_origin_axes = bpy.context.active_object+freemocap_origin_axes.name = "freemocap_origin_axes" # will translate to put skelly on ground symmetric-ish about origin++#####################+## Load nSynched Videos+try:+ print("loading videos as planes...")++ world_origin = bpy.data.objects["world_origin"]++ number_of_videos = len(list(vidFolderPath.glob("*.mp4")))++ vid_location_scale = 1++ for (+ vid_number,+ thisVidPath,+ ) in enumerate(vidFolderPath.glob("*.mp4")):+ print(thisVidPath)+ # use 'images as planes' add on to load in the video files as planes+ bpy.ops.import_image.to_plane(+ files=[{"name": thisVidPath.name}],+ directory=str(thisVidPath.parent),+ shader="EMISSION",+ )+ this_vid_as_plane = bpy.context.active_object+ this_vid_as_plane.name = "vid_" + str(vid_number)++ vid_x = (vid_number - number_of_videos / 2) * vid_location_scale++ this_vid_as_plane.location = [+ vid_x,+ vid_location_scale,+ vid_location_scale,+ ]+ this_vid_as_plane.rotation_euler = [np.pi / 2, 0, 0]+ this_vid_as_plane.scale = [vid_location_scale * 1.5] * 3+ this_vid_as_plane.parent = world_origin+ # create a light+ # bpy.ops.object.light_add(type='POINT', radius=1, align='WORLD')+except Exception as e:+ print(e)+ print(+ 'Failed to load videos to Blender scene - You might need to install the "images as planes" addon to this version of Blender'+ )++############+## Mediapipe Tracked Point Names+++mediapipe_body_names = [+ "nose",+ "left_eye_inner",+ "left_eye",+ "left_eye_outer",+ "right_eye_inner",+ "right_eye",+ "right_eye_outer",+ "left_ear",+ "right_ear",+ "mouth_left",+ "mouth_right",+ "left_shoulder",+ "right_shoulder",+ "left_elbow",+ "right_elbow",+ "left_wrist",+ "right_wrist",+ "left_pinky",+ "right_pinky",+ "left_index",+ "right_index",+ "left_thumb",+ "right_thumb",+ "left_hip",+ "right_hip",+ "left_knee",+ "right_knee",+ "left_ankle",+ "right_ankle",+ "left_heel",+ "right_heel",+ "left_foot_index",+ "right_foot_index",+]++#######################################################################+# %% load mediapipe data+# %%+print("loading data")+# %%+++mediapipe_skel_fr_mar_dim = np.load(str(path_to_body_npy))+mediapipe_skel_fr_mar_dim = mediapipe_skel_fr_mar_dim / 1000 # convert to meters++print(f"mediapipe_skel_fr_mar_dim.shape: {mediapipe_skel_fr_mar_dim.shape}")++##############################+# %% Set start and end frames+number_of_frames = mediapipe_skel_fr_mar_dim.shape[0]+start_frame = 1+end_frame = number_of_frames++bpy.context.scene.frame_start = start_frame+bpy.context.scene.frame_end = end_frame++############################+### Load body data as empty markers+++empty_size = 0.01++for this_point_index, this_point_name in enumerate(mediapipe_body_names):+ print(f"loading {this_point_name}...")+ bpy.ops.object.empty_add(type="SPHERE")+ this_empty = bpy.context.active_object+ this_empty.name = this_point_name++ this_empty.scale = [empty_size] * 3++ this_empty.parent = freemocap_origin_axes++ this_point_fr_xyz = mediapipe_skel_fr_mar_dim[:, this_point_index, :]++ for frame_num in range(end_frame):+ this_empty.location = [+ this_point_fr_xyz[frame_num, 0],+ this_point_fr_xyz[frame_num, 1],+ this_point_fr_xyz[frame_num, 2],+ ]+ bpy.context.view_layer.update()++ this_empty.keyframe_insert(data_path="location", frame=frame_num)++#######################################################################+# %% create virtual markers+print("creating virtual markers")++left_ear_index = 7+right_ear_index = 8+print("head_center - midway between left and right ears")+head_xyz = (+ mediapipe_skel_fr_mar_dim[:, left_ear_index, :]+ + mediapipe_skel_fr_mar_dim[:, right_ear_index, :]+) / 2+bpy.ops.object.empty_add(type="SPHERE")+this_empty = bpy.context.active_object+this_empty.name = "head_center"+this_empty.scale = [empty_size] * 3+this_empty.parent = freemocap_origin_axes++for frame_num in range(end_frame):+ this_empty.location = [+ head_xyz[frame_num, 0],+ head_xyz[frame_num, 1],+ head_xyz[frame_num, 2],+ ]+ this_empty.keyframe_insert(data_path="location", frame=frame_num)++print("neck_center - midway between left and right shoulders")+left_shoulder_index = 11+right_shoulder_index = 12+neck_xyz = (+ mediapipe_skel_fr_mar_dim[:, left_shoulder_index, :]+ + mediapipe_skel_fr_mar_dim[:, right_shoulder_index, :]+) / 2+bpy.ops.object.empty_add(type="PLAIN_AXES")+this_empty = bpy.context.active_object+this_empty.name = "neck_center"+this_empty.scale = [empty_size] * 3+this_empty.parent = freemocap_origin_axes++for frame_num in range(end_frame):+ this_empty.location = [+ neck_xyz[frame_num, 0],+ neck_xyz[frame_num, 1],+ neck_xyz[frame_num, 2],+ ]+ this_empty.keyframe_insert(data_path="location", frame=frame_num)++print("hip_center - midway between left and right hips")+left_hip_index = 23+right_hip_index = 24+hips_xyz = (+ mediapipe_skel_fr_mar_dim[:, left_hip_index, :]+ + mediapipe_skel_fr_mar_dim[:, right_hip_index, :]+) / 2+bpy.ops.object.empty_add(type="PLAIN_AXES")+this_empty = bpy.context.active_object+this_empty.name = "hip_center"+this_empty.scale = [empty_size] * 3+this_empty.parent = freemocap_origin_axes++for frame_num in range(end_frame):+ this_empty.location = [+ hips_xyz[frame_num, 0],+ hips_xyz[frame_num, 1],+ hips_xyz[frame_num, 2],+ ]+ this_empty.keyframe_insert(data_path="location", frame=frame_num)++print("chest_center - midway between hips and neck centers")++chest_xyz = (hips_xyz + neck_xyz) / 2+bpy.ops.object.empty_add(type="PLAIN_AXES")+this_empty = bpy.context.active_object+this_empty.name = "chest_center"+this_empty.scale = [empty_size] * 3+this_empty.parent = freemocap_origin_axes++for frame_num in range(end_frame):+ this_empty.location = [+ chest_xyz[frame_num, 0],+ chest_xyz[frame_num, 1],+ chest_xyz[frame_num, 2],+ ]+ this_empty.keyframe_insert(data_path="location", frame=frame_num)++######################+### Load Mixamo Armature+print(f"Loading Mixamo rigged mesh from: {path_to_mixamo_fbx}")+bpy.ops.import_scene.fbx(filepath=path_to_mixamo_fbx, use_anim=False)+bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)+armature_name = "Armature"+armature = bpy.data.objects[armature_name]++freemocap_origin_axes.rotation_euler[2] = np.pi+##################+### Scale armature++rig_name = "mixamorig1"+mixamo_bone_to_skeleton_segment_name_correspondance = {+ "lower_spine": ["Hips", "Spine"],+ "upper_spine": ["Spine1", "Spine2"],+ "head": ["Neck", "Head"],+ "left_upper_arm": ["LeftArm"],+ "left_forearm": ["LeftForeArm"],+ "left_hand": ["LeftHand"],+ "right_upper_arm": ["RightArm"],+ "right_forearm": ["RightForeArm"],+ "right_hand": ["RightHand"],+ "left_thigh": ["LeftUpLeg"],+ "left_calf": ["LeftLeg"],+ "left_foot": ["LeftFoot"],+ "right_thigh": ["RightUpLeg"],+ "right_calf": ["RightLeg"],+ "right_foot": ["RightFoot"],+}++try:+ bpy.ops.object.mode_set(mode="EDIT")+except:+ pass++for (+ segment_name,+ mixamo_bones_list,+) in mixamo_bone_to_skeleton_segment_name_correspondance.items():+ print(+ f"segment: {segment_name}, length: {skeleton_segment_lengths_dict[segment_name]['median']}mm"+ )++ for mixamo_bone in mixamo_bones_list:+ segment_length = (+ skeleton_segment_lengths_dict[segment_name]["median"]+ / len(mixamo_bones_list)+ ) * 0.001+ print(f"setting: {mixamo_bone} length to: {segment_length} m")+ armature.data.edit_bones[f"{rig_name}:{mixamo_bone}"].length = segment_length++ ####################+#### get segment lengths++########################+### Constrain mixamo bones to track empty locations+++rig_constraint_dict_of_dicts_og = {+ "Hips": {+ "COPY_LOCATION": "hip_center",+ },+ "Spine": {+ "IK": "chest_center",+ },+ "Spine1": {+ "COPY_LOCATION": "chest_center",+ },+ "Spine2": {+ "IK": "neck_center",+ },+ "Neck": {+ "COPY_LOCATION": "neck_center",+ },+ "Head": {+ "IK": "head_center",+ },+ "RightShoulder": {+ "COPY_LOCATION": "neck_center",+ "DAMPED_TRACK": "right_shoulder",+ },+ "RightArm": {+ "COPY_LOCATION": "right_shoulder",+ "DAMPED_TRACK": "right_elbow",+ },+ "RightForeArm": {+ "COPY_LOCATION": "right_elbow",+ "DAMPED_TRACK": "right_wrist",+ },+ "RightHand": {+ "COPY_LOCATION": "right_wrist",+ "DAMPED_TRACK": "right_index",+ },+ "LeftShoulder": {+ "COPY_LOCATION": "neck_center",+ "DAMPED_TRACK": "left_shoulder",+ },+ "LeftArm": {+ "COPY_LOCATION": "left_shoulder",+ "DAMPED_TRACK": "left_elbow",+ },+ "LeftForeArm": {+ "COPY_LOCATION": "left_elbow",+ "DAMPED_TRACK": "left_wrist",+ },+ "LeftHand": {+ "COPY_LOCATION": "left_wrist",+ "DAMPED_TRACK": "left_index",+ },+ "RightUpLeg": {+ "COPY_LOCATION": "right_hip",+ "DAMPED_TRACK": "right_knee",+ },+ "RightLeg": {+ "COPY_LOCATION": "right_knee",+ "DAMPED_TRACK": "right_ankle",+ },+ "RightFoot": {+ "COPY_LOCATION": "right_ankle",+ "DAMPED_TRACK": "right_foot_index",+ },+ "LeftUpLeg": {+ "COPY_LOCATION": "left_hip",+ "DAMPED_TRACK": "left_knee",+ },+ "LeftLeg": {+ "COPY_LOCATION": "left_knee",+ "DAMPED_TRACK": "left_ankle",+ },+ "LeftFoot": {+ "COPY_LOCATION": "left_ankle",+ "DAMPED_TRACK": "left_foot_index",+ },+}++### Pre-pend `rig_name` or whatever to bone names+rig_constraint_dict_of_dicts = {}+for key in rig_constraint_dict_of_dicts_og.keys():+ rig_constraint_dict_of_dicts[f"{rig_name}:{key}"] = rig_constraint_dict_of_dicts_og[+ key+ ]++####+#### Constrain bones to empties+####++# loop through dictionary applying constraints+try:+ bpy.ops.object.mode_set(mode="POSE")+except:+ pass++for this_bone_name, this_bone_dict in rig_constraint_dict_of_dicts.items():+ print(f"---Setting constraints for bone:{this_bone_name}---")++ for (+ this_constraint_name,+ this_constraint_target_empty_name,+ ) in this_bone_dict.items():+ print(+ f"constraint: {this_constraint_name} with target:{this_constraint_target_empty_name}"+ )+ print("grab bone")+ this_bone = armature.pose.bones[this_bone_name]+ print("apply bone")+ this_constraint = this_bone.constraints.new(type=this_constraint_name)+ this_constraint.name = this_constraint_name+ this_constraint.target = bpy.data.objects[+ this_constraint_target_empty_name+ ] # point constraint at relevant empty objectdiff --git a/src/cameras/capture/opencv_camera/opencv_camera.py b/src/cameras/capture/opencv_camera/opencv_camera.pyindex 42563c41..a5a5c37b 100644--- a/src/cameras/capture/opencv_camera/opencv_camera.py+++ b/src/cameras/capture/opencv_camera/opencv_camera.py@@ -3,17 +3,15 @@ import loggingimport platformimport timeimport traceback-from typing import List, Unionimport cv2from src.cameras.capture.dataclasses.frame_payload import FramePayloadfrom src.cameras.viewer.cv_cam_viewer import CvCamViewer-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigfrom src.cameras.capture.opencv_camera.camera_stream_thread_handler import (VideoCaptureThread,)-from src.core_processes.timestamp_manager.timestamp_manager import TimestampLoggerlogger = logging.getLogger(__name__)diff --git a/src/cameras/launch_camera_frame_loop.py b/src/cameras/launch_camera_frame_loop.pyindex ec64a834..3731bd11 100644--- a/src/cameras/launch_camera_frame_loop.py+++ b/src/cameras/launch_camera_frame_loop.py@@ -6,7 +6,7 @@ import tracebackimport cv2from src.cameras.multicam_manager.cv_camera_manager import OpenCVCameraManager-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigfrom src.core_processes.show_cam_window import show_cam_windowfrom src.core_processes.utils.image_fps_writer import write_fps_to_imagediff --git a/src/cameras/multicam_manager/cv_camera_manager.py b/src/cameras/multicam_manager/cv_camera_manager.pyindex c925a4c2..a8d19949 100644--- a/src/cameras/multicam_manager/cv_camera_manager.py+++ b/src/cameras/multicam_manager/cv_camera_manager.py@@ -4,17 +4,15 @@ import tracebackfrom contextlib import contextmanagerfrom typing import ContextManager, Dict, List, Optional, Union-import numpy as npfrom pydantic import BaseModelfrom src.api.services.user_config import UserConfigServicefrom 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 VideoRecorder-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigfrom src.core_processes.timestamp_manager.timestamp_manager import (TimestampManager,- TimestampLogger,)from src.pipelines.session_pipeline.data_classes.multi_frame_payload import (MultiFramePayload,diff --git a/src/cameras/persistence/video_writer/video_recorder.py b/src/cameras/persistence/video_writer/video_recorder.pyindex 40046e02..8ec5f02a 100644--- a/src/cameras/persistence/video_writer/video_recorder.py+++ b/src/cameras/persistence/video_writer/video_recorder.py@@ -1,5 +1,4 @@import logging-import osimport tracebackfrom pathlib import Pathfrom typing import List, Union@@ -9,9 +8,6 @@ import numpy as npimport pandas as pdfrom src.cameras.capture.dataclasses.frame_payload import FramePayload-from src.cameras.create_timestamp_diagnostic_plots import (- create_timestamp_diagnostic_plots,-)logger = logging.getLogger(__name__)diff --git a/src/cameras/save_synchronized_videos.py b/src/cameras/save_synchronized_videos.pyindex ccc2a6a6..ee439479 100644--- a/src/cameras/save_synchronized_videos.py+++ b/src/cameras/save_synchronized_videos.py@@ -4,11 +4,11 @@ from typing import List, Union, Dictimport numpy as npfrom src.cameras.capture.dataclasses.frame_payload import FramePayload-from src.cameras.create_timestamp_diagnostic_plots import (+from src.config.home_dir import DIAGNOSTIC_PLOTS_FOLDER_NAME+from src.diagnostic_plot_makers.create_timestamp_diagnostic_plots import (create_timestamp_diagnostic_plots,)from src.cameras.persistence.video_writer.video_recorder import VideoRecorder-from src.gui.icis_conference_main.state.app_state import APP_STATEimport logging@@ -103,10 +103,13 @@ def save_synchronized_videos(/ f"Camera_{str(camera_id).zfill(3)}.mp4",)+ diagnostic_plot_folder = Path(folder_to_save_videos) / DIAGNOSTIC_PLOTS_FOLDER_NAME+ diagnostic_plot_folder.mkdir(parents=True, exist_ok=True)+ path_to_save_plots = diagnostic_plot_folder / "timestamp_diagnostic_plots.png"create_timestamp_diagnostic_plots(each_cam_raw_frame_list,each_cam_synchronized_frame_list,- Path(folder_to_save_videos) / f"timestamp_synchronization_diagnostic_plots.png",+ path_to_save_plots,)diff --git a/src/config/webcam_config.py b/src/cameras/webcam_config.pysimilarity index 100%rename from src/config/webcam_config.pyrename to src/cameras/webcam_config.pydiff --git a/src/config/home_dir.py b/src/config/home_dir.pyindex e149953e..0a645f29 100644--- a/src/config/home_dir.py+++ b/src/config/home_dir.py@@ -6,18 +6,41 @@ import tomllogger = logging.getLogger(__name__)+# directory namesBASE_FOLDER_NAME = "freemocap_data"LOG_FILE_FOLDER_NAME = "logs"SYNCHRONIZED_VIDEOS_FOLDER_NAME = "synchronized_videos"CALIBRATION_VIDEOS_FOLDER_NAME = "calibration_videos"ANNOTATED_VIDEOS_FOLDER_NAME = "annotated_videos"OUTPUT_DATA_FOLDER_NAME = "output_data"+RAW_DATA_FOLDER_NAME = "raw_data"+CENTER_OF_MASS_FOLDER_NAME = "center_of_mass"+PARTIALLY_PROCESSED_DATA_FOLDER_NAME = "partially_processed_data"+DIAGNOSTIC_PLOTS_FOLDER_NAME = "diagnostic_plots"++# file namesMOST_RECENT_SESSION_ID_FILENAME = "most_recent_session_id.toml"CAMERA_CALIBRATION_FILE_NAME = "camera_calibration_data.toml"+MEDIAPIPE_2D_NPY_FILE_NAME = (+ "mediapipe_2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"+)+MEDIAPIPE_3D_NPY_FILE_NAME = (+ "mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"+)+MEDIAPIPE_REPROJECTION_ERROR_NPY_FILE_NAME = (+ "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"+)++SKELETON_BODY_CSV_FILE_NAME = "mediapipe_body_3d_xyz.csv"++SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME = "segmentCOM_frame_joint_xyz.npy"++TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME = "total_body_center_of_mass_xyz.npy"+MEDIAPIPE_3D_ORIGIN_ALIGNED_NPY_FILE_NAME = "mediaPipeSkel_3d_origin_aligned.npy"def create_default_session_id(string_tag: str = None):- session_id = "session_" + time.strftime("%m-%d-%Y-%H_%M_%S")+ session_id = "session_" + time.strftime("%Y-%m-%d-%H_%M_%S")if string_tag is not None:session_id = session_id + "_" + string_tag@@ -122,8 +145,30 @@ def get_output_data_folder_path(session_id: str, create_folder: bool = True):return str(output_data_folder_path)+def get_raw_data_folder_path(session_id: str, create_folder: bool = True):+ output_data_folder_path = (+ Path(get_session_folder_path(session_id)) / OUTPUT_DATA_FOLDER_NAME+ )+ raw_data_folder_path = output_data_folder_path / RAW_DATA_FOLDER_NAME+ if create_folder:+ raw_data_folder_path.mkdir(exist_ok=create_folder, parents=True)+ return str(raw_data_folder_path)+def get_session_calibration_toml_file_path(session_id: str) -> str:calibration_file_path = (Path(get_session_folder_path(session_id)) / CAMERA_CALIBRATION_FILE_NAME)return str(calibration_file_path)+++def get_skeleton_body_csv_path(session_id: str) -> str:+ skeleton_body_data_path = (+ Path(get_output_data_folder_path(session_id)) / SKELETON_BODY_CSV_FILE_NAME+ )+ return str(skeleton_body_data_path)+++def get_blender_file_path(session_id: str) -> str:+ blend_file_name = session_id + ".blend"+ blender_file_path = Path(get_output_data_folder_path(session_id)) / blend_file_name+ return str(blender_file_path)diff --git a/src/core_processes/batch_processing/__init__.py b/src/core_processes/batch_processing/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/core_processes/batch_processing/batch_process_session_folders.py b/src/core_processes/batch_processing/batch_process_session_folders.pynew file mode 100644index 00000000..2875247c--- /dev/null+++ b/src/core_processes/batch_processing/batch_process_session_folders.py@@ -0,0 +1,107 @@+import logging+from pathlib import Path+from typing import Union, Any, Dict+from rich.pretty import pprint++from src.core_processes.batch_processing.process_session_folder import (+ process_session_folder,+)+from src.core_processes.batch_processing.session_processing_parameter_models import (+ SessionProcessingParameterModel,+)+from src.core_processes.capture_volume_calibration.anipose_camera_calibration import (+ freemocap_anipose,+)++logger = logging.getLogger(__name__)+++def batch_process_session_folders(+ path_to_folder_of_session_folders: Union[str, Path],+ path_to_camera_calibration_toml: Union[str, Path],+ path_to_blender_executable: Union[str, Path],+):+ """+ Process a folder full of session folders.++ Parameters+ ----------+ path_to_folder_of_session_folders : Union[str, Path]+ Path to folder full of session folders.+ path_to_camera_calibration_toml : Union[str, Path]+ Path to camera calibration toml file.+ path_to_blender_executable : Union[str, Path]+ Path to a Blender executable.++ """++ for session_folder_path in Path(path_to_folder_of_session_folders).iterdir():+ if not session_folder_path.is_dir():+ continue++ logger.info(f"Processing session folder: {session_folder_path}")+ if Path(+ session_folder_path / "synchronized_videos"+ ).exists(): # session was recorded freemocap version > v0.0.54 (aka `alpha`)+ synchronized_videos_folder = (+ Path(session_folder_path) / "synchronized_videos"+ )++ if Path(+ session_folder_path / "SyncedVideos"+ ).exists(): # session was recorded with freemocap version <= v0.0.54 (aka `pre-alpha`)+ synchronized_videos_folder = Path(session_folder_path) / "SyncedVideos"+ else:+ print(+ f"No folder full of synchronized videos found for {session_folder_path}"+ )+ raise FileNotFoundError++ anipose_calibration_object = freemocap_anipose.CameraGroup.load(+ str(path_to_camera_calibration_toml)+ )++ output_data_folder = Path(session_folder_path) / "output_data"+ output_data_folder.mkdir(exist_ok=True, parents=True)++ session_processing_parameter_model = SessionProcessingParameterModel(+ path_to_session_folder=session_folder_path,+ path_to_output_data_folder=output_data_folder,+ path_to_folder_of_synchronized_videos=synchronized_videos_folder,+ anipose_calibration_object=anipose_calibration_object,+ path_to_blender_executable=path_to_blender_executable,+ )++ session_processing_parameter_model.anipose_triangulate_3d_parameters.use_triangulate_ransac_method = (+ False+ )++ session_processing_parameter_model.start_processing_at_stage = 0++ pprint(session_processing_parameter_model.dict(), expand_all=True)++ process_session_folder(session_processing_parameter_model)+++if __name__ == "__main__":++ path_to_folder_of_session_folders = Path(+ r"H:\My Drive\Biol2299_Fall2022\partially_processed\FreeMocap_Data"+ )+ # path_to_folder_of_session_folders = Path(+ # r"H:\My Drive\Biol2299_Fall2022\done_needs_checking"+ # )++ path_to_camera_calibration_toml = Path(+ r"H:\My Drive\Biol2299_Fall2022\calibration_recordings\sesh_2022-09-28_15_57_08_calibration\sesh_2022-09-28_15_57_08_calibration_calibration.toml"+ )++ path_to_blender_executable = Path(+ r"C:\Program Files\Blender Foundation\Blender 3.2\blender.exe"+ )++ batch_process_session_folders(+ path_to_folder_of_session_folders=path_to_folder_of_session_folders,+ path_to_camera_calibration_toml=path_to_camera_calibration_toml,+ path_to_blender_executable=path_to_blender_executable,+ )diff --git a/src/core_processes/batch_processing/process_session_folder.py b/src/core_processes/batch_processing/process_session_folder.pynew file mode 100644index 00000000..a12babc4--- /dev/null+++ b/src/core_processes/batch_processing/process_session_folder.py@@ -0,0 +1,252 @@+import logging+from pathlib import Path++import numpy as np+import pandas as pd++from src.blender_stuff.create_blend_file_from_session_data import (+ create_blend_file_from_session_data,+)+from src.config.home_dir import (+ MEDIAPIPE_2D_NPY_FILE_NAME,+ MEDIAPIPE_REPROJECTION_ERROR_NPY_FILE_NAME,+ MEDIAPIPE_3D_NPY_FILE_NAME,+ RAW_DATA_FOLDER_NAME,+)+from src.core_processes.capture_volume_calibration.anipose_camera_calibration import (+ freemocap_anipose,+)+from src.core_processes.capture_volume_calibration.triangulate_3d_data import (+ triangulate_3d_data,+)+from src.core_processes.mediapipe_stuff.convert_mediapipe_npy_to_csv import (+ convert_mediapipe_npy_to_csv,+)+from src.core_processes.mediapipe_stuff.mediapipe_skeleton_detector import (+ MediaPipeSkeletonDetector,+)+from src.core_processes.post_process_skeleton_data.estimate_skeleton_segment_lengths import (+ estimate_skeleton_segment_lengths,+ mediapipe_skeleton_segment_definitions,+ save_skeleton_segment_lengths_to_json,+)+from src.core_processes.post_process_skeleton_data.gap_fill_filter_and_origin_align_skeleton_data import (+ gap_fill_filter_origin_align_3d_data_and_then_calculate_center_of_mass,+)+from src.core_processes.batch_processing.session_processing_parameter_models import (+ SessionProcessingParameterModel,+)+from src.tests.test_mediapipe_data import (+ test_mediapipe_2d_data,+ test_mediapipe_3d_data,+)++logger = logging.getLogger(__name__)+++def process_session_folder(+ session_processing_parameter_model: SessionProcessingParameterModel,+):+ """+ Process a single session folder.++ Parameters+ ----------+ session_processing_parameter_model : SessionProcessingParameterModel+ SessionProcessingParameterModel object (contains all the paths and parameters necessary to process a session folder++ """++ s = session_processing_parameter_model # make it smol++ if s.start_processing_at_stage <= 0:+ if not Path(s.path_to_folder_of_synchronized_videos).exists():+ raise FileNotFoundError(+ f"Could not find synchronized_videos folder at {synchronized_videos_folder}"+ )++ logger.info("Detecting 2d skeletons...")+ # 2d skeleton detection+ mediapipe_skeleton_detector = MediaPipeSkeletonDetector(+ parameter_model=s.mediapipe_2d_parameters,+ )++ mediapipe_2d_data = mediapipe_skeleton_detector.process_folder_full_of_videos(+ s.path_to_folder_of_synchronized_videos,+ s.path_to_output_data_folder / RAW_DATA_FOLDER_NAME,+ )++ assert test_mediapipe_2d_data(+ s.path_to_folder_of_synchronized_videos,+ s.path_to_output_data_folder / RAW_DATA_FOLDER_NAME,+ mediapipe_2d_data,+ )++ if s.start_processing_at_stage <= 1:+ logger.info("Triangulating 3d skeletons...")++ if s.start_processing_at_stage > 0:+ try:+ mediapipe_2d_data = np.load(+ s.path_to_output_data_folder / MEDIAPIPE_2D_NPY_FILE_NAME+ )+ except FileNotFoundError:+ mediapipe_2d_data = np.load(+ s.path_to_output_data_folder / "mediaPipeData_2d.npy"+ )+ assert test_mediapipe_2d_data(+ s.path_to_folder_of_synchronized_videos,+ s.path_to_output_data_folder,+ mediapipe_2d_data,+ )++ (+ raw_skel3d_frame_marker_xyz,+ skeleton_reprojection_error_fr_mar,+ ) = triangulate_3d_data(+ anipose_calibration_object=s.anipose_calibration_object,+ mediapipe_2d_data=mediapipe_2d_data,+ output_data_folder_path=Path(s.path_to_output_data_folder)+ / RAW_DATA_FOLDER_NAME,+ mediapipe_confidence_cutoff_threshold=s.anipose_triangulate_3d_parameters.confidence_threshold_cutoff,+ use_triangulate_ransac=s.anipose_triangulate_3d_parameters.use_triangulate_ransac_method,+ )++ assert test_mediapipe_3d_data(+ s.path_to_folder_of_synchronized_videos,+ Path(s.path_to_output_data_folder) / RAW_DATA_FOLDER_NAME,+ raw_skel3d_frame_marker_xyz,+ skeleton_reprojection_error_fr_mar,+ )++ if s.start_processing_at_stage <= 2:+ logger.info(+ "Gap-filling, butterworth filtering, origin aligning 3d skeletons, then calculating center of mass ..."+ )++ if s.start_processing_at_stage > 1:+ try:+ raw_skel3d_frame_marker_xyz = np.load(+ str(+ Path(s.path_to_output_data_folder)+ / RAW_DATA_FOLDER_NAME+ / MEDIAPIPE_3D_NPY_FILE_NAME+ )+ )+ skeleton_reprojection_error_fr_mar = np.load(+ str(+ Path(s.path_to_output_data_folder)+ / RAW_DATA_FOLDER_NAME+ / MEDIAPIPE_REPROJECTION_ERROR_NPY_FILE_NAME+ )+ )+ except:+ raise FileNotFoundError(+ f"Could not find 3d data at {s.path_to_output_data_folder}"+ )++ assert test_mediapipe_3d_data(+ s.path_to_folder_of_synchronized_videos,+ Path(s.path_to_output_data_folder) / RAW_DATA_FOLDER_NAME,+ raw_skel3d_frame_marker_xyz,+ skeleton_reprojection_error_fr_mar,+ )++ skel3d_frame_marker_xyz = gap_fill_filter_origin_align_3d_data_and_then_calculate_center_of_mass(+ skel3d_frame_marker_xyz=raw_skel3d_frame_marker_xyz,+ skeleton_reprojection_error_fr_mar=skeleton_reprojection_error_fr_mar,+ path_to_folder_where_we_will_save_this_data=s.path_to_output_data_folder,+ sampling_rate=s.post_processing_parameters.framerate,+ cut_off=s.post_processing_parameters.butterworth_filter_parameters.cutoff_frequency,+ order=s.post_processing_parameters.butterworth_filter_parameters.order,+ reference_frame_number=None,+ )++ logger.info(+ "Breaking up big `npy` into smaller bits and converting to `csv`..."+ )+ # break up big NPY and save out csv's+ convert_mediapipe_npy_to_csv(+ mediapipe_3d_frame_trackedPoint_xyz=skel3d_frame_marker_xyz,+ output_data_folder_path=s.path_to_output_data_folder,+ )++ if s.start_processing_at_stage <= 3:+ logger.info("Creating Blender animation from motion capture data...")+ # export to Blender+ path_to_skeleton_body_csv = (+ s.path_to_output_data_folder / "mediapipe_body_3d_xyz.csv"+ )+ skeleton_dataframe = pd.read_csv(path_to_skeleton_body_csv)++ logger.info("Estimating skeleton segment lengths...")+ skeleton_segment_lengths_dict = estimate_skeleton_segment_lengths(+ skeleton_dataframe=skeleton_dataframe,+ skeleton_segment_definitions=mediapipe_skeleton_segment_definitions,+ )++ save_skeleton_segment_lengths_to_json(+ s.path_to_output_data_folder, skeleton_segment_lengths_dict+ )++ logger.info("Starting Blender output sub-process...")+ create_blend_file_from_session_data(+ session_folder_path=Path(s.path_to_folder_of_synchronized_videos).parent,+ blender_exe_path=s.path_to_blender_executable,+ )+++if __name__ == "__main__":++ from rich.pretty import pprint++ session_folder_path = Path(+ r"H:\My Drive\Biol2299_Fall2022\com_vs_bos_posture_data\sesh_2022-09-28_15_52_24_bbbbbb"+ )++ path_to_camera_calibration_toml = Path(+ r"H:\My Drive\Biol2299_Fall2022\calibration_recordings\sesh_2022-09-28_15_39_31_calibration\sesh_2022-09-28_15_39_31_calibration.toml"+ )++ path_to_blender_executable = Path(+ r"C:\Program Files\Blender Foundation\Blender 3.2\blender.exe"+ )++ anipose_calibration_object = freemocap_anipose.CameraGroup.load(+ str(path_to_camera_calibration_toml)+ )++ if Path(+ session_folder_path / "synchronized_videos"+ ).exists(): # freemocap version > v0.0.54 (aka `alpha`)+ synchronized_videos_folder = Path(session_folder_path) / "synchronized_videos"+ elif Path(+ session_folder_path / "SyncedVideos"+ ).exists(): # freemocap version <= v0.0.54 (aka `pre-alpha`)+ synchronized_videos_folder = Path(session_folder_path) / "SyncedVideos"+ else:+ print(f"No folder full of synchronized videos found for {session_folder_path}")+ raise FileNotFoundError++ output_data_folder = Path(session_folder_path) / "output_data"+ output_data_folder.mkdir(exist_ok=True, parents=True)++ session_processing_parameter_model = SessionProcessingParameterModel(+ path_to_session_folder=session_folder_path,+ path_to_output_data_folder=output_data_folder,+ path_to_folder_of_synchronized_videos=synchronized_videos_folder,+ anipose_calibration_object=anipose_calibration_object,+ path_to_blender_executable=path_to_blender_executable,+ )++ session_processing_parameter_model.anipose_triangulate_3d_parameters.use_triangulate_ransac_method = (+ False+ )++ session_processing_parameter_model.start_processing_at_stage = 2++ pprint(session_processing_parameter_model.dict(), expand_all=True)++ process_session_folder(session_processing_parameter_model)++ print("Done!")diff --git a/src/core_processes/batch_processing/session_processing_parameter_models.py b/src/core_processes/batch_processing/session_processing_parameter_models.pynew file mode 100644index 00000000..ec3cb58f--- /dev/null+++ b/src/core_processes/batch_processing/session_processing_parameter_models.py@@ -0,0 +1,46 @@+from pathlib import Path+from typing import Union++from pydantic import BaseModel+++class MediaPipe2DParametersModel(BaseModel):+ model_complexity: int = 2+ min_detection_confidence: float = 0.5+ min_tracking_confidence: float = 0.5+ static_image_mode: bool = False+++class AniposeTriangulate3DParametersModel(BaseModel):+ confidence_threshold_cutoff: float = 0.7+ use_triangulate_ransac_method: bool = True+++class ButterworthFilterParametersModel(BaseModel):+ sampling_rate: float = 30+ cutoff_frequency: float = 7+ order: int = 4+++class PostProcessingParametersModel(BaseModel):+ framerate: float = 30.0+ butterworth_filter_parameters = ButterworthFilterParametersModel()+++class SessionProcessingParameterModel(BaseModel):+ path_to_session_folder: Union[Path, str]+ path_to_output_data_folder: Union[Path, str]+ path_to_folder_of_synchronized_videos: Union[Path, str]+ anipose_calibration_object: object # I don't wtf that thing is lol+ path_to_blender_executable: Union[Path, str]+ mediapipe_2d_parameters: MediaPipe2DParametersModel = MediaPipe2DParametersModel()+ anipose_triangulate_3d_parameters: AniposeTriangulate3DParametersModel = (+ AniposeTriangulate3DParametersModel()+ )+ post_processing_parameters: PostProcessingParametersModel = (+ PostProcessingParametersModel()+ )+ start_processing_at_stage: Union[int, str] = 0++ class Config:+ arbitrary_types_allowed = Truediff --git a/src/core_processes/capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.py b/src/core_processes/capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.pyindex 0d643edb..233f6ba4 100644--- a/src/core_processes/capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.py+++ b/src/core_processes/capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.py@@ -1,3 +1,6 @@+# Most of this was copied (with permission) from the original `aniposelib` package (https://github.com/lambdaloop/aniposelib), and we're adapting it to our needs here. M+# ore info on Anipoise: https://anipose.readthedocs.io/en/latest/+import loggingimport cv2@@ -353,9 +356,12 @@ class Camera:)return out- def reprojection_error(self, p3d, p2d):- proj = self.project(p3d).reshape(p2d.shape)- return p2d - proj+ def single_camera_reprojection_error(self, p3d, p2d):+ projecting_3d_points_onto_2d_image_plane_og = self.project(p3d)+ projecting_3d_points_onto_2d_image_plane = (+ projecting_3d_points_onto_2d_image_plane_og.reshape(p2d.shape)+ )+ return p2d - projecting_3d_points_onto_2d_image_planedef copy(self):return Camera(@@ -684,7 +690,7 @@ class CameraGroup:errors = np.empty((n_cams, n_points, 2))for cnum, cam in enumerate(self.cameras):- errors[cnum] = cam.reprojection_error(p3ds, p2ds[cnum])+ errors[cnum] = cam.single_camera_reprojection_error(p3ds, p2ds[cnum])if mean:errors_norm = np.linalg.norm(errors, axis=2)@@ -1312,7 +1318,9 @@ class CameraGroup:c = np.isfinite(p3ds[:, :, 0])if np.sum(c) < 20:- print("warning: not enough 3D points to run optimization")+ print(+ "warning: not enough 3D points to calculate_center_of_mass optimization"+ )return p3dsreturn self.optim_points(points, p3ds, **kwargs)diff --git a/src/core_processes/capture_volume_calibration/charuco_board_detection/charuco_board_detector.py b/src/core_processes/capture_volume_calibration/charuco_board_detection/charuco_board_detector.pyindex e624f199..82cf09f5 100644--- a/src/core_processes/capture_volume_calibration/charuco_board_detection/charuco_board_detector.py+++ b/src/core_processes/capture_volume_calibration/charuco_board_detection/charuco_board_detector.py@@ -171,6 +171,6 @@ class CharucoBoardDetector:if __name__ == "__main__":pass- # ## Jon, Run me to easily start a charuco board detect run+ # ## Jon, Run me to easily start a charuco board detect calculate_center_of_mass# print('starting icis_conference_main')# BoardDetection().process()diff --git a/src/core_processes/capture_volume_calibration/get_anipose_calibration_object.py b/src/core_processes/capture_volume_calibration/get_anipose_calibration_object.pyindex 7e760eea..5a2f8202 100644--- a/src/core_processes/capture_volume_calibration/get_anipose_calibration_object.py+++ b/src/core_processes/capture_volume_calibration/get_anipose_calibration_object.py@@ -39,22 +39,24 @@ def load_most_recent_anipose_calibration_toml(return freemocap_anipose.CameraGroup.load(str(session_calibration_file_path))-def load_anipose_calibration_toml_from_user_selection(- user_selected_toml_path: Union[str, Path],+def load_anipose_calibration_toml_from_path(+ camera_calibration_data_toml_path: Union[str, Path],save_copy_of_calibration_to_this_path: Union[str, Path] = None,):- logger.info(f"loading camera calibration file from:{str(user_selected_toml_path)}")+ logger.info(+ f"loading camera calibration file from:{str(camera_calibration_data_toml_path)}"+ )try:anipose_calibration_object = freemocap_anipose.CameraGroup.load(- str(user_selected_toml_path)+ str(camera_calibration_data_toml_path))if save_copy_of_calibration_to_this_path is not None:logger.info(- f"Saving copy of {user_selected_toml_path} to {save_copy_of_calibration_to_this_path}"+ f"Saving copy of {camera_calibration_data_toml_path} to {save_copy_of_calibration_to_this_path}")shutil.copy(- str(user_selected_toml_path),+ str(camera_calibration_data_toml_path),str(Path(save_copy_of_calibration_to_this_path)/ CAMERA_CALIBRATION_FILE_NAME@@ -63,7 +65,7 @@ def load_anipose_calibration_toml_from_user_selection(return anipose_calibration_objectexcept Exception as e:logger.error(- f"Failed to load anipose calibration info from {str(user_selected_toml_path)}"+ f"Failed to load anipose calibration info from {str(camera_calibration_data_toml_path)}")raise ereturn Nonediff --git a/src/core_processes/capture_volume_calibration/triangulate_3d_data.py b/src/core_processes/capture_volume_calibration/triangulate_3d_data.pyindex 92f77958..41304ab1 100644--- a/src/core_processes/capture_volume_calibration/triangulate_3d_data.py+++ b/src/core_processes/capture_volume_calibration/triangulate_3d_data.py@@ -4,8 +4,9 @@ from typing import Unionimport numpy as npimport logging-from src.core_processes.mediapipe_stuff.convert_mediapipe_npy_to_csv import (- convert_mediapipe_npy_to_csv,+from src.config.home_dir import (+ MEDIAPIPE_3D_NPY_FILE_NAME,+ MEDIAPIPE_REPROJECTION_ERROR_NPY_FILE_NAME,)logger = logging.getLogger(__name__)@@ -15,7 +16,6 @@ def threshold_by_confidence(mediapipe_2d_data: np.ndarray,mediapipe_confidence_cutoff_threshold: float = 0.0,):-mediapipe_2d_data[mediapipe_2d_data <= mediapipe_confidence_cutoff_threshold] = np.NaN@@ -31,12 +31,65 @@ def threshold_by_confidence(return mediapipe_2d_data+def remove_3d_data_with_high_reprojection_error(+ data3d_numFrames_numTrackedPoints_XYZ: np.ndarray,+ data3d_numFrames_numTrackedPoints_reprojectionError: np.ndarray,+):+ logger.info("Removing 3D data with high reprojection error")+ mean_reprojection_error_per_frame = np.nanmean(+ data3d_numFrames_numTrackedPoints_reprojectionError,+ axis=1,+ )++ reprojection_error_mean = np.nanmean(mean_reprojection_error_per_frame)+ reprojection_error_median = np.nanmedian(mean_reprojection_error_per_frame)+ reprojection_error_std = np.nanstd(mean_reprojection_error_per_frame)++ median_absolute_deviation = np.nanmedian(+ np.abs(mean_reprojection_error_per_frame - reprojection_error_median)+ )++ logger.info(+ f"\nInitial reprojection error - \nmean: {reprojection_error_mean:.3f},\nstandard deviation: {reprojection_error_std:.3f},\nmedian: {reprojection_error_median}\nmedian absolute deviation: {median_absolute_deviation:.3f}"+ )++ error_threshold = reprojection_error_median + 3 * median_absolute_deviation++ number_of_nans_before_thresholding = np.sum(+ np.isnan(data3d_numFrames_numTrackedPoints_XYZ)+ )++ # replace points with high reprojection error with `np.nan`+ data3d_numFrames_numTrackedPoints_XYZ[+ data3d_numFrames_numTrackedPoints_reprojectionError > error_threshold+ ] = np.nan++ number_of_nans_after_thresholding = np.sum(+ np.isnan(data3d_numFrames_numTrackedPoints_XYZ)+ )+ percentage_of_nans_removed = (+ (number_of_nans_before_thresholding - number_of_nans_after_thresholding)+ / number_of_nans_before_thresholding+ * 100+ )++ logger.info(f"Removing points with reprojection error > {error_threshold:.3f}")+ logger.info(+ f"Number of NaNs before thresholding: {number_of_nans_before_thresholding}"+ )+ logger.info(+ f"Number of NaNs after thresholding: {number_of_nans_after_thresholding} ({percentage_of_nans_removed:.2f} %)"+ )++ return data3d_numFrames_numTrackedPoints_XYZ++def triangulate_3d_data(anipose_calibration_object,mediapipe_2d_data: np.ndarray,output_data_folder_path: Union[str, Path],mediapipe_confidence_cutoff_threshold: float,- save_data_as_csv: bool,+ use_triangulate_ransac: bool = False,):number_of_cameras = mediapipe_2d_data.shape[0]number_of_frames = mediapipe_2d_data.shape[1]@@ -59,51 +112,66 @@ def triangulate_3d_data(data2d_flat = mediapipe_2d_data.reshape(number_of_cameras, -1, 2)logger.info(- f"Reconstructing 3d points from 2d points with shape: "- f"number_of_cameras: {number_of_cameras},"- f" number_of_frames: {number_of_frames}, "- f" number_of_tracked_points: {number_of_tracked_points},"- f" number_of_spatial_dimensions: {number_of_spatial_dimensions}"+ f"Reconstructing 3d points from 2d points with shape: \n"+ f"number_of_cameras: {number_of_cameras},\n"+ f"number_of_frames: {number_of_frames}, \n"+ f"number_of_tracked_points: {number_of_tracked_points},\n"+ f"number_of_spatial_dimensions: {number_of_spatial_dimensions}")- data3d_flat = anipose_calibration_object.triangulate(data2d_flat, progress=True)+ if use_triangulate_ransac:+ logger.info("Using `triangulate_ransac` method")+ data3d_flat = anipose_calibration_object.triangulate_ransac(+ data2d_flat, progress=True+ )+ else:+ logger.info("Using simple `triangulate` method ")+ data3d_flat = anipose_calibration_object.triangulate(data2d_flat, progress=True)++ spatial_data3d_numFrames_numTrackedPoints_XYZ_og = data3d_flat.reshape(+ number_of_frames, number_of_tracked_points, 3+ )data3d_reprojectionError_flat = anipose_calibration_object.reprojection_error(data3d_flat, data2d_flat, mean=True)- data3d_numFrames_numTrackedPoints_XYZ = data3d_flat.reshape(- number_of_frames, number_of_tracked_points, 3- )- data3d_numFrames_numTrackedPoints_reprojectionError = (+ reprojection_error_data3d_numFrames_numTrackedPoints = (data3d_reprojectionError_flat.reshape(number_of_frames, number_of_tracked_points))- path_to_3d_data_npy = save_mediapipe_3d_data_to_npy(- data3d_numFrames_numTrackedPoints_XYZ=data3d_numFrames_numTrackedPoints_XYZ,- data3d_numFrames_numTrackedPoints_reprojectionError=data3d_numFrames_numTrackedPoints_reprojectionError,- output_data_folder_path=output_data_folder_path,+ spatial_data3d_numFrames_numTrackedPoints_XYZ = remove_3d_data_with_high_reprojection_error(+ data3d_numFrames_numTrackedPoints_XYZ=spatial_data3d_numFrames_numTrackedPoints_XYZ_og,+ data3d_numFrames_numTrackedPoints_reprojectionError=reprojection_error_data3d_numFrames_numTrackedPoints,)- if save_data_as_csv:- convert_mediapipe_npy_to_csv(- data3d_numFrames_numTrackedPoints_XYZ, output_data_folder_path- )-- return path_to_3d_data_npy+ save_mediapipe_3d_data_to_npy(+ data3d_numFrames_numTrackedPoints_XYZ=spatial_data3d_numFrames_numTrackedPoints_XYZ,+ data3d_numFrames_numTrackedPoints_reprojectionError=reprojection_error_data3d_numFrames_numTrackedPoints,+ path_to_folder_where_data_will_be_saved=output_data_folder_path,+ )+ # TODO - don't output multiple variables, make this a dataclass/BAG pattern or something+ return (+ spatial_data3d_numFrames_numTrackedPoints_XYZ,+ reprojection_error_data3d_numFrames_numTrackedPoints,+ )def save_mediapipe_3d_data_to_npy(data3d_numFrames_numTrackedPoints_XYZ: np.ndarray,data3d_numFrames_numTrackedPoints_reprojectionError: np.ndarray,- output_data_folder_path: Union[str, Path],+ path_to_folder_where_data_will_be_saved: Union[str, Path],):- # save spatial XYZ data+ path_to_folder_where_data_will_be_saved = Path(+ path_to_folder_where_data_will_be_saved+ )+ Path(path_to_folder_where_data_will_be_saved).mkdir(+ parents=True, exist_ok=True+ ) # save spatial XYZ datamediapipe_3dData_save_path = (- Path(output_data_folder_path)- / "mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"+ path_to_folder_where_data_will_be_saved / MEDIAPIPE_3D_NPY_FILE_NAME)logger.info(f"saving: {mediapipe_3dData_save_path}")@@ -111,8 +179,8 @@ def save_mediapipe_3d_data_to_npy(# save reprojection errormediapipe_reprojection_error_save_path = (- Path(output_data_folder_path)- / "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"+ path_to_folder_where_data_will_be_saved+ / MEDIAPIPE_REPROJECTION_ERROR_NPY_FILE_NAME)logger.info(f"saving: {mediapipe_reprojection_error_save_path}")@@ -120,3 +188,81 @@ def save_mediapipe_3d_data_to_npy(str(mediapipe_reprojection_error_save_path),data3d_numFrames_numTrackedPoints_reprojectionError,)+++if __name__ == "__main__":+ import argparse+ from src.core_processes.capture_volume_calibration.get_anipose_calibration_object import (+ load_anipose_calibration_toml_from_path,+ )++ parser = argparse.ArgumentParser()+ parser.add_argument(+ "--mediapipe_2d_data_path",+ type=str,+ help="path to mediapipe 2d data",+ required=True,+ )+ parser.add_argument(+ "--output_data_folder_path",+ type=str,+ help="path to output folder",+ required=False,+ )+ parser.add_argument(+ "--calibration_file_path",+ type=str,+ help="path to calibration file",+ required=False,+ )+ parser.add_argument(+ "--mediapipe_confidence_cutoff_threshold",+ type=float,+ help="confidence cutoff threshold",+ required=False,+ )+ parser.add_argument(+ "--save_data_as_csv",+ type=bool,+ help="save data as csv",+ required=False,+ )+ parser.add_argument(+ "--use_triangulate_ransac",+ type=bool,+ help="use triangulate ransac anipose method ",+ required=False,+ )+ args = parser.parse_args()++ mediapipe_2d_data = np.load(args.mediapipe_2d_data_path)++ if args.mediapipe_confidence_cutoff_threshold is None:+ args.mediapipe_confidence_cutoff_threshold = 0.7 # default++ if args.output_data_folder_path is None:+ args.output_data_folder_path = Path(args.mediapipe_2d_data_path).parent++ if args.save_data_as_csv is None:+ args.save_data_as_csv = True # default++ if args.use_triangulate_ransac is None:+ args.use_triangulate_ransac = True++ if args.calibration_file_path:+ anipose_calibration_object = load_anipose_calibration_toml_from_path(+ args.calibration_file_path+ )+ else:+ anipose_calibration_object = load_anipose_calibration_toml_from_path(+ Path(args.mediapipe_2d_data_path).parent.parent+ / "camera_calibration_data.toml"+ )++ triangulate_3d_data(+ anipose_calibration_object=anipose_calibration_object,+ mediapipe_2d_data=mediapipe_2d_data,+ output_data_folder_path=args.output_data_folder_path,+ mediapipe_confidence_cutoff_threshold=args.mediapipe_confidence_cutoff_threshold,+ use_triangulate_ransac=args.use_triangulate_ransac,+ )diff --git a/src/core_processes/mediapipe_stuff/__init__.py b/src/core_processes/mediapipe_stuff/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/core_processes/mediapipe_stuff/convert_mediapipe_npy_to_csv.py b/src/core_processes/mediapipe_stuff/convert_mediapipe_npy_to_csv.pyindex 237d7975..d4e1a05d 100644--- a/src/core_processes/mediapipe_stuff/convert_mediapipe_npy_to_csv.py+++ b/src/core_processes/mediapipe_stuff/convert_mediapipe_npy_to_csv.py@@ -3,8 +3,8 @@ import loggingfrom pathlib import Pathfrom typing import Union-import pandas as pdimport numpy as np+import pandas as pdfrom mediapipe.python.solutions import holistic as mp_holisticlogger = logging.getLogger(__name__)@@ -14,9 +14,8 @@ def convert_mediapipe_npy_to_csv(mediapipe_3d_frame_trackedPoint_xyz: np.ndarray,output_data_folder_path: Union[str, Path],):-logger.info(- f"loaded npy data with shape: {mediapipe_3d_frame_trackedPoint_xyz.shape}"+ f"Converting npy data with shape: {mediapipe_3d_frame_trackedPoint_xyz.shape} into `csv` and smaller `npy` files")# %%@@ -27,8 +26,8 @@ def convert_mediapipe_npy_to_csv(landmark.name.lower() for landmark in mp_holistic.HandLandmark]# face_landmark_names = [landmark.name.lower() for landmark in mp_holistic.PoseLandmark] #gonna have the clever for the face- logger.info(f"Body tracked point names: {mediapipe_pose_landmark_names}")- logger.info(mediapipe_hand_landmark_names)+ # logger.info(f"Body tracked point names: {mediapipe_pose_landmark_names}")+ # logger.info(mediapipe_hand_landmark_names)# %%# get number of points in body, hands, face@@ -52,31 +51,31 @@ def convert_mediapipe_npy_to_csv(number_of_face_points = last_face_marker_index - first_face_marker_index- logger.info(- f"body tracked point indices: {first_body_marker_index}:{last_body_marker_index}"- )- logger.info(- f"right hand tracked point indices: {first_right_hand_marker_index}:{last_right_hand_marker_index}"- )- logger.info(- f"left hand tracked point indices: {first_left_hand_marker_index}:{last_left_hand_marker_index}"- )- logger.info(- f"face tracked point indices: {first_face_marker_index}:{last_face_marker_index}"- )-- logger.info(- f"number of body points: {last_body_marker_index - first_body_marker_index + 1}"- )- logger.info(- f"number of right hand points: {last_right_hand_marker_index - first_right_hand_marker_index + 1}"- )- logger.info(- f"number of left hand points: {last_left_hand_marker_index - first_left_hand_marker_index + 1}"- )- logger.info(- f"number of face points: {last_face_marker_index - first_face_marker_index + 1}"- )+ # logger.info(+ # f"body tracked point indices: {first_body_marker_index}:{last_body_marker_index}"+ # )+ # logger.info(+ # f"right hand tracked point indices: {first_right_hand_marker_index}:{last_right_hand_marker_index}"+ # )+ # logger.info(+ # f"left hand tracked point indices: {first_left_hand_marker_index}:{last_left_hand_marker_index}"+ # )+ # logger.info(+ # f"face tracked point indices: {first_face_marker_index}:{last_face_marker_index}"+ # )+ #+ # logger.info(+ # f"number of body points: {last_body_marker_index - first_body_marker_index + 1}"+ # )+ # logger.info(+ # f"number of right hand points: {last_right_hand_marker_index - first_right_hand_marker_index + 1}"+ # )+ # logger.info(+ # f"number of left hand points: {last_left_hand_marker_index - first_left_hand_marker_index + 1}"+ # )+ # logger.info(+ # f"number of face points: {last_face_marker_index - first_face_marker_index + 1}"+ # )# %%body_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[@@ -92,10 +91,10 @@ def convert_mediapipe_npy_to_csv(:, first_face_marker_index : last_face_marker_index + 1, :]- logger.info(f"body 3d xyz shape: {body_3d_xyz.shape}")- logger.info(f"right hand 3d xyz shape: {right_hand_3d_xyz.shape}")- logger.info(f"left hand 3d xyz shape: {left_hand_3d_xyz.shape}")- logger.info(f"face 3d xyz shape: {face_3d_xyz.shape}")+ # logger.info(f"body 3d xyz shape: {body_3d_xyz.shape}")+ # logger.info(f"right hand 3d xyz shape: {right_hand_3d_xyz.shape}")+ # logger.info(f"left hand 3d xyz shape: {left_hand_3d_xyz.shape}")+ # logger.info(f"face 3d xyz shape: {face_3d_xyz.shape}")# %%# save broken up npy files@@ -140,19 +139,19 @@ def convert_mediapipe_npy_to_csv(face_3d_xyz_header.append(f"face_{str(landmark_number).zfill(4)}_x")face_3d_xyz_header.append(f"face_{str(landmark_number).zfill(4)}_y")face_3d_xyz_header.append(f"face_{str(landmark_number).zfill(4)}_z")-- logger.info(- f"length of body 3d xyz header: {len(body_3d_xyz_header)}, should be: {number_of_body_points * 3}"- )- logger.info(- f"length of right hand 3d xyz header: {len(right_hand_3d_xyz_header)}, should be: {number_of_hand_points * 3}"- )- logger.info(- f"length of left hand 3d xyz header: {len(left_hand_3d_xyz_header)}, should be: {number_of_hand_points * 3}"- )- logger.info(- f"length of face 3d xyz header: {len(face_3d_xyz_header)}, should be: {number_of_face_points * 3}"- )+ #+ # logger.debug(+ # f"length of body 3d xyz header: {len(body_3d_xyz_header)}, should be: {number_of_body_points * 3}"+ # )+ # logger.debug(+ # f"length of right hand 3d xyz header: {len(right_hand_3d_xyz_header)}, should be: {number_of_hand_points * 3}"+ # )+ # logger.debug(+ # f"length of left hand 3d xyz header: {len(left_hand_3d_xyz_header)}, should be: {number_of_hand_points * 3}"+ # )+ # logger.debug(+ # f"length of face 3d xyz header: {len(face_3d_xyz_header)}, should be: {number_of_face_points * 3}"+ # )# %%number_of_frames = mediapipe_3d_frame_trackedPoint_xyz.shape[0]@@ -199,8 +198,9 @@ def convert_mediapipe_npy_to_csv(landmark.name.lower() for landmark in mp_holistic.HandLandmark]# face_landmark_names = [landmark.name.lower() for landmark in mp_holistic.PoseLandmark] #gonna have the clever for the face- logger.info(f"Body tracked point names: {mediapipe_pose_landmark_names}")- logger.info(mediapipe_hand_landmark_names)++ # logger.debug(f"Body tracked point names: {mediapipe_pose_landmark_names}")+ # logger.debug(mediapipe_hand_landmark_names)# %%# get number of points in body, hands, face@@ -224,31 +224,31 @@ def convert_mediapipe_npy_to_csv(number_of_face_points = last_face_marker_index - first_face_marker_index- logger.info(- f"body tracked point indices: {first_body_marker_index}:{last_body_marker_index}"- )- logger.info(- f"right hand tracked point indices: {first_right_hand_marker_index}:{last_right_hand_marker_index}"- )- logger.info(- f"left hand tracked point indices: {first_left_hand_marker_index}:{last_left_hand_marker_index}"- )- logger.info(- f"face tracked point indices: {first_face_marker_index}:{last_face_marker_index}"- )-- logger.info(- f"number of body points: {last_body_marker_index - first_body_marker_index + 1}"- )- logger.info(- f"number of right hand points: {last_right_hand_marker_index - first_right_hand_marker_index + 1}"- )- logger.info(- f"number of left hand points: {last_left_hand_marker_index - first_left_hand_marker_index + 1}"- )- logger.info(- f"number of face points: {last_face_marker_index - first_face_marker_index + 1}"- )+ # logger.debug(+ # f"body tracked point indices: {first_body_marker_index}:{last_body_marker_index}"+ # )+ # logger.debug(+ # f"right hand tracked point indices: {first_right_hand_marker_index}:{last_right_hand_marker_index}"+ # )+ # logger.debug(+ # f"left hand tracked point indices: {first_left_hand_marker_index}:{last_left_hand_marker_index}"+ # )+ # logger.debug(+ # f"face tracked point indices: {first_face_marker_index}:{last_face_marker_index}"+ # )+ #+ # logger.debug(+ # f"number of body points: {last_body_marker_index - first_body_marker_index + 1}"+ # )+ # logger.debug(+ # f"number of right hand points: {last_right_hand_marker_index - first_right_hand_marker_index + 1}"+ # )+ # logger.debug(+ # f"number of left hand points: {last_left_hand_marker_index - first_left_hand_marker_index + 1}"+ # )+ # logger.debug(+ # f"number of face points: {last_face_marker_index - first_face_marker_index + 1}"+ # )# %%body_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[@@ -264,10 +264,10 @@ def convert_mediapipe_npy_to_csv(:, first_face_marker_index : last_face_marker_index + 1, :]- logger.info(f"body 3d xyz shape: {body_3d_xyz.shape}")- logger.info(f"right hand 3d xyz shape: {right_hand_3d_xyz.shape}")- logger.info(f"left hand 3d xyz shape: {left_hand_3d_xyz.shape}")- logger.info(f"face 3d xyz shape: {face_3d_xyz.shape}")+ logger.debug(f"body 3d xyz shape: {body_3d_xyz.shape}")+ logger.debug(f"right hand 3d xyz shape: {right_hand_3d_xyz.shape}")+ logger.debug(f"left hand 3d xyz shape: {left_hand_3d_xyz.shape}")+ logger.debug(f"face 3d xyz shape: {face_3d_xyz.shape}")# %%# save broken up npy files@@ -313,23 +313,22 @@ def convert_mediapipe_npy_to_csv(face_3d_xyz_header.append(f"face_{str(landmark_number).zfill(4)}_y")face_3d_xyz_header.append(f"face_{str(landmark_number).zfill(4)}_z")- logger.info(- f"length of body 3d xyz header: {len(body_3d_xyz_header)}, should be: {number_of_body_points * 3}"+ logger.debug(+ f"length of body 3d xyz `.csv` header: {len(body_3d_xyz_header)}, should be: {number_of_body_points * 3}")- logger.info(- f"length of right hand 3d xyz header: {len(right_hand_3d_xyz_header)}, should be: {number_of_hand_points * 3}"+ logger.debug(+ f"length of right hand 3d xyz `.csv` header: {len(right_hand_3d_xyz_header)}, should be: {number_of_hand_points * 3}")- logger.info(- f"length of left hand 3d xyz header: {len(left_hand_3d_xyz_header)}, should be: {number_of_hand_points * 3}"+ logger.debug(+ f"length of left hand 3d xyz `.csv` header: {len(left_hand_3d_xyz_header)}, should be: {number_of_hand_points * 3}")- logger.info(- f"length of face 3d xyz header: {len(face_3d_xyz_header)}, should be: {number_of_face_points * 3}"+ logger.debug(+ f"length of face 3d xyz `.csv` header: {len(face_3d_xyz_header)}, should be: {number_of_face_points * 3}")# %%number_of_frames = mediapipe_3d_frame_trackedPoint_xyz.shape[0]body_flat = body_3d_xyz.reshape(number_of_frames, number_of_body_points * 3)- body_flat.shapebody_dataframe = pd.DataFrame(body_flat, columns=body_3d_xyz_header)body_dataframe.to_csv(@@ -362,4 +361,17 @@ def convert_mediapipe_npy_to_csv(str(Path(output_data_folder_path) / "mediapipe_face_3d_xyz.csv"), index=False)- # %%+ logger.info("Done saving out `csv` and broken up `npy` files")+++if __name__ == "__main__":+ mediapipe_3d_frame_trackedPoint_xyz = np.load(+ r"C:\Users\jonma\freemocap_data\session_10-15-2022-09_50_10\output_data\post_processed_data\mediaPipeSkel_3d_origin_aligned.npy"+ )+ output_data_folder_path = (+ r"C:\Users\jonma\freemocap_data\session_10-15-2022-09_50_10\output_data"+ )++ convert_mediapipe_npy_to_csv(+ mediapipe_3d_frame_trackedPoint_xyz, output_data_folder_path+ )diff --git a/src/core_processes/mediapipe_stuff/load_mediapipe3d_data.py b/src/core_processes/mediapipe_stuff/load_mediapipe3d_data.pyindex 826193d7..fe3ea986 100644--- a/src/core_processes/mediapipe_stuff/load_mediapipe3d_data.py+++ b/src/core_processes/mediapipe_stuff/load_mediapipe3d_data.py@@ -5,17 +5,44 @@ import loggingimport numpy as np+from src.config.home_dir import RAW_DATA_FOLDER_NAME, MEDIAPIPE_3D_NPY_FILE_NAME+logger = logging.getLogger(__name__)-def load_mediapipe3d_data(output_data_folder_path: Union[str, Path]):+def load_raw_mediapipe3d_data(output_data_folder_path: Union[str, Path]):mediapipe3d_xyz_file_path = (Path(output_data_folder_path)- / "mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"+ / RAW_DATA_FOLDER_NAME+ / MEDIAPIPE_3D_NPY_FILE_NAME+ )+ logger.info(f"loading: {mediapipe3d_xyz_file_path}")+ mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ = np.load(+ str(mediapipe3d_xyz_file_path))++ return mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ+++def load_post_processed_mediapipe3d_data(mediapipe3d_xyz_file_path: Union[str, Path]):+logger.info(f"loading: {mediapipe3d_xyz_file_path}")mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ = np.load(str(mediapipe3d_xyz_file_path))return mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ+++def load_skeleton_reprojection_error_data(output_data_folder_path: Union[str, Path]):+ mediapipe3d_reprojection_error_file_path = (+ Path(output_data_folder_path)+ / "raw_data"+ / "mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"+ )+ logger.info(f"loading: {mediapipe3d_reprojection_error_file_path}")+ mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError = np.load(+ str(mediapipe3d_reprojection_error_file_path)+ )++ return mediapipe_3dData_numFrames_numTrackedPoints_reprojectionErrordiff --git a/src/core_processes/mediapipe_stuff/mediapipe_skeleton_detector.py b/src/core_processes/mediapipe_stuff/mediapipe_skeleton_detector.pyindex dd898ed9..d871923a 100644--- a/src/core_processes/mediapipe_stuff/mediapipe_skeleton_detector.py+++ b/src/core_processes/mediapipe_stuff/mediapipe_skeleton_detector.py@@ -1,24 +1,23 @@import loggingfrom dataclasses import dataclassfrom pathlib import Path-from typing import List, Dict, Union, Any+from typing import List, Union, Anyimport cv2import numpy as npimport mediapipe as mp+from tqdm import tqdmfrom src.cameras.capture.dataclasses.frame_payload import FramePayloadfrom src.cameras.persistence.video_writer.video_recorder import VideoRecorder-from src.config.home_dir import (- get_session_folder_path,- get_synchronized_videos_folder_path,- get_output_data_folder_path,-)+from src.config.home_dir import MEDIAPIPE_2D_NPY_FILE_NAME+from src.core_processes.mediapipe_stuff.medaipipe_tracked_points_names_dict import (mediapipe_tracked_point_names_dict,)--from src.gui.main.app_state.app_state import APP_STATE+from src.core_processes.batch_processing.session_processing_parameter_models import (+ MediaPipe2DParametersModel,+)logger = logging.getLogger(__name__)@@ -79,11 +78,10 @@ class Mediapipe2dDataPayload:class MediaPipeSkeletonDetector:- def __init__(self, session_id: str = None):-- self.model_complexity = 2 # can be 0,1, or 2 - higher numbers are more accurate but heavier computationally- self.min_detection_confidence = 0.5- self.min_tracking_confidence = 0.5+ def __init__(+ self,+ parameter_model=MediaPipe2DParametersModel(),+ ):self._mediapipe_payload_list = []@@ -102,9 +100,9 @@ class MediaPipeSkeletonDetector:)self._holistic_tracker = self._mp_holistic.Holistic(- model_complexity=self.model_complexity,- min_detection_confidence=self.min_detection_confidence,- min_tracking_confidence=self.min_tracking_confidence,+ model_complexity=parameter_model.model_complexity,+ min_detection_confidence=parameter_model.min_detection_confidence,+ min_tracking_confidence=parameter_model.min_tracking_confidence,)self._mediapipe_tracked_point_names_dict = mediapipe_tracked_point_names_dict@@ -170,7 +168,7 @@ class MediaPipeSkeletonDetector:path_to_folder_of_videos_to_process: Union[Path, str],output_data_folder_path: Union[str, Path],save_annotated_videos: bool = True,- ):+ ) -> np.ndarray:path_to_folder_of_videos_to_process = Path(path_to_folder_of_videos_to_process)@@ -195,18 +193,24 @@ class MediaPipeSkeletonDetector:this_video_annotated_images_list = []success, image = this_video_capture_object.read()- if not success or image is None:- logger.error(- f"Failed to load an image from: {str(this_synchronized_video_file_path)}"- )- raise Exception- frame_number = 0- while success and image is not None:+ number_of_frames = int(+ this_video_capture_object.get(cv2.CAP_PROP_FRAME_COUNT)+ )- frame_number += 1- if frame_number % 5 == 0:- print(f"frame {frame_number}")+ for frame_number in tqdm(+ range(number_of_frames),+ desc=f"mediapiping video: {this_synchronized_video_file_path.name}",+ total=number_of_frames,+ colour="magenta",+ unit="frames",+ dynamic_ncols=True,+ ):+ if not success or image is None:+ logger.error(+ f"Failed to load an image from: {str(this_synchronized_video_file_path)}"+ )+ raise Exceptionmediapipe2d_data_payload = self.detect_skeleton_in_image(raw_image=image@@ -290,7 +294,7 @@ class MediaPipeSkeletonDetector:data2d_numCams_numFrames_numTrackedPts_XY=data2d_numCams_numFrames_numTrackedPts_XY,output_data_folder_path=Path(output_data_folder_path),)- return str(mediapipe_data_2d_npy_path)+ return data2d_numCams_numFrames_numTrackedPts_XYdef _save_mediapipe2d_data_to_npy(self,@@ -298,9 +302,9 @@ class MediaPipeSkeletonDetector:output_data_folder_path: Union[str, Path],):mediapipe_2dData_save_path = (- Path(output_data_folder_path)- / "mediapipe_2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"+ Path(output_data_folder_path) / MEDIAPIPE_2D_NPY_FILE_NAME)+ mediapipe_2dData_save_path.parent.mkdir(exist_ok=True, parents=True)logger.info(f"saving: {mediapipe_2dData_save_path}")np.save(str(mediapipe_2dData_save_path), data2d_numCams_numFrames_numTrackedPts_XYdiff --git a/src/core_processes/mediapipe_stuff/mediapipe_skeleton_names_and_connections.py b/src/core_processes/mediapipe_stuff/mediapipe_skeleton_names_and_connections.pyindex ab6937a3..11637e94 100644--- a/src/core_processes/mediapipe_stuff/mediapipe_skeleton_names_and_connections.py+++ b/src/core_processes/mediapipe_stuff/mediapipe_skeleton_names_and_connections.py@@ -8,7 +8,7 @@ mediapipe_face_connections = [connection for connection in mp_holistic.FACEMESH_TESSELATION]-mediapipe_pose_landmark_names = [+mediapipe_body_landmark_names = [landmark.name.lower() for landmark in mp_holistic.PoseLandmark]diff --git a/src/core_processes/post_process_skeleton_data/__init__.py b/src/core_processes/post_process_skeleton_data/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/core_processes/post_process_skeleton_data/estimate_skeleton_segment_lengths.py b/src/core_processes/post_process_skeleton_data/estimate_skeleton_segment_lengths.pynew file mode 100644index 00000000..2d9ebd29--- /dev/null+++ b/src/core_processes/post_process_skeleton_data/estimate_skeleton_segment_lengths.py@@ -0,0 +1,171 @@+import logging+from pathlib import Path+from typing import Union++import numpy as np+import pandas as pd+import json++from rich import print++logger = logging.getLogger(__name__)++mediapipe_skeleton_segment_definitions = {+ "lower_spine": {"proximal": "hips_center", "distal": "chest_center"},+ "upper_spine": {"proximal": "chest_center", "distal": "neck_center"},+ "head": {"proximal": "neck_center", "distal": "head_center"},+ "left_clavicle": {"proximal": "neck_center", "distal": "left_shoulder"},+ "left_upper_arm": {"proximal": "left_shoulder", "distal": "left_elbow"},+ "left_forearm": {"proximal": "left_elbow", "distal": "left_wrist"},+ "left_hand": {"proximal": "left_wrist", "distal": "left_index"},+ "right_clavicle": {"proximal": "neck_center", "distal": "right_shoulder"},+ "right_upper_arm": {"proximal": "right_shoulder", "distal": "right_elbow"},+ "right_forearm": {"proximal": "right_elbow", "distal": "right_wrist"},+ "right_hand": {"proximal": "right_wrist", "distal": "right_index"},+ "left_pelvis": {"proximal": "hips_center", "distal": "left_hip"},+ "left_thigh": {"proximal": "left_hip", "distal": "left_knee"},+ "left_calf": {"proximal": "left_knee", "distal": "left_ankle"},+ "left_foot": {"proximal": "left_ankle", "distal": "left_foot_index"},+ "right_pelvis": {"proximal": "hips_center", "distal": "right_hip"},+ "right_thigh": {"proximal": "right_hip", "distal": "right_knee"},+ "right_calf": {"proximal": "right_knee", "distal": "right_ankle"},+ "right_foot": {"proximal": "right_ankle", "distal": "right_foot_index"},+}+++def estimate_skeleton_segment_lengths(+ skeleton_dataframe: pd.DataFrame, skeleton_segment_definitions: dict+) -> dict:+ """Estimate the length of each skeleton segment.++ Args:+ skeleton_data_dictionary (dict): Dictionary containing the skeleton data.+ skeleton_segment_definitions (dict): Dictionary containing the definitions of each segment (i.e. the proximal and distal joints).++ Returns:+ dict: Dictionary containing the estimated length of each skeleton segment.+ """+ logger.debug("Estimating skeleton segment lengths (mm)...")+ skeleton_data_dictionary = create_skeleton_dictionary_from_skeleton_body_data_frame(+ skeleton_dataframe+ )++ skeleton_segment_lengths_dict = {}+ for segment_name, segment_definition_dict in skeleton_segment_definitions.items():+ print(+ f"Estimating length of segment '{segment_name}' "+ f"based on proximal joint: '{segment_definition_dict['proximal']}' and "+ f"distal joint:'{segment_definition_dict['distal']}'"+ )+ proximal_joint_name = segment_definition_dict["proximal"]+ distal_joint_name = segment_definition_dict["distal"]++ proximal_x = skeleton_data_dictionary[f"{proximal_joint_name}_x"]+ proximal_y = skeleton_data_dictionary[f"{proximal_joint_name}_y"]+ proximal_z = skeleton_data_dictionary[f"{proximal_joint_name}_z"]++ distal_x = skeleton_data_dictionary[f"{distal_joint_name}_x"]+ distal_y = skeleton_data_dictionary[f"{distal_joint_name}_y"]+ distal_z = skeleton_data_dictionary[f"{distal_joint_name}_z"]++ # logger.debug(f"proximal_x nans: {np.isnan(proximal_x).sum()}")+ # logger.debug(f"len proximal_x: {len(proximal_x)}")+ # logger.debug(f"distal_x nans: {np.isnan(distal_x).sum()}")+ # logger.debug(f"len distal_x: {len(distal_x)}")++ # good ol pythag <3+ segment_length_per_frame = np.sqrt(+ (proximal_x - distal_x) ** 2+ + (proximal_y - distal_y) ** 2+ + (proximal_z - distal_z) ** 2+ )+ skeleton_segment_lengths_dict[segment_name] = {}+ skeleton_segment_lengths_dict[segment_name]["median"] = np.nanmedian(+ segment_length_per_frame+ )+ skeleton_segment_lengths_dict[segment_name]["mean"] = np.nanmean(+ segment_length_per_frame+ )+ skeleton_segment_lengths_dict[segment_name]["standard_deviation"] = np.nanstd(+ segment_length_per_frame+ )++ return skeleton_segment_lengths_dict+++def create_virtual_markers(+ skeleton_data_dictionary, virtual_marker_name: str, marker_name_list: list+) -> dict:+ # print(+ # f"Creating virtual marker '{virtual_marker_name}' from markers: {marker_name_list}"+ # )++ x = []+ y = []+ z = []++ for marker_name in marker_name_list:+ x.append(skeleton_data_dictionary[f"{marker_name}_x"])+ y.append(skeleton_data_dictionary[f"{marker_name}_y"])+ z.append(skeleton_data_dictionary[f"{marker_name}_z"])++ skeleton_data_dictionary[f"{virtual_marker_name}_x"] = np.mean(+ np.asarray(x), axis=0+ )+ skeleton_data_dictionary[f"{virtual_marker_name}_y"] = np.mean(+ np.asarray(y), axis=0+ )+ skeleton_data_dictionary[f"{virtual_marker_name}_z"] = np.mean(+ np.asarray(z), axis=0+ )++ return skeleton_data_dictionary+++def create_skeleton_dictionary_from_skeleton_body_data_frame(+ skeleton_body_dataframe: pd.DataFrame,+) -> dict:+ skeleton_data_dictionary = skeleton_body_dataframe.to_dict(orient="list")++ for key, value in skeleton_data_dictionary.items():+ skeleton_data_dictionary[key] = np.asarray(value)++ skeleton_data_dictionary = create_virtual_markers(+ skeleton_data_dictionary, "hips_center", ["left_hip", "right_hip"]+ )+ skeleton_data_dictionary = create_virtual_markers(+ skeleton_data_dictionary, "neck_center", ["left_shoulder", "right_shoulder"]+ )+ skeleton_data_dictionary = create_virtual_markers(+ skeleton_data_dictionary, "head_center", ["left_ear", "right_ear"]+ )++ skeleton_data_dictionary = create_virtual_markers(+ skeleton_data_dictionary, "chest_center", ["hips_center", "neck_center"]+ )+ return skeleton_data_dictionary+++def save_skeleton_segment_lengths_to_json(+ save_path: Union[Path, str], skeleton_segment_lengths_dict: dict+):+ logger.info("Saving skeleton segment lengths to JSON file...")+ json_file_path = Path(save_path) / "skeleton_segment_lengths.json"++ with open(json_file_path, "w") as file:+ json.dump(skeleton_segment_lengths_dict, file, indent=4)++ print(f"Saved skeleton segment lengths to: {json_file_path}")+++if __name__ == "__main__":+ path_to_skeleton_body_csv = Path(+ r"D:\Dropbox\FreeMoCapProject\teddy_animation\FreeMocap_Data\sesh_2022-10-09_13_55_45_calib_and_take_1_alpha\output_data\mediapipe_body_3d_xyz.csv"+ )+ skeleton_dataframe = pd.read_csv(path_to_skeleton_body_csv)++ skeleton_segment_lengths = estimate_skeleton_segment_lengths(+ skeleton_dataframe, mediapipe_skeleton_segment_definitions+ )++ print(skeleton_segment_lengths)diff --git a/src/core_processes/post_process_skeleton_data/gap_fill_filter_and_origin_align_skeleton_data.py b/src/core_processes/post_process_skeleton_data/gap_fill_filter_and_origin_align_skeleton_data.pynew file mode 100644index 00000000..3df2bf8a--- /dev/null+++ b/src/core_processes/post_process_skeleton_data/gap_fill_filter_and_origin_align_skeleton_data.py@@ -0,0 +1,1276 @@+# %%+import logging+import sys+from pathlib import Path+import pickle+from typing import Union++import numpy as np+import pandas as pd+from rich.progress import track+from scipy import signal++from src.config.home_dir import (+ CENTER_OF_MASS_FOLDER_NAME,+ SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME,+ TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME,+)++logger = logging.getLogger(__name__)+++def find_good_clean_frame_reprojection_error_method(+ skeleton_3d_fr_mar_xyz, skeleton_reprojection_error_fr_mar+):+ """+ Find the frame with the fewest nans, scaled by reprojection error (i.e. hopefully a frame where all tracked points are visible and well tracked)+ """+ print(+ "estimating good clean frame as the one where there few `nans`, reprojection error is low, and velocity is low..."+ )++ nans_per_frame = np.sum(np.isnan(skeleton_3d_fr_mar_xyz[:, :, 0]), axis=1)+ reprojection_error_per_frame = np.nanmedian(+ skeleton_reprojection_error_fr_mar, axis=1+ )+ marker_velocity_per_frame = np.nanmedian(+ np.abs(np.diff(skeleton_3d_fr_mar_xyz, axis=1)), axis=1+ )+ marker_velocity_per_frame = np.nanmean(np.abs(marker_velocity_per_frame), axis=1)++ print(f"nans_per_frame.shape: {nans_per_frame.shape}")+ print(f"reprojection_error_per_frame.shape: {reprojection_error_per_frame.shape}")+ print(f"marker_velocity_per_frame.shape: {marker_velocity_per_frame.shape}")++ # normalize errors by relevant thing+ nans_per_frame_normalized = nans_per_frame / skeleton_3d_fr_mar_xyz.shape[1]+ reprojection_error_per_frame_normalized = (+ reprojection_error_per_frame / np.nanmedian(reprojection_error_per_frame)+ )+ marker_velocity_per_frame_normalized = marker_velocity_per_frame / np.nanmedian(+ marker_velocity_per_frame+ )++ print(+ f"nans_per_frame_normalized (mean, [standard_deviation] : {np.nanmean(nans_per_frame_normalized):.3f} [{np.nanstd(nans_per_frame_normalized):.3f}]"+ )+ print(+ f"reprojection_error_per_frame_normalized (mean, [standard_deviation] : {np.nanmean(reprojection_error_per_frame_normalized):.3f} [{np.nanstd(reprojection_error_per_frame_normalized):.3f}]"+ )+ print(+ f"marker_velocity_per_frame_normalized (mean, [standard_deviation] : {np.nanmean(marker_velocity_per_frame_normalized):.3f} [{np.nanstd(marker_velocity_per_frame_normalized):.3f}]"+ )++ frame_cleanliness_score_where_low_scores_are_good = (+ nans_per_frame_normalized+ + reprojection_error_per_frame_normalized+ + marker_velocity_per_frame_normalized+ )++ good_clean_frame_number = np.nanargmin(+ frame_cleanliness_score_where_low_scores_are_good+ )+ print(f"----estimated good_clean_frame_number: {good_clean_frame_number}----")+ return good_clean_frame_number+++# %%+def fill_gaps_in_freemocap_data(freemocap_marker_data: np.ndarray) -> np.ndarray:+ """+ Takes in a 3d skeleton numpy array from freemocap and interpolates missing NaN values+ TODO - refactor so it doesn't use a for loop (and maybe uses more sophisticated gap-fill methods?)+ """+ num_frames = freemocap_marker_data.shape[0]+ num_markers = freemocap_marker_data.shape[1]++ freemocap_interpolated_data = np.empty((num_frames, num_markers, 3))++ for marker in track(+ range(num_markers),+ description="Filling gaps (`nan` values) via linear interpolation",+ ):+ this_marker_skel3d_data = freemocap_marker_data[:, marker, :]++ df = pd.DataFrame(this_marker_skel3d_data)+ df2 = df.interpolate(+ method="linear", axis=0+ ) # use pandas interpolation methods to fill in missing data+ this_marker_interpolated_skel3d_array = np.array(df2)+ # replace the remaining NaN values (the ones that often happen at the start of the recording)+ this_marker_interpolated_skel3d_array = np.where(+ np.isfinite(this_marker_interpolated_skel3d_array),+ this_marker_interpolated_skel3d_array,+ np.nanmean(this_marker_interpolated_skel3d_array),+ )++ freemocap_interpolated_data[+ :, marker, :+ ] = this_marker_interpolated_skel3d_array++ return freemocap_interpolated_data+++# %%+def butterworth_lowpass_zerolag_filter(data, cutoff, sampling_rate, order):+ """Run a low pass butterworth filter on a single column of data"""+ nyquist_freq = 0.5 * sampling_rate+ normal_cutoff = cutoff / nyquist_freq+ # Get the filter coefficients+ b, a = signal.butter(order, normal_cutoff, btype="low", analog=False)+ y = signal.filtfilt(b, a, data)+ return y+++def butterworth_filter_skeleton(skeleton_3d_data, cutoff, sampling_rate, order):+ """Take in a 3d skeleton numpy array and calculate_center_of_mass a low pass butterworth filter on each marker in the data"""+ number_of_frames = skeleton_3d_data.shape[0]+ number_of_markers = skeleton_3d_data.shape[1]+ butterworth_filtered_data = np.empty((number_of_frames, number_of_markers, 3))++ for marker_number in range(number_of_markers):+ for dimension in range(3):+ butterworth_filtered_data[+ :, marker_number, dimension+ ] = butterworth_lowpass_zerolag_filter(+ skeleton_3d_data[:, marker_number, dimension],+ cutoff,+ sampling_rate,+ order,+ )++ assert skeleton_3d_data.shape == butterworth_filtered_data.shape++ return butterworth_filtered_data+++# %%+def find_velocity_values_within_limit(skeleton_velocity_data, velocity_limit):+ """+ This function takes in a skeleton velocity data array and a limit and returns the indices of the values that are within the limit+ """+ indices = []+ for i in range(len(skeleton_velocity_data)):+ if abs(skeleton_velocity_data[i]) <= velocity_limit:+ indices.append(+ i + 1+ ) # add 1 to account for the difference in indices between the position and velocity data+ return indices+++# %%+++def find_matching_indices_in_lists(list_1, list_2, list_3, list_4):+ """+ This function takes in four lists and returns the indices of the values that are in all four lists+ """+ matching_values = [x for x in list_1 if x in list_2 and x in list_3 and x in list_4]++ return matching_values+++# %%+++def find_best_velocity_guess(+ skeleton_velocity_data, skeleton_indices, velocity_guess, iteration_range+):+ """+ This function iterates over velocity data and tries to pare down to a single frame that has the closest velocity to 0 for all foot markers+ """++ print(f"Velocity guess: {velocity_guess}, iteration range: {iteration_range}")++ right_heel_index = skeleton_indices.index("right_heel")+ right_toe_index = skeleton_indices.index("right_foot_index")+ left_heel_index = skeleton_indices.index("left_heel")+ left_toe_index = skeleton_indices.index("left_foot_index")++ skeleton_data_velocity_x_right_heel = skeleton_velocity_data[:, right_heel_index, 0]+ skeleton_data_velocity_x_right_toe = skeleton_velocity_data[:, right_toe_index, 0]+ skeleton_data_velocity_x_left_heel = skeleton_velocity_data[:, left_heel_index, 0]+ skeleton_data_velocity_x_left_toe = skeleton_velocity_data[:, left_toe_index, 0]++ print(+ f"sum nan right heel: {np.sum(np.isnan(skeleton_data_velocity_x_right_heel))}, "+ f"\nsum nan right toe: {np.sum(np.isnan(skeleton_data_velocity_x_right_toe))}, "+ f"\nsum nan left heel: {np.sum(np.isnan(skeleton_data_velocity_x_left_heel))}, "+ f"\nsum nan left toe: {np.sum(np.isnan(skeleton_data_velocity_x_left_toe))}, "+ f"\nnum frames: {len(skeleton_data_velocity_x_right_heel)}"+ )++ # get a list of the frames where the velocity for that marker is within the velocity limit+ right_heel_x_velocity_limits = find_velocity_values_within_limit(+ skeleton_data_velocity_x_right_heel, velocity_guess+ )+ right_toe_x_velocity_limits = find_velocity_values_within_limit(+ skeleton_data_velocity_x_right_toe, velocity_guess+ )+ left_heel_x_velocity_limits = find_velocity_values_within_limit(+ skeleton_data_velocity_x_left_heel, velocity_guess+ )+ left_toe_x_velocity_limits = find_velocity_values_within_limit(+ skeleton_data_velocity_x_left_toe, velocity_guess+ )++ # return a list of matching frame indices from the four lists generated above+ matching_values = find_matching_indices_in_lists(+ right_heel_x_velocity_limits,+ right_toe_x_velocity_limits,+ left_heel_x_velocity_limits,+ left_toe_x_velocity_limits,+ )+ matching_values = [x for x in matching_values if x > 75]++ # print(matching_values)+ if len(matching_values) > 1 and velocity_guess > 0:+ # if there are multiple matching values, decrease the guess a little bit and calculate_center_of_mass the function again+ #+ velocity_guess = velocity_guess - iteration_range+ print(+ "Current Velocity Guess:",+ velocity_guess,+ "| Number of Possible Frames:",+ len(matching_values),+ "| Possible Frames:",+ matching_values,+ )+ matching_values, velocity_guess = find_best_velocity_guess(+ skeleton_velocity_data, skeleton_indices, velocity_guess, iteration_range+ )++ f = 2+ elif len(matching_values) == 0:+ # if there are no matching values (we decreased our guess too far), reset the guess to be a bit smaller and calculate_center_of_mass the function again with smaller intervals between the guesses+ iteration_range = iteration_range / 2+ matching_values, velocity_guess = find_best_velocity_guess(+ skeleton_velocity_data,+ skeleton_indices,+ velocity_guess + iteration_range * 2,+ iteration_range,+ )++ f = 2+ elif len(matching_values) == 1:+ print("Good Frame:", matching_values, "| Final Velocity Guess:", velocity_guess)++ return matching_values, velocity_guess+++# %%+++def find_good_frame_recursive_guess_method(+ skeleton_data, skeleton_indices: list, initial_velocity_guess: float, debug=False+):+ """+ Finds a frame (called the good frame) where the velocity of both feet are closest to 0++ Input:+ skeleton data: a 3D numpy array of skeleton data in freemocap format+ skeleton indices: a list of joints being tracked by mediapipe/your 2d pose estimator+ initial velocity guess: just a starting guess for the optimizer. Can adjust if you're not getting the results you want+ debug: plots and displays the calculated good frame if True+ """++ skeleton_velocity_data = np.diff(skeleton_data, axis=0)+ print("finding best velocity guess...")+ matching_values, velocity_guess = find_best_velocity_guess(+ skeleton_velocity_data,+ skeleton_indices,+ initial_velocity_guess,+ iteration_range=0.1,+ )+ print(f"Return values: {matching_values}")+ good_frame = matching_values[0]++ return good_frame+++# %%+++def create_vector(point1, point2):+ """Put two points in, make a vector"""+ vector = point2 - point1+ return vector+++# %%+++def normalize_vector(vector):+ """Take in a vector, normalize it"""+ unit_vector = vector / np.linalg.norm(vector)++ vector_length = np.sqrt(np.sum(unit_vector**2))+ assert (+ np.abs(vector_length - 1.0) < sys.float_info.epsilon+ ), f"Vector is not normalized: vector_length = {vector_length}"+ return unit_vector+++# %%+++def calculate_shoulder_center_XYZ_coordinates(+ single_frame_skeleton_data, left_shoulder_index, right_shoulder_index+):+ """Take in the left and right shoulder indices, and calculate the shoulder center point"""+ left_shoulder_point = single_frame_skeleton_data[left_shoulder_index, :]+ right_shoulder_point = single_frame_skeleton_data[right_shoulder_index, :]+ shoulder_center_XYZ_coordinates = (left_shoulder_point + right_shoulder_point) / 2++ return shoulder_center_XYZ_coordinates+++# %%+++def calculate_mid_hip_XYZ_coordinates(+ single_frame_skeleton_data, left_hip_index, right_hip_index+):+ """Take in the left and right hip indices, and calculate the mid hip point"""+ left_hip_point = single_frame_skeleton_data[left_hip_index, :]+ right_hip_point = single_frame_skeleton_data[right_hip_index, :]+ mid_hip_XYZ_coordinates = (left_hip_point + right_hip_point) / 2++ return mid_hip_XYZ_coordinates+++# %%+++def calculate_mid_foot_XYZ_coordinate(+ single_frame_skeleton_data,+ left_heel_index,+ right_heel_index,+):+ """Take in the primary and secondary foot indices, and calculate the mid foot point"""+ right_foot_point = single_frame_skeleton_data[right_heel_index, :]+ left_foot_point = single_frame_skeleton_data[left_heel_index, :]+ mid_foot_XYZ_coordinates = (right_foot_point + left_foot_point) / 2++ return mid_foot_XYZ_coordinates+++# def calculate_translation_distance(skeleton_point_coordinate):+# """Take a skeleton point coordinate and calculate its distance to the origin"""++# translation_distance = skeleton_point_coordinate - [0,0,0]+# return translation_distance+++# %%+++def translate_skeleton_frame(rotated_skeleton_data_frame, translation_distance):+ """Take in a frame of rotated skeleton data, and apply the translation distance to each point in the skeleton"""++ translated_skeleton_frame = rotated_skeleton_data_frame - translation_distance+ return translated_skeleton_frame+++# %%+++def translate_skeleton_to_origin(point_to_translate, original_skeleton_data):+ num_frames = original_skeleton_data.shape[0]++ translated_skeleton_data = np.zeros(original_skeleton_data.shape)++ for frame in track(range(num_frames), description="Translating Skeleton"):+ translated_skeleton_data[frame, :, :] = translate_skeleton_frame(+ original_skeleton_data[frame, :, :], point_to_translate+ )++ return translated_skeleton_data+++# %%+++def calculate_skewed_symmetric_cross_product(cross_product_vector):+ # needed in the calculate_rotation_matrix function+ skew_symmetric_cross_product = np.array(+ [+ [0, -cross_product_vector[2], cross_product_vector[1]],+ [cross_product_vector[2], 0, -cross_product_vector[0]],+ [-cross_product_vector[1], cross_product_vector[0], 0],+ ]+ )+ return skew_symmetric_cross_product+++# %%+++def calculate_rotation_matrix(vector1, vector2):+ """Put in two vectors to calculate the rotation matrix between those two vectors"""+ # based on the code found here: https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d"""++ identity_matrix = np.identity(3)+ vector_cross_product = np.cross(vector1, vector2)+ vector_dot_product = np.dot(vector1, vector2)+ skew_symmetric_cross_product = calculate_skewed_symmetric_cross_product(+ vector_cross_product+ )+ rotation_matrix = (+ identity_matrix+ + skew_symmetric_cross_product+ + (np.dot(skew_symmetric_cross_product, skew_symmetric_cross_product))+ * (1 - vector_dot_product)+ / (np.linalg.norm(vector_cross_product) ** 2)+ )++ return rotation_matrix+++# %%+++def rotate_point(point, rotation_matrix):+ rotated_point = np.dot(rotation_matrix, point)+ return rotated_point+++# %%+++def rotate_skeleton_frame(this_frame_aligned_skeleton_data, rotation_matrix):+ """Take in a frame of skeleton data, and apply the rotation matrix to each point in the skeleton"""++ this_frame_rotated_skeleton = np.zeros(+ this_frame_aligned_skeleton_data.shape+ ) # initialize the array to hold the rotated skeleton data for this frame+ num_tracked_points = this_frame_aligned_skeleton_data.shape[0]++ for i in range(num_tracked_points):+ this_frame_rotated_skeleton[i, :] = rotate_point(+ this_frame_aligned_skeleton_data[i, :], rotation_matrix+ )++ return this_frame_rotated_skeleton+++# %%+++def calculate_skeleton_rotation_matrix(+ skeleton_right_vector: np.ndarray,+ skeleton_up_vector: np.ndarray,+ skeleton_forward_vector: np.ndarray,+ world_up_vector: str,+):+ """Calculate the rotation matrix to align the skeleton to the world coordinate system"""++ skel_positive_x = normalize_vector(skeleton_right_vector)+ skel_positive_y = normalize_vector(skeleton_forward_vector)+ skel_positive_z = normalize_vector(skeleton_up_vector)++ z_hat = np.cross(skel_positive_x, skel_positive_y)+ y_hat = np.cross(z_hat, skel_positive_x)+ x_hat = np.cross(y_hat, z_hat)+ z_hat = np.cross(x_hat, y_hat)+ y_hat = np.cross(z_hat, x_hat)++ if (+ world_up_vector == "z"+ ): # biomechanics convention (assumes 'groundplane' is primary XY plane)+ rotation_matrix = np.array([x_hat, y_hat, z_hat])+ elif (+ world_up_vector == "y"+ ): # computer graphics convention (assumes 'viewingplane' is primary XY plane)+ rotation_matrix = np.array([x_hat, z_hat, y_hat])+ elif (+ world_up_vector == "x"+ ): # I don't know of anyone who uses X as vertical, but you do you boo+ rotation_matrix = np.array([z_hat, y_hat, x_hat])+ else:+ raise ValueError("world_up_vector must be one of 'x', 'y', or 'z'")++ assert (+ np.dot(rotation_matrix[0, :], rotation_matrix[1, :]) < sys.float_info.epsilon+ ), "x_hat and y_hat are not orthogonal"+ assert (+ np.dot(rotation_matrix[1, :], rotation_matrix[2, :]) < sys.float_info.epsilon+ ), "y_hat and z_hat are not orthogonal"+ assert (+ np.dot(rotation_matrix[2, :], rotation_matrix[0, :]) < sys.float_info.epsilon+ ), "z_hat and x_hat are not orthogonal"++ return rotation_matrix+++def rotate_align_skeleton(+ positive_x_reference_vector_on_the_skeleton: np.ndarray,+ positive_y_reference_vector_on_the_skeleton: np.ndarray,+ positive_z_reference_vector_on_the_skeleton: np.ndarray,+ world_up_vector: str,+ original_skeleton_np_array: np.ndarray,+) -> np.ndarray:+ """+ Find the rotation matrix needed to rotate the 'reference_vector_on_the_skeleton' to match the 'world_vector_to_align_skeleton_vector_to', and+ rotate the entire skeleton with that matrix.++ Input:+ reference_vector_on_the_skeleton: The vector on the skeleton that you want to rotate/base the rotation matrix on+ world_vector_to_align_skeleton_vector_to: The vector that you want to align the skeleton too (i.e. the x-axis/y-axis etc.)+ Original skeleton data: The freemocap data you want to rotate+ Output:+ rotated_skeleton_data: A numpy data array of your rotated skeleton++ """++ skeleton_original_rotation_matrix = calculate_skeleton_rotation_matrix(+ skeleton_right_vector=positive_x_reference_vector_on_the_skeleton,+ skeleton_up_vector=positive_z_reference_vector_on_the_skeleton,+ skeleton_forward_vector=positive_y_reference_vector_on_the_skeleton,+ world_up_vector=world_up_vector,+ )+ logger.info(+ f"Skeleton original rotation matrix: \n {str(skeleton_original_rotation_matrix)}"+ )+ skeleton_inverse_rotation_matrix = np.linalg.inv(skeleton_original_rotation_matrix)++ logger.info(+ f"Skeleton inverse rotation matrix: \n {skeleton_inverse_rotation_matrix}"+ )++ skeleton_z_vector_rotated = (+ positive_z_reference_vector_on_the_skeleton @ skeleton_inverse_rotation_matrix+ )+ original_z_vector_length = np.sqrt(+ np.sum(positive_z_reference_vector_on_the_skeleton**2)+ )+ rotated_up_vector_length = np.sqrt(np.sum(skeleton_z_vector_rotated**2))++ assert (+ original_z_vector_length - rotated_up_vector_length < 1+ ), f"Rotating the skeleton up vector changed its size -\ something went wrong (original_z_vector_length {original_z_vector_length} - rotated_up_vector_length {rotated_up_vector_length} = {original_z_vector_length - rotated_up_vector_length})"++ skeleton_left_vector_rotated = (+ positive_x_reference_vector_on_the_skeleton @ skeleton_inverse_rotation_matrix+ )++ rotated_left_vector_length = np.sqrt(np.sum(skeleton_left_vector_rotated**2))+ original_x_vector_length = np.sqrt(+ np.sum(positive_x_reference_vector_on_the_skeleton**2)+ )++ assert (+ rotated_left_vector_length - original_x_vector_length < 1+ ), f"Rotating the skeleton left vector changed its size - something went wrong (rotated_left_vector_length {rotated_left_vector_length} - original_x_vector_length {original_x_vector_length} = {rotated_left_vector_length - original_x_vector_length})"++ print(+ f"Skeleton up vector (rounded) - original: {np.round(positive_z_reference_vector_on_the_skeleton)}, rotated: {np.round(skeleton_z_vector_rotated)}"+ )+ print(+ f"Skeleton left vector (rounded) - original: {np.round(positive_x_reference_vector_on_the_skeleton)}, rotated: {np.round(skeleton_left_vector_rotated)}"+ )++ rotated_skeleton_data_array = np.empty(original_skeleton_np_array.shape)+ for frame_number in track(+ range(original_skeleton_np_array.shape[0]), description="Rotating Skeleton..."+ ):+ for point_number in range(original_skeleton_np_array.shape[1]):+ rotated_point_xyz = (+ original_skeleton_np_array[frame_number, point_number, :]+ @ skeleton_inverse_rotation_matrix+ )++ rotated_skeleton_data_array[+ frame_number, point_number, :+ ] = rotated_point_xyz++ return rotated_skeleton_data_array+++# %%+def align_skeleton_with_origin_mean_blob_method(+ skeleton_3d_frame_landmark_xyz: np.ndarray,+) -> np.ndarray:+ """get stats of skeleton postions and align with origin and point upwards based on that"""+ skeleton_3d_frame_landmark_xyz_og = skeleton_3d_frame_landmark_xyz.copy()++ # get the mean of the skeleton+ skel_median_x = np.nanmedian(skeleton_3d_frame_landmark_xyz[:, :, 0])+ skel_median_y = np.nanmedian(skeleton_3d_frame_landmark_xyz[:, :, 1])+ skel_median_z = np.nanmedian(skeleton_3d_frame_landmark_xyz[:, :, 2])++ # translate the skeleton to the origin+ skeleton_3d_frame_landmark_xyz[:, :, 0] = (+ skeleton_3d_frame_landmark_xyz[:, :, 0] - skel_median_x+ )+ skeleton_3d_frame_landmark_xyz[:, :, 1] = (+ skeleton_3d_frame_landmark_xyz[:, :, 1] - skel_median_y+ )+ skeleton_3d_frame_landmark_xyz[:, :, 2] = (+ skeleton_3d_frame_landmark_xyz[:, :, 2] - skel_median_z+ )++ skeleton_3d_frame_landmark_xyz_translated = skeleton_3d_frame_landmark_xyz.copy()++ # pull out head markers to define 'up'+ # (mediapipe - frames 0-10 are the head)+ head_median_x = np.nanmedian(skeleton_3d_frame_landmark_xyz[:10, :, 0])+ head_median_y = np.nanmedian(skeleton_3d_frame_landmark_xyz[:10, :, 1])+ head_median_z = np.nanmedian(skeleton_3d_frame_landmark_xyz[:10, :, 2])++ skeleton_up_vector = np.array([head_median_x, head_median_y, head_median_z])+ world_up_vector = np.array([0, 0, 1])++ # rotate the skeleton to point upwards+ skeleton_3d_frame_landmark_xyz = rotate_align_skeleton(+ reference_vector_on_the_skeleton=skeleton_up_vector,+ world_vector_to_align_skeleton_vector_to=world_up_vector,+ original_skeleton_np_array=skeleton_3d_frame_landmark_xyz,+ )++ return skeleton_3d_frame_landmark_xyz+++def align_skeleton_with_origin_foot_spine_method(+ skeleton_data: np.ndarray, skeleton_indices: list, good_frame: int+) -> np.ndarray:+ """+ Takes in freemocap skeleton data and translates the skeleton to the origin, and then rotates the data+ so that the skeleton is facing the +y direction and standing in the +z direction++ Input:+ skeleton data: a 3D numpy array of skeleton data in freemocap format+ skeleton indices: a list of joints being tracked by mediapipe/your 2d pose estimator+ good frame: the frame that you want to base the rotation on (can be entered manually,+ or use the 'good_frame_finder.py' to calculate it)+ debug: If 'True', display a plot of the raw data and the 3 main alignment stages++ Output:+ spine aligned skeleton data: a 3d numpy array of the origin aligned data in freemocap format+ """++ ## Translate the data such that the midpoint between the two feet is at the origin++ good_skeleton_frame = skeleton_data[good_frame, :, :]++ # the mid point between the two heels+ midpoint_between_heels_xyz = np.mean(+ good_skeleton_frame[+ [skeleton_indices.index("left_heel"), skeleton_indices.index("right_heel")],+ :,+ ],+ axis=0,+ )++ # subtract the mean heel position from the skeleton data (so it is at the origin, )+ skeleton_data_zeroed = skeleton_data.copy()+ skeleton_data_zeroed[:, :, 0] -= midpoint_between_heels_xyz[0]+ skeleton_data_zeroed[:, :, 1] -= midpoint_between_heels_xyz[1]+ skeleton_data_zeroed[:, :, 2] -= midpoint_between_heels_xyz[2]++ # rotate so left heel is on the +Y axis+ right_heel_vector = skeleton_data_zeroed[+ good_frame, skeleton_indices.index("right_heel"), :+ ]++ # Rotating the skeleton so that the spine is aligned with +z+ midpoint_between_hips_xyz = np.mean(+ skeleton_data_zeroed[+ good_frame,+ [skeleton_indices.index("left_hip"), skeleton_indices.index("right_hip")],+ :,+ ],+ axis=0,+ )++ midpoint_between_toes_xyz = np.mean(+ skeleton_data_zeroed[+ good_frame,+ [+ skeleton_indices.index("left_foot_index"),+ skeleton_indices.index("right_foot_index"),+ ],+ :,+ ],+ axis=0,+ )++ origin_aligned_skeleton_data = rotate_align_skeleton(+ positive_x_reference_vector_on_the_skeleton=right_heel_vector,+ positive_y_reference_vector_on_the_skeleton=midpoint_between_toes_xyz,+ positive_z_reference_vector_on_the_skeleton=midpoint_between_hips_xyz,+ world_up_vector="z",+ original_skeleton_np_array=skeleton_data_zeroed,+ )++ return origin_aligned_skeleton_data+++# %%+mediapipe_landmark_names = [+ "nose",+ "left_eye_inner",+ "left_eye",+ "left_eye_outer",+ "right_eye_inner",+ "right_eye",+ "right_eye_outer",+ "left_ear",+ "right_ear",+ "mouth_left",+ "mouth_right",+ "left_shoulder",+ "right_shoulder",+ "left_elbow",+ "right_elbow",+ "left_wrist",+ "right_wrist",+ "left_pinky",+ "right_pinky",+ "left_index",+ "right_index",+ "left_thumb",+ "right_thumb",+ "left_hip",+ "right_hip",+ "left_knee",+ "right_knee",+ "left_ankle",+ "right_ankle",+ "left_heel",+ "right_heel",+ "left_foot_index",+ "right_foot_index",+]+++def return_indices_of_joints(list_of_indices, list_of_joint_names):+ indices = []+ for name in list_of_joint_names:+ this_name_index = list_of_indices.index(name)+ indices.append(this_name_index)++ return indices+++# %%+++def return_XYZ_coordinates_of_markers(freemocap_data, indices_list, frame):+ XYZ_coordinates = []+ for index in indices_list:+ this_joint_coordinate = freemocap_data[frame, index, :]+ XYZ_coordinates.append(this_joint_coordinate)++ return XYZ_coordinates+++# %%+++def build_virtual_trunk_marker(+ freemocap_data, list_of_indices, trunk_joint_connection, frame+):+ trunk_marker_indices = return_indices_of_joints(+ list_of_indices, trunk_joint_connection+ )++ trunk_XYZ_coordinates = return_XYZ_coordinates_of_markers(+ freemocap_data, trunk_marker_indices, frame+ )++ trunk_proximal = (trunk_XYZ_coordinates[0] + trunk_XYZ_coordinates[1]) / 2+ trunk_distal = (trunk_XYZ_coordinates[2] + trunk_XYZ_coordinates[3]) / 2++ return trunk_proximal, trunk_distal+++# %%+++def build_mediapipe_skeleton(+ mediapipe_pose_data, segment_dataframe, mediapipe_indices+) -> list:+ """This function takes in the mediapipe pose data array and the segment_conn_len_perc_dataframe.+ For each frame of data, it loops through each segment we want to find and identifies the names+ of the proximal and distal joints of that segment. Then it searches the mediapipe_indices list+ to find the index that corresponds to the name of that segment. We plug the index into the+ mediapipe_pose_data array to find the proximal/distal joints' XYZ coordinates at that frame.+ The segment, its proximal joint and its distal joint gets thrown into a dictionary.+ And then that dictionary gets saved to a list for each frame. By the end of the function, you+ have a list that contains the skeleton segment XYZ coordinates for each frame."""++ num_frames = mediapipe_pose_data.shape[0]+ num_frame_range = range(num_frames)++ mediapipe_frame_segment_joint_XYZ = (+ []+ ) # empty list to hold all the skeleton XYZ coordinates/frame++ for frame in track(num_frame_range, description="Building a MediaPipe Skeleton"):++ trunk_joint_connection = [+ "left_shoulder",+ "right_shoulder",+ "left_hip",+ "right_hip",+ ]+ trunk_virtual_markers = build_virtual_trunk_marker(+ mediapipe_pose_data, mediapipe_indices, trunk_joint_connection, frame+ )++ mediapipe_pose_skeleton_coordinates = {}+ for (+ segment,+ segment_info,+ ) in (+ segment_dataframe.iterrows()+ ): # iterate through the data frame by the segment name and all the info for that segment+ if segment == "trunk":++ # based on index, excract coordinate data from fmc mediapipe data+ mediapipe_pose_skeleton_coordinates[segment] = [+ trunk_virtual_markers[0],+ trunk_virtual_markers[1],+ ]+ elif segment == "left_hand" or segment == "right_hand":+ proximal_joint_hand = segment_info["Joint_Connection"][0]+ if segment == "left_hand":+ distal_joint_hand = "left_index"+ else:+ distal_joint_hand = "right_index"++ proximal_joint_hand_index = mediapipe_indices.index(proximal_joint_hand)+ distal_joint_hand_index = mediapipe_indices.index(distal_joint_hand)++ mediapipe_pose_skeleton_coordinates[segment] = [+ mediapipe_pose_data[frame, proximal_joint_hand_index, :],+ mediapipe_pose_data[frame, distal_joint_hand_index, :],+ ]++ elif segment == "left_foot" or segment == "right_foot":+ if segment == "left_foot":+ proximal_joint_foot_name = "left_ankle"+ else:+ proximal_joint_foot_name = "right_ankle"++ proximal_joint_foot_index = mediapipe_indices.index(+ proximal_joint_foot_name+ )++ distal_joint_foot = segment_info["Joint_Connection"][1]+ distal_joint_foot_index = mediapipe_indices.index(distal_joint_foot)+ mediapipe_pose_skeleton_coordinates[segment] = [+ mediapipe_pose_data[frame, proximal_joint_foot_index, :],+ mediapipe_pose_data[frame, distal_joint_foot_index, :],+ ]++ else:+ proximal_joint_name = segment_info["Joint_Connection"][0]+ distal_joint_name = segment_info["Joint_Connection"][1]++ # get the mediapipe index for the proximal and distal joint for this segment+ proximal_joint_index = mediapipe_indices.index(proximal_joint_name)+ distal_joint_index = mediapipe_indices.index(distal_joint_name)++ # use the mediapipe indices to get the XYZ coordinates for the prox/distal joints and throw it in a dictionary+ # mediapipe_pose_skeleton_coordinates[segment] = {'proximal':mediapipe_pose_data[frame,proximal_joint_index,:],'distal':mediapipe_pose_data[frame,distal_joint_index,:]}+ mediapipe_pose_skeleton_coordinates[segment] = [+ mediapipe_pose_data[frame, proximal_joint_index, :],+ mediapipe_pose_data[frame, distal_joint_index, :],+ ]++ mediapipe_frame_segment_joint_XYZ.append(mediapipe_pose_skeleton_coordinates)+ f = 2++ return mediapipe_frame_segment_joint_XYZ+++# %%+# values for segment weight and segment mass percentages taken from Winter anthropometry tables+# https://imgur.com/a/aD74j+# Winter, D.A. (2005) Biomechanics and Motor Control of Human Movement. 3rd Edition, John Wiley & Sons, Inc., Hoboken.+++segments = [+ "head",+ "trunk",+ "right_upper_arm",+ "left_upper_arm",+ "right_forearm",+ "left_forearm",+ "right_hand",+ "left_hand",+ "right_thigh",+ "left_thigh",+ "right_shin",+ "left_shin",+ "right_foot",+ "left_foot",+]++joint_connections = [+ ["left_ear", "right_ear"],+ ["mid_chest_marker", "mid_hip_marker"],+ ["right_shoulder", "right_elbow"],+ ["left_shoulder", "left_elbow"],+ ["right_elbow", "right_wrist"],+ ["left_elbow", "left_wrist"],+ ["right_wrist", "right_hand_marker"],+ ["left_wrist", "left_hand_marker"],+ ["right_hip", "right_knee"],+ ["left_hip", "left_knee"],+ ["right_knee", "right_ankle"],+ ["left_knee", "left_ankle"],+ ["right_back_of_foot_marker", "right_foot_index"],+ ["left_back_of_foot_marker", "left_foot_index"],+]++segment_COM_lengths = [+ 0.5,+ 0.5,+ 0.436,+ 0.436,+ 0.430,+ 0.430,+ 0.506,+ 0.506,+ 0.433,+ 0.433,+ 0.433,+ 0.433,+ 0.5,+ 0.5,+]++segment_COM_percentages = [+ 0.081,+ 0.497,+ 0.028,+ 0.028,+ 0.016,+ 0.016,+ 0.006,+ 0.006,+ 0.1,+ 0.1,+ 0.0465,+ 0.0465,+ 0.0145,+ 0.0145,+]+++# %%+def calculate_segment_COM(+ segment_conn_len_perc_dataframe,+ skelcoordinates_frame_segment_joint_XYZ,+ num_frame_range,+):+ segment_COM_frame_dict = []+ for frame in track(+ num_frame_range, description="Calculating Segment Center of Mass"+ ):+ segment_COM_dict = {}+ for segment, segment_info in segment_conn_len_perc_dataframe.iterrows():+ this_segment_XYZ = skelcoordinates_frame_segment_joint_XYZ[frame][segment]++ # for mediapipe+ this_segment_proximal = this_segment_XYZ[0]+ this_segment_distal = this_segment_XYZ[1]+ this_segment_COM_length = segment_info["Segment_COM_Length"]++ this_segment_COM = this_segment_proximal + this_segment_COM_length * (+ this_segment_distal - this_segment_proximal+ )+ segment_COM_dict[segment] = this_segment_COM+ segment_COM_frame_dict.append(segment_COM_dict)+ return segment_COM_frame_dict+++# %%+++def reformat_segment_COM(segment_COM_frame_dict, num_frame_range, num_segments):+ segment_COM_frame_imgPoint_XYZ = np.empty(+ [int(len(num_frame_range)), int(num_segments), 3]+ )+ for frame in num_frame_range:+ this_frame_skeleton = segment_COM_frame_dict[frame]+ for joint_count, segment in enumerate(this_frame_skeleton.keys()):+ segment_COM_frame_imgPoint_XYZ[frame, joint_count, :] = this_frame_skeleton[+ segment+ ]+ return segment_COM_frame_imgPoint_XYZ+++# %%+++def calculate_total_body_COM(+ segment_conn_len_perc_dataframe, segment_COM_frame_dict, num_frame_range+):+ logger.info("Calculating Total Body Center of Mass")+ totalBodyCOM_frame_XYZ = np.empty([int(len(num_frame_range)), 3])++ for frame in track(+ num_frame_range, description="Calculating Total Body Center of Mass..."+ ):++ this_frame_total_body_percentages = []+ this_frame_skeleton = segment_COM_frame_dict[frame]++ for segment, segment_info in segment_conn_len_perc_dataframe.iterrows():+ this_segment_COM = this_frame_skeleton[segment]+ this_segment_COM_percentage = segment_info["Segment_COM_Percentage"]++ this_segment_total_body_percentage = (+ this_segment_COM * this_segment_COM_percentage+ )+ this_frame_total_body_percentages.append(this_segment_total_body_percentage)++ this_frame_total_body_COM = np.nansum(this_frame_total_body_percentages, axis=0)++ totalBodyCOM_frame_XYZ[frame, :] = this_frame_total_body_COM++ f = 2+ return totalBodyCOM_frame_XYZ+++# %%+++def build_anthropometric_dataframe(+ segments: list,+ joint_connections: list,+ segment_COM_lengths: list,+ segment_COM_percentages: list,+) -> pd.DataFrame:+ # load anthropometric data into a pandas dataframe+ df = pd.DataFrame(+ list(+ zip(+ segments,+ joint_connections,+ segment_COM_lengths,+ segment_COM_percentages,+ )+ ),+ columns=[+ "Segment_Name",+ "Joint_Connection",+ "Segment_COM_Length",+ "Segment_COM_Percentage",+ ],+ )+ segment_conn_len_perc_dataframe = df.set_index("Segment_Name")+ return segment_conn_len_perc_dataframe+++def calculate_center_of_mass(+ freemocap_marker_data_array: np.ndarray,+ pose_estimation_skeleton: list,+ anthropometric_info_dataframe: pd.DataFrame,+):+ num_frames = freemocap_marker_data_array.shape[0]+ num_frame_range = range(num_frames)+ num_segments = len(anthropometric_info_dataframe)++ segment_COM_frame_dict = calculate_segment_COM(+ anthropometric_info_dataframe, pose_estimation_skeleton, num_frame_range+ )+ segment_COM_frame_imgPoint_XYZ = reformat_segment_COM(+ segment_COM_frame_dict, num_frame_range, num_segments+ )+ totalBodyCOM_frame_XYZ = calculate_total_body_COM(+ anthropometric_info_dataframe, segment_COM_frame_dict, num_frame_range+ )++ return (+ segment_COM_frame_dict,+ segment_COM_frame_imgPoint_XYZ,+ totalBodyCOM_frame_XYZ,+ )+++# %%+def are_there_feet_in_this_mediapipe_skeleton_data(+ skeleton3d_frame_landmark_xyz, mediapipe_landmark_names+):+ number_of_frames = skeleton3d_frame_landmark_xyz.shape[0]++ number_nan_left_heel = np.sum(+ np.isnan(+ skeleton3d_frame_landmark_xyz[+ :, mediapipe_landmark_names.index("left_heel"), 0+ ]+ )+ )+ number_nan_right_heel = np.sum(+ np.isnan(+ skeleton3d_frame_landmark_xyz[+ :, mediapipe_landmark_names.index("right_heel"), 0+ ]+ )+ )+ number_nan_left_toe = np.sum(+ np.isnan(+ skeleton3d_frame_landmark_xyz[+ :, mediapipe_landmark_names.index("left_foot_index"), 0+ ]+ )+ )+ number_nan_right_toe = np.sum(+ np.isnan(+ skeleton3d_frame_landmark_xyz[+ :, mediapipe_landmark_names.index("right_foot_index"), 0+ ]+ )+ )++ no_left_heel = number_nan_left_heel == number_of_frames+ no_right_heel = number_nan_right_heel == number_of_frames+ no_left_toe = number_nan_left_toe == number_of_frames+ no_right_toe = number_nan_right_toe == number_of_frames++ if no_left_heel and no_right_heel and no_left_toe and no_right_toe:+ return False+ else:+ return True+++def gap_fill_filter_origin_align_3d_data_and_then_calculate_center_of_mass(+ skel3d_frame_marker_xyz: np.ndarray,+ skeleton_reprojection_error_fr_mar: np.ndarray,+ path_to_folder_where_we_will_save_this_data: [str, Path],+ # Filter the data, set the filtering options here+ sampling_rate: Union[float, int],+ cut_off: Union[float, int],+ order: Union[float, int],+ reference_frame_number: Union[float, int] = None,+):+ path_to_folder_where_we_will_save_this_data = Path(path_to_folder_where_we_will_save_this_data)++ logger.info("Gap-filling data...")+ # Interpolate the data+ freemocap_interpolated_data = fill_gaps_in_freemocap_data(skel3d_frame_marker_xyz)++ logger.info(+ f"Filtering data at with a {order}th order, zero-lag, low-pass Butterworth filter with a cut-off frequency of {cut_off} Hz..."+ )+ butterworth_filtered_skeleton_data = butterworth_filter_skeleton(+ freemocap_interpolated_data, cut_off, sampling_rate, order+ )++ # pin skeleton to origin (set to mean positin of skeletonin this recording)+ zeroed_skeleton_data = butterworth_filtered_skeleton_data.copy()+ zeroed_skeleton_data[:,:,0] -= np.nanmean(zeroed_skeleton_data[:,:,0])+ zeroed_skeleton_data[:,:,1] -= np.nanmean(zeroed_skeleton_data[:,:,1])+ zeroed_skeleton_data[:,:,2] -= np.nanmean(zeroed_skeleton_data[:,:,2])++ # TODO - align skeleton so feet are at Z-plane and head is facing up+ origin_aligned_freemocap_marker_data = zeroed_skeleton_data.copy()+ # logger.info("Aligning data to the origin...")++ # reference_frame_number = find_good_clean_frame_reprojection_error_method(+ # skeleton_3d_fr_mar_xyz=freemocap_filtered_marker_data,+ # skeleton_reprojection_error_fr_mar=skeleton_reprojection_error_fr_mar,+ # )++ # has_feet = are_there_feet_in_this_mediapipe_skeleton_data(+ # butterworth_filtered_skeleton_data, mediapipe_landmark_names+ # )+ # if has_feet:+ # reference_frame_number = find_good_frame_recursive_guess_method(+ # butterworth_filtered_skeleton_data, mediapipe_landmark_names, 0.3+ # )+ #+ # logger.info("Using the foot/spine method of alignment...")+ # origin_aligned_freemocap_marker_data = (+ # align_skeleton_with_origin_foot_spine_method(+ # butterworth_filtered_skeleton_data,+ # mediapipe_landmark_names,+ # reference_frame_number,+ # )+ # )+ # else: # no feet+ # logger.info("Using the skelly blob method of alignment...")+ # origin_aligned_freemocap_marker_data = (+ # align_skeleton_with_origin_mean_blob_method(+ # butterworth_filtered_skeleton_data+ # )+ # )++ logger.info("Saving Origin Aligned Data")+ Path(path_to_folder_where_we_will_save_this_data).mkdir(+ parents=True, exist_ok=True+ )+ np.save(+ str(+ path_to_folder_where_we_will_save_this_data+ / "mediaPipeSkel_3d_origin_aligned"+ ),+ origin_aligned_freemocap_marker_data,+ )++ # Calculate segment and total body COM+ anthropometric_info_dataframe = build_anthropometric_dataframe(+ segments, joint_connections, segment_COM_lengths, segment_COM_percentages+ )+ skelcoordinates_frame_segment_joint_XYZ = build_mediapipe_skeleton(+ origin_aligned_freemocap_marker_data,+ anthropometric_info_dataframe,+ mediapipe_landmark_names,+ )+ (+ segment_COM_frame_dict,+ segment_COM_frame_imgPoint_XYZ,+ totalBodyCOM_frame_XYZ,+ ) = calculate_center_of_mass(+ origin_aligned_freemocap_marker_data,+ skelcoordinates_frame_segment_joint_XYZ,+ anthropometric_info_dataframe,+ )+ Path(path_to_folder_where_we_will_save_this_data / CENTER_OF_MASS_FOLDER_NAME).mkdir(+ parents=True, exist_ok=True+ )+ np.save(+ str(+ path_to_folder_where_we_will_save_this_data+ / CENTER_OF_MASS_FOLDER_NAME+ / SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME+ ),+ segment_COM_frame_imgPoint_XYZ,+ )+ np.save(+ str(+ path_to_folder_where_we_will_save_this_data+ / CENTER_OF_MASS_FOLDER_NAME+ / TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME+ ),+ totalBodyCOM_frame_XYZ,+ )++ logger.info("Done with gap filling, filtering, aligning, and COM calculation")+ return origin_aligned_freemocap_marker_data+++if __name__ == "__main__":+ mediapipe_3d_frame_trackedPoint_xyz = np.load(+ r"C:\Users\jonma\freemocap_data\session_10-15-2022-09_50_10\output_data\raw_data\mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy"+ )+ skeleton_reprojection_error_fr_mar = np.load(+ r"C:\Users\jonma\freemocap_data\session_10-15-2022-09_50_10\output_data\raw_data\mediapipe_3dData_numFrames_numTrackedPoints_reprojectionError.npy"+ )+ output_data_folder_path = (+ r"C:\Users\jonma\freemocap_data\session_10-15-2022-09_50_10\output_data"+ )+ gap_fill_filter_origin_align_3d_data_and_then_calculate_center_of_mass(+ mediapipe_3d_frame_trackedPoint_xyz,+ skeleton_reprojection_error_fr_mar=skeleton_reprojection_error_fr_mar,+ path_to_folder_where_we_will_save_this_data=output_data_folder_path,+ sampling_rate=30,+ cut_off=7,+ order=4,+ reference_frame_number=None,+ )+ print("Done :D ")diff --git a/src/diagnostic_plot_makers/__init__.py b/src/diagnostic_plot_makers/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/diagnostic_plot_makers/create_3d_data_diagnostic_plots.py b/src/diagnostic_plot_makers/create_3d_data_diagnostic_plots.pynew file mode 100644index 00000000..b93e1fb4--- /dev/null+++ b/src/diagnostic_plot_makers/create_3d_data_diagnostic_plots.py@@ -0,0 +1,61 @@+import logging+from pathlib import Path+from typing import Union++import numpy as np++from src.core_processes.mediapipe_stuff.mediapipe_skeleton_names_and_connections import (+ mediapipe_body_landmark_names,+)++logger = logging.getLogger(__name__)+++def create_3d_data_diagnostic_plots(+ spatial_data3d_numFrames_numTrackedPoints_XYZ: np.ndarray,+ reprojection_error_data3d_numCams_numFrames_numTrackedPoints_error: np.ndarray,+ path_to_save_plots: Union[str, Path],+):+ """+ Create diagnostic plots for spot checking 3d data+ """++ logger.info("Creating 3d data diagnostic plots")+ # opportunistic load of matplotlib to avoid startup time costs+ from matplotlib import pyplot as plt++ plt.set_loglevel("warning")++ mean_reprojection_error_numFrames_numLandmark = np.mean(+ reprojection_error_data3d_numCams_numFrames_numTrackedPoints_error, axis=0+ )++ fig = plt.figure(figsize=(18, 10))+ ax1 = plt.subplot(411, title="X Data", xlabel="Frame#", ylabel="X position(mm)")+ ax2 = plt.subplot(412, title="Y Data", xlabel="Frame#", ylabel="Y position(mm)")+ ax3 = plt.subplot(413, title="Z Data", xlabel="Frame#", ylabel="Z position(mm)")+ ax4 = plt.subplot(+ 414, title="Reprojection Error", xlabel="Frame#", ylabel="Error(mm)"+ )++ ax1.plot(spatial_data3d_numFrames_numTrackedPoints_XYZ[:, :, 0])+ ax1.legend(mediapipe_body_landmark_names)++ ax2.plot(spatial_data3d_numFrames_numTrackedPoints_XYZ[:, :, 1])+ ax2.legend(mediapipe_body_landmark_names)++ ax3.plot(spatial_data3d_numFrames_numTrackedPoints_XYZ[:, :, 2])+ ax3.legend(mediapipe_body_landmark_names)++ ax4.plot(mean_reprojection_error_numFrames_numLandmark[:, :, 0])+ ax4.legend(mediapipe_body_landmark_names)++ fig.savefig(path_to_save_plots)++ logger.info(f"Saving diagnostic figure as png")+ import matplotlib++ matplotlib.use("QtAgg")+ plt.show()+ plt.pause(0.1)+ f = 9diff --git a/src/cameras/create_timestamp_diagnostic_plots.py b/src/diagnostic_plot_makers/create_timestamp_diagnostic_plots.pysimilarity index 100%rename from src/cameras/create_timestamp_diagnostic_plots.pyrename to src/diagnostic_plot_makers/create_timestamp_diagnostic_plots.pydiff --git a/src/debug_plot_makers/simple_plot_3d_points.py b/src/diagnostic_plot_makers/simple_plot_3d_points.pysimilarity index 68%rename from src/debug_plot_makers/simple_plot_3d_points.pyrename to src/diagnostic_plot_makers/simple_plot_3d_points.pyindex 006e9b3b..11c66840 100644--- a/src/debug_plot_makers/simple_plot_3d_points.py+++ b/src/diagnostic_plot_makers/simple_plot_3d_points.py@@ -13,3 +13,10 @@ def simple_plot_3d(data_pt_xyz):ax3d.scatter(x, y, z)plt.pause(0.1)plt.show()+++if __name__ == "__main__":+ import numpy as np++ data_pt_xyz = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])+ simple_plot_3d(data_pt_xyz)diff --git a/src/experiments/cv_cam_multi_process.py b/src/experiments/cv_cam_multi_process.pyindex 69e8a89b..58514816 100644--- a/src/experiments/cv_cam_multi_process.py+++ b/src/experiments/cv_cam_multi_process.py@@ -1,18 +1,14 @@import loggingimport multiprocessingimport platform-import threadingimport timeimport traceback-from multiprocessing import Process, Queue-from typing import Union+from multiprocessing import Processimport cv2from src.cameras.capture.dataclasses.frame_payload import FramePayload-from src.cameras.capture.opencv_camera.opencv_camera import OpenCVCamera-from src.cameras.detection.cam_singleton import get_or_create_cams-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfiglogger = logging.getLogger(__name__)diff --git a/src/experiments/viewers.py b/src/experiments/viewers.pyindex 6f11dfe9..f5d51a51 100644--- a/src/experiments/viewers.py+++ b/src/experiments/viewers.py@@ -2,7 +2,7 @@ import asynciofrom src.cameras.capture.opencv_camera.opencv_camera import OpenCVCamerafrom src.cameras.detection.cam_singleton import get_or_create_cams-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigasync def imshow_testing():diff --git a/src/export_stuff/blender_stuff/get_best_guess_of_blender_path.py b/src/export_stuff/blender_stuff/get_best_guess_of_blender_path.pydeleted file mode 100644index 245bba43..00000000--- a/src/export_stuff/blender_stuff/get_best_guess_of_blender_path.py+++ /dev/null@@ -1,30 +0,0 @@-import logging-import platform-from pathlib import Path--logger = logging.getLogger(__name__)---def get_best_guess_of_blender_path():- if platform.system() == "Windows":- try:- base_path = Path("C:\Program Files\Blender Foundation")- blender_folder_path = [path for path in base_path.glob("Blender*")]- blender_exe_path = blender_folder_path[0] / "blender.exe"- logger.info(- f"Windows machine detected - guessing that `blender` is installed at: {str(blender_exe_path)}"- )-- if blender_exe_path.is_file():- return str(blender_exe_path)- except Exception as e:- print(e)- logger.warning(- "Couldn't find Blender path automatically, need to select it manually"- )-- return None-- else:- logger.info(f"Non-Windows machine detected - TODO - This, lol")- return Nonediff --git a/src/gui/icis_conference_main/icis_conference_main.py b/src/gui/icis_conference_main/icis_conference_main.pyindex 86c03df6..7fee737b 100644--- a/src/gui/icis_conference_main/icis_conference_main.py+++ b/src/gui/icis_conference_main/icis_conference_main.py@@ -22,7 +22,9 @@ if __name__ == "__main__":app = get_qt_app()timer = QTimer()timer.start(500)- timer.timeout.connect(lambda: None) # Let the interpreter run each 500 ms.+ timer.timeout.connect(+ lambda: None+ ) # Let the interpreter calculate_center_of_mass each 500 ms.win = ICISConferenceMainWindow()# win = SlopMainWindow()win.show()diff --git a/src/gui/icis_conference_main/qt_widgets/jupyter_console_widget.py b/src/gui/icis_conference_main/qt_widgets/jupyter_console_widget.pyindex 24331fd9..a4b033ae 100644--- a/src/gui/icis_conference_main/qt_widgets/jupyter_console_widget.py+++ b/src/gui/icis_conference_main/qt_widgets/jupyter_console_widget.py@@ -25,7 +25,7 @@ try:from qtconsole import inprocessexcept:print(- "The example in `jupyter_console_example.py` requires `qtconsole` to run. Install with `pip install qtconsole` or equivalent."+ "The example in `jupyter_console_example.py` requires `qtconsole` to calculate_center_of_mass. Install with `pip install qtconsole` or equivalent.")diff --git a/src/gui/icis_conference_main/workers/cam_charuco_frame_worker.py b/src/gui/icis_conference_main/workers/cam_charuco_frame_worker.pyindex 4a2fc106..edf4e60f 100644--- a/src/gui/icis_conference_main/workers/cam_charuco_frame_worker.py+++ b/src/gui/icis_conference_main/workers/cam_charuco_frame_worker.py@@ -3,7 +3,7 @@ from PyQt6.QtCore import QThread, Qt, pyqtSignalfrom PyQt6.QtGui import QImagefrom src.cameras.capture.opencv_camera.opencv_camera import OpenCVCamera-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigfrom src.gui.icis_conference_main.state.app_state import APP_STATEfrom src.core_processes.capture_volume_calibration.charuco_board_detection.charuco_board_detector import (CharucoBoardDetector,diff --git a/src/gui/icis_conference_main/workers/cam_frame_worker.py b/src/gui/icis_conference_main/workers/cam_frame_worker.pyindex 60ec9857..d68cd42d 100644--- a/src/gui/icis_conference_main/workers/cam_frame_worker.py+++ b/src/gui/icis_conference_main/workers/cam_frame_worker.py@@ -3,7 +3,7 @@ from PyQt6.QtCore import QThread, Qt, pyqtSignalfrom PyQt6.QtGui import QImagefrom src.cameras.capture.opencv_camera.opencv_camera import OpenCVCamera-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigclass CamFrameWorker(QThread):diff --git a/src/gui/icis_conference_main/workflows/record_videos.py b/src/gui/icis_conference_main/workflows/record_videos.pyindex c826bd62..97e44096 100644--- a/src/gui/icis_conference_main/workflows/record_videos.py+++ b/src/gui/icis_conference_main/workflows/record_videos.py@@ -13,7 +13,7 @@ from src.core_processes.mediapipe_stuff.mediapipe_skeleton_detector import ()from src.gui.icis_conference_main.state.app_state import APP_STATEfrom src.gui.icis_conference_main.workflows.single_camera import SingleCamera-from src.export_stuff.blender_stuff.export_to_blender import (+from src.blender_stuff import (export_to_blender,)from src.pipelines.calibration_pipeline.calibration_pipeline_orchestrator import (diff --git a/src/gui/main/custom_widgets/single_camera_widget.py b/src/gui/main/custom_widgets/single_camera_widget.pyindex 24ebad6e..2cc22741 100644--- a/src/gui/main/custom_widgets/single_camera_widget.py+++ b/src/gui/main/custom_widgets/single_camera_widget.py@@ -3,9 +3,9 @@ import enumfrom PyQt6 import QtGuifrom PyQt6.QtCore import pyqtSignal, Qtfrom PyQt6.QtGui import QPixmap-from PyQt6.QtWidgets import QHBoxLayout, QWidget, QLabel, QFrame, QVBoxLayout+from PyQt6.QtWidgets import QWidget, QLabel, QFrame, QVBoxLayout-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigfrom src.gui.main.workers.cam_charuco_frame_thread_worker import (CamCharucoFrameThreadWorker,)diff --git a/src/gui/main/main.py b/src/gui/main/main.pyindex 78b62d6e..9bb69cf2 100644--- a/src/gui/main/main.py+++ b/src/gui/main/main.py@@ -33,7 +33,9 @@ if __name__ == "__main__":app.setStyleSheet(qt_app_css_style_sheet)timer = QTimer()timer.start(500)- timer.timeout.connect(lambda: None) # Let the interpreter run each 500 ms.+ timer.timeout.connect(+ lambda: None+ ) # Let the interpreter calculate_center_of_mass each 500 ms.while True:# rebootable GUI method based on this - https://stackoverflow.com/a/56563926/14662833diff --git a/src/gui/main/main_window/left_panel_controls/toolbox_widgets/camera_setup_control_panel.py b/src/gui/main/main_window/left_panel_controls/toolbox_widgets/camera_setup_control_panel.pyindex fa0d0755..5d88ba04 100644--- a/src/gui/main/main_window/left_panel_controls/toolbox_widgets/camera_setup_control_panel.py+++ b/src/gui/main/main_window/left_panel_controls/toolbox_widgets/camera_setup_control_panel.py@@ -6,14 +6,13 @@ from PyQt6.QtWidgets import (QVBoxLayout,QWidget,QPushButton,- QTextEdit,QLabel,QHBoxLayout,)from pyqtgraph.parametertree import ParameterTree, Parameterfrom src.cameras.detection.models import FoundCamerasResponse-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigfrom src.gui.main.qt_utils.clear_layout import clear_layoutimport loggingdiff --git a/src/gui/main/main_window/left_panel_controls/toolbox_widgets/process_session_data_panel.py b/src/gui/main/main_window/left_panel_controls/toolbox_widgets/process_session_data_panel.pyindex 174f3689..06bb28e8 100644--- a/src/gui/main/main_window/left_panel_controls/toolbox_widgets/process_session_data_panel.py+++ b/src/gui/main/main_window/left_panel_controls/toolbox_widgets/process_session_data_panel.py@@ -1,7 +1,5 @@import logging-import numpy as np-from PyQt6 import QtCorefrom PyQt6.QtWidgets import (QWidget,QVBoxLayout,@@ -13,12 +11,12 @@ from PyQt6.QtWidgets import (QLabel,)+from src.blender_stuff.get_best_guess_of_blender_path import (+ get_best_guess_of_blender_path,+)from src.core_processes.mediapipe_stuff.mediapipe_default_settings import (default_mediapipe_confidence_threshold,)-from src.export_stuff.blender_stuff.get_best_guess_of_blender_path import (- get_best_guess_of_blender_path,-)from src.gui.main.tool_tips.tool_tips_strings import (mediapipe_confidence_cutoff_tool_tip_str,@@ -48,11 +46,26 @@ class ProcessSessionDataPanel(QWidget):self._triangulate_3d_data_button.setEnabled(True)self._layout.addWidget(self._triangulate_3d_data_button)+ self._use_triangulate_ransac_checkbox = QCheckBox(+ "Use `anipose.triangulate_ransac() - EXPERIMENTAL"+ )+ self._use_triangulate_ransac_checkbox.setChecked(False)+ self._layout.addWidget(self._use_triangulate_ransac_checkbox)+self._mediapipe_confidence_cutoff_form_layout = (self._make_mediapipe_confidence_cutoff_layout())self._layout.addLayout(self._mediapipe_confidence_cutoff_form_layout)+ self._gap_fill_filter_origin_align_button = QPushButton(+ "Gap Fill, Butterworth Filter, and Origin Align Skeleton data (experimental)"+ )+ self._layout.addWidget(self._gap_fill_filter_origin_align_button)++ self._visualize_freemocap_session_button = QPushButton(+ "Visualize Freemocap Session"+ )+self._convert_npy_to_csv_checkbox = QCheckBox("Convert 3D npy data to csv (experimental)")@@ -82,6 +95,10 @@ class ProcessSessionDataPanel(QWidget):def mediapipe_confidence_cutoff_threshold(self) -> float:return float(self._mediapipe_confidence_cutoff_line_edit_widget.text())+ @property+ def use_triangulate_ransac_checkbox(self):+ return self._use_triangulate_ransac_checkbox+@propertydef convert_npy_to_csv_checkbox(self):return self._convert_npy_to_csv_checkbox@@ -90,6 +107,10 @@ class ProcessSessionDataPanel(QWidget):def triangulate_3d_data_button(self):return self._triangulate_3d_data_button+ @property+ def gap_fill_filter_origin_align_button(self):+ return self._gap_fill_filter_origin_align_button+@propertydef open_in_blender_button(self):diff --git a/src/gui/main/main_window/main_window.py b/src/gui/main/main_window/main_window.pyindex 513b83c6..d518fe60 100644--- a/src/gui/main/main_window/main_window.py+++ b/src/gui/main/main_window/main_window.py@@ -3,10 +3,12 @@ import shutilfrom pathlib import Pathfrom typing import Union+import pandas as pdfrom PyQt6 import QtGuifrom PyQt6.QtGui import QAction-from PyQt6.QtWidgets import QMainWindow, QSplitter, QFileDialog, QMenuBar, QMenu, QLabel+from PyQt6.QtWidgets import QMainWindow, QSplitter, QFileDialog, QMenuBar, QMenu+from src.blender_stuff.export_to_blender import export_to_blenderfrom src.cameras.detection.models import FoundCamerasResponsefrom src.config.home_dir import (get_calibration_videos_folder_path,@@ -17,6 +19,9 @@ from src.config.home_dir import (get_most_recent_session_id,get_freemocap_data_folder_path,get_annotated_videos_folder_path,+ get_skeleton_body_csv_path,+ get_blender_file_path, get_raw_data_folder_path, PARTIALLY_PROCESSED_DATA_FOLDER_NAME,+ MEDIAPIPE_3D_ORIGIN_ALIGNED_NPY_FILE_NAME,)from src.core_processes.capture_volume_calibration.charuco_board_detection.dataclasses.charuco_board_definition import (CharucoBoardDefinition,@@ -24,17 +29,22 @@ from src.core_processes.capture_volume_calibration.charuco_board_detection.datacfrom src.core_processes.capture_volume_calibration.get_anipose_calibration_object import (load_most_recent_anipose_calibration_toml,load_calibration_from_session_id,- load_anipose_calibration_toml_from_user_selection,+ load_anipose_calibration_toml_from_path,)from src.core_processes.mediapipe_stuff.load_mediapipe2d_data import (load_mediapipe2d_data,)from src.core_processes.mediapipe_stuff.load_mediapipe3d_data import (- load_mediapipe3d_data,+ load_raw_mediapipe3d_data,+ load_post_processed_mediapipe3d_data,+ load_skeleton_reprojection_error_data,)-from src.export_stuff.blender_stuff.export_to_blender import (- export_to_blender,+from src.core_processes.post_process_skeleton_data.estimate_skeleton_segment_lengths import (+ mediapipe_skeleton_segment_definitions,+ estimate_skeleton_segment_lengths,+ save_skeleton_segment_lengths_to_json,)+from src.gui.main.app import get_qt_appfrom src.gui.main.app_state.app_state import APP_STATEfrom src.gui.main.main_window.left_panel_controls.control_panel import ControlPanel@@ -62,6 +72,7 @@ logger = logging.getLogger(__name__)class MainWindow(QMainWindow):def __init__(self):+ self._pipedream_ping_dictionary = {"gui_window": "launched"}logger.info("Creating main window")super().__init__()@@ -90,7 +101,7 @@ class MainWindow(QMainWindow):self._main_layout.addWidget(self._right_side_panel.frame)- self._thread_worker_manager = ThreadWorkerManager()+ self._thread_worker_manager = ThreadWorkerManager(session_progress_dictionary = self._pipedream_ping_dictionary )# actions, signals and slots, o myself._create_actions()@@ -386,6 +397,10 @@ class MainWindow(QMainWindow):self._setup_and_launch_triangulate_3d_thread_worker)+ self._control_panel.process_session_data_panel.gap_fill_filter_origin_align_button.clicked.connect(+ self._setup_and_launch_gap_fill_filter_origin_align_thread_worker+ )+self._control_panel.process_session_data_panel.open_in_blender_button.clicked.connect(self._export_to_blender)@@ -433,6 +448,18 @@ class MainWindow(QMainWindow):))+ self._thread_worker_manager.start_post_processing_signal.connect(+ lambda: self._setup_and_launch_gap_fill_filter_origin_align_thread_worker(+ auto_process_next_stage=True+ )+ )++ self._thread_worker_manager.start_convert_npy_to_to_csv_signal.connect(+ lambda: self._setup_and_launch_convert_npy_to_csv_thread_worker(+ auto_process_next_stage=False+ )+ )+self._thread_worker_manager.start_blender_processing_signal.connect(self._export_to_blender)@@ -489,10 +516,7 @@ class MainWindow(QMainWindow):def _start_session(self, session_id: str, new_session: bool = False):- if (- self._middle_viewing_panel.welcome_create_or_load_session_panel.send_pings_checkbox.isChecked()- ):- send_pipedream_ping("session_started")+self._session_id = session_idself._control_panel.enable_toolbox_panels()@@ -666,10 +690,10 @@ class MainWindow(QMainWindow):synchronized_videos_folder_path = get_synchronized_videos_folder_path(self._session_id)- output_data_folder_path = get_output_data_folder_path(self._session_id)+ raw_data_folder_path = get_raw_data_folder_path(self._session_id)self._thread_worker_manager.launch_detect_2d_skeletons_thread_worker(synchronized_videos_folder_path=synchronized_videos_folder_path,- output_data_folder_path=output_data_folder_path,+ output_data_folder_path=raw_data_folder_path,auto_process_next_stage=auto_process_next_stage,)@@ -679,13 +703,22 @@ class MainWindow(QMainWindow):if (self._control_panel.calibrate_capture_volume_panel.use_previous_calibration_box_is_checked):+anipose_calibration_object = load_most_recent_anipose_calibration_toml(get_session_folder_path(self._session_id))++ calibration_toml_filename = f"camera_calibration_data.toml"+ camera_calibration_toml_path = (+ Path(get_session_folder_path(self._session_id))+ / calibration_toml_filename+ )+ anipose_calibration_object.dump(camera_calibration_toml_path)+elif (self._control_panel.calibrate_capture_volume_panel.load_camera_calibration_checkbox_is_checked):- anipose_calibration_object = load_anipose_calibration_toml_from_user_selection(+ anipose_calibration_object = load_anipose_calibration_toml_from_path(self._control_panel.calibrate_capture_volume_panel.user_selected_calibration_toml_path,get_session_folder_path(self._session_id),)@@ -700,25 +733,86 @@ class MainWindow(QMainWindow):get_session_calibration_toml_file_path(self._session_id))- output_data_folder_path = get_output_data_folder_path(self._session_id)- mediapipe_2d_data = load_mediapipe2d_data(output_data_folder_path)+ raw_data_folder_path = get_raw_data_folder_path(self._session_id)+ mediapipe_2d_data = load_mediapipe2d_data(raw_data_folder_path)self._thread_worker_manager.launch_triangulate_3d_data_thread_worker(anipose_calibration_object=anipose_calibration_object,mediapipe_2d_data=mediapipe_2d_data,- output_data_folder_path=output_data_folder_path,+ output_data_folder_path=raw_data_folder_path,mediapipe_confidence_cutoff_threshold=self._control_panel.process_session_data_panel.mediapipe_confidence_cutoff_threshold,- save_data_as_csv=self._control_panel.process_session_data_panel.convert_npy_to_csv_checkbox.isChecked(),+ auto_process_next_stage=auto_process_next_stage,+ use_triangulate_ransac=self._control_panel.process_session_data_panel.use_triangulate_ransac_checkbox.isChecked(),+ )++ def _setup_and_launch_gap_fill_filter_origin_align_thread_worker(+ self, auto_process_next_stage: bool = False+ ):+ output_data_folder_path = Path(get_output_data_folder_path(self._session_id))++ skel3d_frame_marker_xyz = load_raw_mediapipe3d_data(output_data_folder_path)+ skeleton_reprojection_error_fr_mar = load_skeleton_reprojection_error_data(+ output_data_folder_path+ )++ data_save_path = output_data_folder_path / PARTIALLY_PROCESSED_DATA_FOLDER_NAME+ data_save_path.mkdir(exist_ok=True)+ sampling_rate = 30+ cut_off = 7+ order = 4+ reference_frame_number = None++ self._thread_worker_manager.launch_post_process_3d_data_thread_worker(+ skel3d_frame_marker_xyz=skel3d_frame_marker_xyz,+ skeleton_reprojection_error_fr_mar=skeleton_reprojection_error_fr_mar,+ data_save_path=data_save_path,+ sampling_rate=sampling_rate,+ cut_off=cut_off,+ order=order,+ reference_frame_number=reference_frame_number,+ auto_process_next_stage=auto_process_next_stage,+ )++ def _setup_and_launch_convert_npy_to_csv_thread_worker(+ self, auto_process_next_stage: bool = False+ ):+ logger.info("Launching convert npy to csv thread worker")++ output_data_folder_path = Path(get_output_data_folder_path(self._session_id))+ mediapipe3d_xyz_file_path = (+ Path(output_data_folder_path)+ / PARTIALLY_PROCESSED_DATA_FOLDER_NAME+ / MEDIAPIPE_3D_ORIGIN_ALIGNED_NPY_FILE_NAME+ )+ skel3d_frame_marker_xyz = load_post_processed_mediapipe3d_data(+ mediapipe3d_xyz_file_path+ )++ self._thread_worker_manager.launch_convert_npy_to_csv_thread_worker(+ skel3d_frame_marker_xyz=skel3d_frame_marker_xyz,+ output_data_folder_path=output_data_folder_path,auto_process_next_stage=auto_process_next_stage,)def _export_to_blender(self):logger.debug(- "Open Session in Blender button clicked (this will freeze the GUI while it is running, sorry! I tried to run it in a thread instead of a 'subprocess' but I got some kind of permission error when it tried to save the `.blend` file, so.... here we are. Frozen in the GUI. How are you? "+ "Open Session in Blender button clicked (this will freeze the GUI while it is running, sorry! I tried to calculate_center_of_mass it in a thread instead of a 'subprocess' but I got some kind of permission error when it tried to save the `.blend` file, so.... here we are. Frozen in the GUI. How are you? ")# self._thread_worker_manager.launch_export_to_blender_thread_worker(# get_session_folder_path(self._session_id)# )+ path_to_skeleton_body_csv = get_skeleton_body_csv_path(self._session_id)+ skeleton_dataframe = pd.read_csv(path_to_skeleton_body_csv)++ skeleton_segment_lengths_dict = estimate_skeleton_segment_lengths(+ skeleton_dataframe=skeleton_dataframe,+ skeleton_segment_definitions=mediapipe_skeleton_segment_definitions,+ )++ save_skeleton_segment_lengths_to_json(+ get_output_data_folder_path(self._session_id), skeleton_segment_lengths_dict+ )+blender_file_path = export_to_blender(session_folder_path=get_session_folder_path(self._session_id),blender_exe_path=self._control_panel.process_session_data_panel.blender_exe_path_str,@@ -727,10 +821,19 @@ class MainWindow(QMainWindow):if (self._control_panel.record_motion_capture_videos_panel.open_in_blender_automatically_checkbox.isChecked()):- self._open_blender_file(blender_file_path)+ if blender_file_path:+ self._open_blender_file(blender_file_path)def _open_blender_file(self, blender_file_path: Union[str, Path]):logger.info(f"Opening {str(blender_file_path)}")++ if blender_file_path is False:+ blender_file_path = get_blender_file_path(self._session_id)++ if not Path(blender_file_path).exists():+ logger.error(f"ERROR - {str(blender_file_path)} does not exist!")+ return+os.startfile(str(blender_file_path))def _visualize_motion_capture_data(self):@@ -738,8 +841,11 @@ class MainWindow(QMainWindow):"`self._control_panel.visualize_motion_capture_data.load_session_data_button` was pressed ")- skeleton_3d_npy = load_mediapipe3d_data(- get_output_data_folder_path(self._session_id)+ skeleton_3d_npy = load_post_processed_mediapipe3d_data(+ Path(get_output_data_folder_path(self._session_id)) /+ PARTIALLY_PROCESSED_DATA_FOLDER_NAME /+ MEDIAPIPE_3D_ORIGIN_ALIGNED_NPY_FILE_NAME+)video_path_iterator = Path(@@ -767,6 +873,17 @@ class MainWindow(QMainWindow):get_qt_app().exit(EXIT_CODE_REBOOT)def closeEvent(self, a0: QtGui.QCloseEvent) -> None:++ if (+ self._middle_viewing_panel.welcome_create_or_load_session_panel.send_pings_checkbox.isChecked()+ ):+ pipedream_ping_dict = self._thread_worker_manager.session_progress_dictionary+ if Path(get_blender_file_path(self._session_id)).exists():+ pipedream_ping_dict['blender_file_created'] = True+ else:+ pipedream_ping_dict['blender_file_created'] = False+ send_pipedream_ping(pipedream_ping_dict)+logger.info("Close Event detected for main window... ")self._middle_viewing_panel.camera_stream_grid_view.close_camera_widgets()diff --git a/src/gui/main/main_window/middle_panel_viewers/camera_stream_grid_view.py b/src/gui/main/main_window/middle_panel_viewers/camera_stream_grid_view.pyindex f86db2ea..1ea0726b 100644--- a/src/gui/main/main_window/middle_panel_viewers/camera_stream_grid_view.py+++ b/src/gui/main/main_window/middle_panel_viewers/camera_stream_grid_view.py@@ -1,23 +1,15 @@-from typing import List, Dict, Callable+from typing import Dictimport cv2-import numpy as np-from PyQt6 import QtCore, QtGui+from PyQt6 import QtGuifrom PyQt6.QtCore import pyqtSignalfrom PyQt6.QtWidgets import (QWidget,- QGridLayout,QVBoxLayout,- QLabel,- QDockWidget,- QPushButton,QHBoxLayout,)-from src.cameras.detection.models import FoundCamerasResponse-from src.cameras.save_synchronized_videos import save_synchronized_videos-from src.config.webcam_config import WebcamConfig-from src.gui.main.app_state.app_state import APP_STATE+from src.cameras.webcam_config import WebcamConfigfrom src.gui.main.custom_widgets.single_camera_widget import SingleCameraWidgetfrom src.gui.main.qt_utils.clear_layout import clear_layoutdiff --git a/src/gui/main/main_window/middle_panel_viewers/session_playback_view/video_playback_grid_view.py b/src/gui/main/main_window/middle_panel_viewers/session_playback_view/video_playback_grid_view.pyindex c570e84e..ef9f78d8 100644--- a/src/gui/main/main_window/middle_panel_viewers/session_playback_view/video_playback_grid_view.py+++ b/src/gui/main/main_window/middle_panel_viewers/session_playback_view/video_playback_grid_view.py@@ -1,24 +1,13 @@from pathlib import Path-from typing import List, Dict, Callable+from typing import List-import numpy as np-from PyQt6 import QtCore-from PyQt6.QtCore import pyqtSignalfrom PyQt6.QtWidgets import (QWidget,- QGridLayout,QVBoxLayout,QLabel,- QDockWidget,- QPushButton,QHBoxLayout,)-from src.cameras.detection.models import FoundCamerasResponse-from src.cameras.save_synchronized_videos import save_synchronized_videos-from src.config.webcam_config import WebcamConfig-from src.gui.main.app_state.app_state import APP_STATE-from src.gui.main.custom_widgets.single_camera_widget import SingleCameraWidgetfrom src.gui.main.custom_widgets.video_player_widget import VideoPlayerWidgetfrom src.gui.main.qt_utils.clear_layout import clear_layoutdiff --git a/src/gui/main/qt_utils/parameter_tree_to_and_from_dictionary.py b/src/gui/main/qt_utils/parameter_tree_to_and_from_dictionary.pynew file mode 100644index 00000000..078dc8d3--- /dev/null+++ b/src/gui/main/qt_utils/parameter_tree_to_and_from_dictionary.py@@ -0,0 +1,51 @@+from typing import Dict, Any++from pyqtgraph.parametertree import Parameter+++def create_parameter_tree_from_dictionary(+ dictionary: Dict[str, Any], name: str = "Root"+) -> Parameter:+ """+ Creates a ParameterTree from a dictionary.+ """+ parameter_tree = Parameter.create(name=name, type="group", children=[])+ for key, value in dictionary.items():+ if isinstance(value, dict):+ parameter_tree.addChild(create_parameter_tree_from_dictionary(value, key))+ else:+ parameter_tree.addChild(Parameter.create(name=key, type="str", value=value))+ return parameter_tree+++def create_dictionary_from_parameter_tree(parameter_tree: Parameter) -> Dict[str, Any]:+ """+ Creates a dictionary from a ParameterTree.+ """+ dictionary = {}+ for child in parameter_tree.children():+ if isinstance(child, Parameter):+ dictionary[child.name()] = child.value()+ else:+ dictionary[child.name()] = create_dictionary_from_parameter_tree(child)+ return dictionary+++if __name__ == "__main__":+ import pyqtgraph as pg+ from rich import print++ dict_to_tree = {+ "a": 1,+ "b": 2,+ "c": {"d": 3, "e": 4},+ }++ tree = create_parameter_tree_from_dictionary(dict_to_tree)++ dict_from_tree = create_dictionary_from_parameter_tree(tree)+ print(dict_from_tree)+ tree.show()++ app = pg.mkQApp()+ pg.exec()diff --git a/src/gui/main/workers/cam_charuco_frame_thread_worker.py b/src/gui/main/workers/cam_charuco_frame_thread_worker.pyindex dd330a72..177a417a 100644--- a/src/gui/main/workers/cam_charuco_frame_thread_worker.py+++ b/src/gui/main/workers/cam_charuco_frame_thread_worker.py@@ -1,12 +1,11 @@import cv2-import numpy as npfrom PyQt6.QtCore import QThread, pyqtSignalfrom PyQt6.QtGui import QImagefrom src.cameras.capture.dataclasses.frame_payload import FramePayloadfrom src.cameras.capture.opencv_camera.opencv_camera import OpenCVCamerafrom src.cameras.persistence.video_writer.video_recorder import VideoRecorder-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigfrom src.core_processes.capture_volume_calibration.charuco_board_detection.charuco_board_detector import (CharucoBoardDetector,)diff --git a/src/gui/main/workers/cam_frame_worker.py b/src/gui/main/workers/cam_frame_worker.pyindex 60ec9857..d68cd42d 100644--- a/src/gui/main/workers/cam_frame_worker.py+++ b/src/gui/main/workers/cam_frame_worker.py@@ -3,7 +3,7 @@ from PyQt6.QtCore import QThread, Qt, pyqtSignalfrom PyQt6.QtGui import QImagefrom src.cameras.capture.opencv_camera.opencv_camera import OpenCVCamera-from src.config.webcam_config import WebcamConfig+from src.cameras.webcam_config import WebcamConfigclass CamFrameWorker(QThread):diff --git a/src/gui/main/workers/convert_npy_to_csv_thread_worker.py b/src/gui/main/workers/convert_npy_to_csv_thread_worker.pynew file mode 100644index 00000000..e5990f51--- /dev/null+++ b/src/gui/main/workers/convert_npy_to_csv_thread_worker.py@@ -0,0 +1,37 @@+from pathlib import Path+from typing import Union++import numpy as np+from PyQt6.QtCore import QThread, pyqtSignal++from src.cameras.detection.cam_singleton import get_or_create_cams+from src.cameras.detection.models import FoundCamerasResponse++import logging++from src.core_processes.mediapipe_stuff.convert_mediapipe_npy_to_csv import (+ convert_mediapipe_npy_to_csv,+)++logger = logging.getLogger(__name__)+++class ConvertNpyToCsvThreadWorker(QThread):+ finished = pyqtSignal(str)++ def __init__(+ self,+ skel3d_frame_marker_xyz: np.ndarray,+ output_data_folder_path: Union[Path, str],+ ):+ super().__init__()+ self._skel3d_frame_marker_xyz = skel3d_frame_marker_xyz+ self.output_data_folder_path = output_data_folder_path++ def run(self):+ convert_mediapipe_npy_to_csv(+ mediapipe_3d_frame_trackedPoint_xyz=self._skel3d_frame_marker_xyz,+ output_data_folder_path=self.output_data_folder_path,+ )++ self.finished.emit("Done!")diff --git a/src/gui/main/workers/export_to_blender_worker.py b/src/gui/main/workers/export_to_blender_worker.pyindex 26742414..29ddd401 100644--- a/src/gui/main/workers/export_to_blender_worker.py+++ b/src/gui/main/workers/export_to_blender_worker.py@@ -3,12 +3,9 @@ from typing import Unionfrom PyQt6.QtCore import QThread, pyqtSignal-from src.cameras.detection.cam_singleton import get_or_create_cams-from src.cameras.detection.models import FoundCamerasResponse-import logging-from src.export_stuff.blender_stuff.export_to_blender import export_to_blender+from src.blender_stuff import export_to_blenderlogger = logging.getLogger(__name__)diff --git a/src/gui/main/workers/post_process_3d_data_thread_worker.py b/src/gui/main/workers/post_process_3d_data_thread_worker.pynew file mode 100644index 00000000..2de38956--- /dev/null+++ b/src/gui/main/workers/post_process_3d_data_thread_worker.py@@ -0,0 +1,49 @@+from pathlib import Path+from typing import Union++import numpy as np+from PyQt6.QtCore import QThread, pyqtSignal+++import logging++from src.core_processes.post_process_skeleton_data.gap_fill_filter_and_origin_align_skeleton_data import (+ gap_fill_filter_origin_align_3d_data_and_then_calculate_center_of_mass,+)++logger = logging.getLogger(__name__)+++class PostProcess3dDataThreadWorker(QThread):+ finished = pyqtSignal(str)++ def __init__(+ self,+ skel3d_frame_marker_xyz: np.ndarray,+ skeleton_reprojection_error_fr_mar: np.ndarray,+ data_save_path: Union[str, Path],+ sampling_rate: int,+ cut_off: float,+ order: int,+ reference_frame_number: int = None,+ ):+ super().__init__()+ self.skel3d_frame_marker_xyz = skel3d_frame_marker_xyz+ self.skeleton_reprojection_error_fr_mar = skeleton_reprojection_error_fr_mar+ self.data_save_path = data_save_path+ self.sample_rate = sampling_rate+ self.cut_off = cut_off+ self.order = order+ self.reference_frame_number = reference_frame_number++ def run(self):+ gap_fill_filter_origin_align_3d_data_and_then_calculate_center_of_mass(+ self.skel3d_frame_marker_xyz,+ skeleton_reprojection_error_fr_mar=self.skeleton_reprojection_error_fr_mar,+ path_to_folder_where_we_will_save_this_data=self.data_save_path,+ sampling_rate=self.sample_rate,+ cut_off=self.cut_off,+ order=self.order,+ reference_frame_number=self.reference_frame_number,+ )+ self.finished.emit("Done!")diff --git a/src/gui/main/workers/thread_worker_manager.py b/src/gui/main/workers/thread_worker_manager.pyindex ced1fbeb..5d495287 100644--- a/src/gui/main/workers/thread_worker_manager.py+++ b/src/gui/main/workers/thread_worker_manager.py@@ -17,10 +17,16 @@ from src.gui.main.workers.cam_detection_thread_worker import CameraDetectionThreimport logging+from src.gui.main.workers.convert_npy_to_csv_thread_worker import (+ ConvertNpyToCsvThreadWorker,+)from src.gui.main.workers.export_to_blender_worker import ExportToBlenderThreadWorkerfrom src.gui.main.workers.mediapipe_2d_detection_thread_worker import (Mediapipe2dDetectionThreadWorker,)+from src.gui.main.workers.post_process_3d_data_thread_worker import (+ PostProcess3dDataThreadWorker,+)from src.gui.main.workers.save_to_video_thread_worker import SaveToVideoThreadWorkerfrom src.gui.main.workers.session_playback_thread_worker import (SessionPlaybackThreadWorker,@@ -38,20 +44,31 @@ class ThreadWorkerManager(QWidget):camera_detection_finished = pyqtSignal(FoundCamerasResponse)videos_saved_signal = pyqtSignal(bool)start_3d_processing_signal = pyqtSignal()+ start_post_processing_signal = pyqtSignal()+ start_convert_npy_to_to_csv_signal = pyqtSignal()start_blender_processing_signal = pyqtSignal()blender_file_created_signal = pyqtSignal(str)- def __init__(self):+ def __init__(self, session_progress_dictionary: dict):super().__init__()+ self._session_progress_dictionary = session_progress_dictionary++ @property+ def session_progress_dictionary(self) -> dict:+ return self._session_progress_dictionarydef launch_detect_cameras_worker(self):logger.info("Launching `Camera Detection` thread worker")++ self._session_progress_dictionary["camera_detection"] = 'launched'+self._camera_detection_thread_worker = CameraDetectionThreadWorker()self._camera_detection_thread_worker.finished.connect(self.camera_detection_finished.emit)self._camera_detection_thread_worker.start()+def launch_save_videos_thread_worker(self,folder_to_save_videos: Union[str, Path],@@ -60,6 +77,12 @@ class ThreadWorkerManager(QWidget):):logger.info("Launching `Save Videos` thread worker...")+ if calibration_videos:+ self._session_progress_dictionary["save_calibrate_videos"] = 'launched'+ else:+ self._session_progress_dictionary["save_mocap_videos"] = 'launched'++self._save_to_video_thread_worker = SaveToVideoThreadWorker(dictionary_of_video_recorders=dictionary_of_video_recorders,folder_to_save_videos=folder_to_save_videos,@@ -69,6 +92,8 @@ class ThreadWorkerManager(QWidget):lambda: self.videos_saved_signal.emit(calibration_videos))++def launch_anipose_calibration_thread_worker(self,charuco_board_definition: CharucoBoardDefinition,@@ -78,6 +103,7 @@ class ThreadWorkerManager(QWidget):jupyter_console_print_function_callable: Callable,):logger.info("Launching `Anipose (Charuco Board) Calibration` thread worker")+ self._session_progress_dictionary["anipose_calibration"] = 'launched'self._anipose_calibration_worker = AniposeCalibrationThreadWorker(charuco_board_definition=charuco_board_definition,calibration_videos_folder_path=calibration_videos_folder_path,@@ -96,13 +122,14 @@ class ThreadWorkerManager(QWidget):auto_process_next_stage: bool = True,):logger.info("Launching `Detect Mediapipe 2d Skeleton` thread worker...")-+ self._session_progress_dictionary["medipipe"] = 'launched'self._mediapipe_2d_detection_thread_worker = Mediapipe2dDetectionThreadWorker(path_to_folder_of_videos_to_process=synchronized_videos_folder_path,output_data_folder_path=output_data_folder_path,)if auto_process_next_stage:+ logger.info("Emitting `start_3d_processing_signal`")self._mediapipe_2d_detection_thread_worker.finished.connect(self.start_3d_processing_signal.emit)@@ -114,38 +141,75 @@ class ThreadWorkerManager(QWidget):mediapipe_2d_data: np.ndarray,output_data_folder_path: Union[str, Path],mediapipe_confidence_cutoff_threshold: float,- save_data_as_csv: bool,auto_process_next_stage: bool = False,+ use_triangulate_ransac: bool = False,):logger.info("Launching `Triangulate 3d Data` thread worker...")-+ self._session_progress_dictionary["triangulate"] = 'launched'self._triangulate_3d_data_thread_worker = Triangulate3dDataThreadWorker(anipose_calibration_object=anipose_calibration_object,mediapipe_2d_data=mediapipe_2d_data,output_data_folder_path=output_data_folder_path,mediapipe_confidence_cutoff_threshold=mediapipe_confidence_cutoff_threshold,- save_data_as_csv=save_data_as_csv,+ use_triangulate_ransac=use_triangulate_ransac,)self._triangulate_3d_data_thread_worker.start()if auto_process_next_stage:+ logger.info("Emitting `start_post_processing_signal`")self._triangulate_3d_data_thread_worker.finished.connect(- self.start_blender_processing_signal.emit+ self.start_post_processing_signal.emit)- # def launch_export_to_blender_thread_worker(- # self, session_folder_path: Union[str, Path]- # ):- # logger.info("Launching `Export to Blender` thread worker...")- #- # self._export_to_blender_thread_worker = ExportToBlenderThreadWorker(- # session_folder_path- # )- # self._export_to_blender_thread_worker.finished.connect(- # self.blender_file_created_signal.emit- # )- # self._export_to_blender_thread_worker.start()+ def launch_post_process_3d_data_thread_worker(+ self,+ skel3d_frame_marker_xyz: np.ndarray,+ skeleton_reprojection_error_fr_mar: np.ndarray,+ data_save_path: Union[str, Path],+ sampling_rate: int,+ cut_off: float,+ order: int,+ reference_frame_number: int = None,+ auto_process_next_stage: bool = False,+ ):+ logger.info("Launching `Post Process 3d Data` thread worker...")+ self._session_progress_dictionary["post_process"] = 'launched'+ self._post_process_3d_data_thread_worker = PostProcess3dDataThreadWorker(+ skel3d_frame_marker_xyz=skel3d_frame_marker_xyz,+ skeleton_reprojection_error_fr_mar=skeleton_reprojection_error_fr_mar,+ data_save_path=data_save_path,+ sampling_rate=sampling_rate,+ cut_off=cut_off,+ order=order,+ reference_frame_number=reference_frame_number,+ )+ self._post_process_3d_data_thread_worker.start()++ logger.info("Emitting `convert_to_csv_signal`")+ self._post_process_3d_data_thread_worker.finished.connect(+ self.start_convert_npy_to_to_csv_signal.emit+ )++ def launch_convert_npy_to_csv_thread_worker(+ self,+ skel3d_frame_marker_xyz: np.ndarray,+ output_data_folder_path: Union[str, Path],+ auto_process_next_stage: bool = False,+ ):+ logger.info("Launching `Convert Npy to Csv` thread worker...")+ self._session_progress_dictionary["convert_to_csv"] = 'launched'+ self._convert_npy_to_csv_thread_worker = ConvertNpyToCsvThreadWorker(+ skel3d_frame_marker_xyz=skel3d_frame_marker_xyz,+ output_data_folder_path=output_data_folder_path,+ )+ self._convert_npy_to_csv_thread_worker.start()++ if auto_process_next_stage:+ logger.info("Emitting `start_export_to_blender_signal`")+ self._convert_npy_to_csv_thread_worker.finished.connect(+ self.start_blender_processing_signal.emit+ )def launch_session_playback_thread(self,@@ -158,6 +222,7 @@ class ThreadWorkerManager(QWidget):logger.info(f"Launching `session_playback_thread_worker` with frames_per_second set to {frames_per_second} ")+ self._session_progress_dictionary["launch_session_playback"] = 'launched'self._session_playback_viewer_thread_worker = SessionPlaybackThreadWorker(frames_per_second=frames_per_second,list_of_video_paths=list_of_video_paths,diff --git a/src/gui/main/workers/triangulate_3d_data_thread_worker.py b/src/gui/main/workers/triangulate_3d_data_thread_worker.pyindex b17b3963..81f91cf8 100644--- a/src/gui/main/workers/triangulate_3d_data_thread_worker.py+++ b/src/gui/main/workers/triangulate_3d_data_thread_worker.py@@ -22,7 +22,7 @@ class Triangulate3dDataThreadWorker(QThread):mediapipe_2d_data: np.ndarray,output_data_folder_path: Union[str, Path],mediapipe_confidence_cutoff_threshold: float,- save_data_as_csv: bool,+ use_triangulate_ransac: bool = False,):super().__init__()self._anipose_calibration_object = anipose_calibration_object@@ -31,7 +31,7 @@ class Triangulate3dDataThreadWorker(QThread):self._mediapipe_confidence_cutoff_threshold = (mediapipe_confidence_cutoff_threshold)- self._save_data_as_csv = save_data_as_csv+ self._use_triangulate_ransac = use_triangulate_ransacdef run(self):logger.info(@@ -43,7 +43,7 @@ class Triangulate3dDataThreadWorker(QThread):mediapipe_2d_data=self._mediapipe_2d_data,output_data_folder_path=self._output_data_folder_path,mediapipe_confidence_cutoff_threshold=self._mediapipe_confidence_cutoff_threshold,- save_data_as_csv=self._save_data_as_csv,+ use_triangulate_ransac=self._use_triangulate_ransac,)self.finished.emit()diff --git a/src/pupil_labs_stuff/pupil_freemocap_calibration_pipeline_orchestrator.py b/src/pupil_labs_stuff/pupil_freemocap_calibration_pipeline_orchestrator.pyindex 72db66e2..66fdcafe 100644--- a/src/pupil_labs_stuff/pupil_freemocap_calibration_pipeline_orchestrator.py+++ b/src/pupil_labs_stuff/pupil_freemocap_calibration_pipeline_orchestrator.py@@ -65,11 +65,11 @@ class PupilFreemocapCalibrationPipelineOrchestrator:f"self.raw_session_data.freemocap_timestamps.shape: {self.raw_session_data.timestamps.shape}")- self.raw_session_data.mediapipe_skel_fr_mar_dim = (+ self.raw_session_data.mediapipe_skel_fr_mar_xyz = (self.session_data_loader.load_mediapipe_data())logger.info(- f"self.raw_session_data.mediapipe_skel_fr_mar_dim.shape: {self.raw_session_data.mediapipe_skel_fr_mar_dim.shape}"+ f"self.raw_session_data.mediapipe_skel_fr_mar_dim.shape: {self.raw_session_data.mediapipe_skel_fr_mar_xyz.shape}")####@@ -102,7 +102,7 @@ class PupilFreemocapCalibrationPipelineOrchestrator:# Calculate Head Rotation matrix for each frame (gaze data will be rotated by head_rot, then calibrated_offset_rot)####rotation_matrix_calculator = RotationMatrixCalculator(- synchronized_session_data.mediapipe_skel_fr_mar_dim+ synchronized_session_data.mediapipe_skel_fr_mar_xyz)synchronized_session_data.head_rotation_data = (@@ -131,13 +131,13 @@ class PupilFreemocapCalibrationPipelineOrchestrator:# Perform Vestibular-Ocular-Reflex based calibration (see methods from (Matthis et al, 2018 and 2022) for deetos)####vor_calibrator = VorCalibrator(- synchronized_session_data.mediapipe_skel_fr_mar_dim.copy(),+ synchronized_session_data.mediapipe_skel_fr_mar_xyz.copy(),vor_start_frame=self.vor_frame_start,vor_end_frame=self.vor_frame_end,debug=False,)right_index_fingertip_idx = 41 # pretty sure this is right?- fixation_point_fr_xyz = synchronized_session_data.mediapipe_skel_fr_mar_dim[+ fixation_point_fr_xyz = synchronized_session_data.mediapipe_skel_fr_mar_xyz[self.vor_frame_start : self.vor_frame_end, right_index_fingertip_idx, :]# right eyediff --git a/src/pupil_labs_stuff/pupil_freemocap_synchronizer.py b/src/pupil_labs_stuff/pupil_freemocap_synchronizer.pyindex 659debe1..d480df9b 100644--- a/src/pupil_labs_stuff/pupil_freemocap_synchronizer.py+++ b/src/pupil_labs_stuff/pupil_freemocap_synchronizer.py@@ -139,7 +139,7 @@ class PupilFreemocapSynchronizer:synchronized_session_data = FreemocapSessionDataClass(timestamps=self.synchronized_timestamps,- mediapipe_skel_fr_mar_dim=self.raw_session_data.mediapipe_skel_fr_mar_dim[+ mediapipe_skel_fr_mar_dim=self.raw_session_data.mediapipe_skel_fr_mar_xyz[freemocap_start_frame:freemocap_end_frame, :, :],right_eye_pupil_labs_data=synchronized_right_eye_data,diff --git a/src/pupil_labs_stuff/qt_gl_laser_skeleton_visualizer.py b/src/pupil_labs_stuff/qt_gl_laser_skeleton_visualizer.pyindex e3cafce3..94d5face 100644--- a/src/pupil_labs_stuff/qt_gl_laser_skeleton_visualizer.py+++ b/src/pupil_labs_stuff/qt_gl_laser_skeleton_visualizer.py@@ -35,7 +35,7 @@ class QtGlLaserSkeletonVisualizer:if session_data is not None:self.session_data = session_data- self.mediapipe_fr_mar_xyz = session_data.mediapipe_skel_fr_mar_dim+ self.mediapipe_fr_mar_xyz = session_data.mediapipe_skel_fr_mar_xyzelif mediapipe_skel_fr_mar_xyz is not None:self.mediapipe_fr_mar_xyz = mediapipe_skel_fr_mar_xyzelse:diff --git a/src/sending_anonymous_user_info_to_places/send_pipedream_ping.py b/src/sending_anonymous_user_info_to_places/send_pipedream_ping.pyindex b4c99802..73d2d655 100644--- a/src/sending_anonymous_user_info_to_places/send_pipedream_ping.py+++ b/src/sending_anonymous_user_info_to_places/send_pipedream_ping.py@@ -5,10 +5,11 @@ import requestslogger = logging.getLogger(__name__)-def send_pipedream_ping(pinged_string):+def send_pipedream_ping(pipe_dream_ping_dictionary):logger.info(- "sending anonymous ping to pipedream to let the devs know that someone is using this, which will allow us to secure more funding to support this project"+ f"sending anonymous ping to pipedream to let the devs know that someone is using this, which will allow us to secure more funding to support this project. This is the dictionary of info we're sending: \n {pipe_dream_ping_dictionary}")+r = requests.post(- "https://eoivu13g86if0cp.m.pipedream.net", json={"pinged_string": pinged_string}+ "https://eoivu13g86if0cp.m.pipedream.net", json={"pinged_string": pipe_dream_ping_dictionary})diff --git a/src/tests/session_folder/test_session_folder.py b/src/tests/session_folder/test_session_folder.pynew file mode 100644index 00000000..bbfa883d--- /dev/null+++ b/src/tests/session_folder/test_session_folder.py@@ -0,0 +1,43 @@+from pathlib import Path+from typing import Union+from unittest import TestCase++import cv2++from src.config.home_dir import (+ SYNCHRONIZED_VIDEOS_FOLDER_NAME,+ OUTPUT_DATA_FOLDER_NAME,+ MEDIAPIPE_2D_NPY_FILE_NAME,+)+++class SessionFolderTestCase(TestCase):+ pass+ # def __init__(self, session_folder_path: Union[str, Path]):+ # super().__init__()+ # self._session_folder_path = session_folder_path+ #+ # # test folder structure+ # self._get_folder_names()+ # self._test_folders_exist()+ #+ # def _get_folder_names(self):+ #+ # self._synchronized_videos_folder = (+ # self._session_folder_path / SYNCHRONIZED_VIDEOS_FOLDER_NAME+ # )+ # self._output_data_folder = self._session_folder_path / OUTPUT_DATA_FOLDER_NAME+ #+ # # handle pre-alpha names+ # if not self._synchronized_videos_folder.exists():+ # self._synchronized_videos_folder = (+ # self._session_folder_path / "SyncedVideos"+ # )+ #+ # if not self._output_data_folder.exists():+ # self._output_data_folder = self._session_folder_path / "DataArrays"+ #+ # def _test_folders_exist(self):+ # self.assertTrue(self._synchronized_videos_folder.exists())+ # self.assertTrue(self._output_data_folder.exists())+ #diff --git a/src/tests/test_mediapipe_data.py b/src/tests/test_mediapipe_data.pynew file mode 100644index 00000000..e1eab4cd--- /dev/null+++ b/src/tests/test_mediapipe_data.py@@ -0,0 +1,104 @@+from pathlib import Path+from typing import Union++import cv2+import numpy as np++from src.config.home_dir import (+ MEDIAPIPE_3D_NPY_FILE_NAME,+ MEDIAPIPE_REPROJECTION_ERROR_NPY_FILE_NAME,+ MEDIAPIPE_2D_NPY_FILE_NAME,+)+++def test_mediapipe_2d_data(+ synchronized_videos_folder: Union[str, Path],+ path_to_folder_where_data_is_saved: Union[str, Path],+ mediapipe_2d_data: np.ndarray,+):++ """+ test that the `mediapipe 2d detection` process worked correctly by checking:++ 1. There is an `.npy` file containing the mediapipe 2d data in the `output_data_folder`+ 2. The dimensions of that `npy` (number of cameras, number of frames, [ need to do - number of tracked points], [pixelX, pixelY] matches the videos in the `synchronized videos` folder++ TODO - check number of tracked points vs 'expected' number of tracked points+ """++ mediapipe_2d_data_file_path = (+ path_to_folder_where_data_is_saved / MEDIAPIPE_2D_NPY_FILE_NAME+ )+ assert mediapipe_2d_data_file_path.exists()++ saved_mediapipe_2d_data = np.load(mediapipe_2d_data_file_path)+ assert np.array_equal(saved_mediapipe_2d_data, mediapipe_2d_data, equal_nan=True)++ list_of_video_paths = list(synchronized_videos_folder.glob("*.mp4"))+ number_of_videos = len(list_of_video_paths)+ assert mediapipe_2d_data.shape[0] == number_of_videos++ video_0_cv2_capture_object = cv2.VideoCapture(str(list_of_video_paths[0]))++ number_of_frames_in_video_0 = int(+ video_0_cv2_capture_object.get(cv2.CAP_PROP_FRAME_COUNT)+ )+ assert mediapipe_2d_data.shape[1] == number_of_frames_in_video_0++ # TODO - check number of tracked points vs 'expected' number of tracked points++ assert mediapipe_2d_data.shape[3] == 2++ return True+++def test_mediapipe_3d_data(+ synchronized_videos_folder: Union[str, Path],+ path_to_folder_where_data_is_saved: Union[str, Path],+ skel3d_frame_marker_xyz: np.ndarray,+ skeleton_reprojection_error_fr_mar: np.ndarray,+):+ """+ test that the `mediapipe 3d detection` process worked correctly by checking:++ 1. There is an `.npy` file containing the mediapipe 3d data in the `output_data_folder`+ 2. The dimensions of that `npy` ( number of frames, [ need to do - number of tracked points], [X,Y,Z] matches the videos in the `synchronized videos` folder++ TODO - check number of tracked points vs 'expected' number of tracked points+ """++ mediapipe_3d_spatial_data_file_path = (+ path_to_folder_where_data_is_saved / MEDIAPIPE_3D_NPY_FILE_NAME+ )+ assert (+ mediapipe_3d_spatial_data_file_path.exists()+ ), f"3d skeleton data file does not exist at {mediapipe_3d_spatial_data_file_path}"++ saved_spatial_data = np.load(mediapipe_3d_spatial_data_file_path)+ assert np.array_equal(saved_spatial_data, skel3d_frame_marker_xyz, equal_nan=True)++ mediapipe_reprojection_error_file_path = (+ path_to_folder_where_data_is_saved / MEDIAPIPE_REPROJECTION_ERROR_NPY_FILE_NAME+ )+ assert mediapipe_reprojection_error_file_path.exists()++ saved_reprojection_error = np.load(mediapipe_reprojection_error_file_path)+ assert np.array_equal(+ saved_reprojection_error, skeleton_reprojection_error_fr_mar, equal_nan=True+ )++ list_of_video_paths = list(synchronized_videos_folder.glob("*.mp4"))++ video_0_cv2_capture_object = cv2.VideoCapture(str(list_of_video_paths[0]))++ number_of_frames_in_video_0 = int(+ video_0_cv2_capture_object.get(cv2.CAP_PROP_FRAME_COUNT)+ )+ assert skel3d_frame_marker_xyz.shape[0] == number_of_frames_in_video_0+ assert skeleton_reprojection_error_fr_mar.shape[0] == number_of_frames_in_video_0++ # TODO - check number of tracked points vs 'expected' number of tracked points++ assert skel3d_frame_marker_xyz.shape[2] == 3++ return Truediff --git a/versioneer.py b/versioneer.pyindex db3a7aca..70958ce6 100644--- a/versioneer.py+++ b/versioneer.py@@ -28,7 +28,7 @@ system, and maybe making new tarballs.* `pip install versioneer` to somewhere to your $PATH* add a `[versioneer]` section to your setup.cfg (see below)-* run `versioneer install` in your source tree, commit the results+* calculate_center_of_mass `versioneer install` in your source tree, commit the results## Version Identifiers@@ -94,7 +94,7 @@ See [INSTALL.md](./INSTALL.md) for detailed installation instructions.Code which uses Versioneer can learn about its version string at runtime byimporting `_version` from your icis_conference_main `__init__.py` file and running the`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can-import the top-level `versioneer.py` and run `get_versions()`.+import the top-level `versioneer.py` and calculate_center_of_mass `get_versions()`.Both functions return a dictionary with different flavors of versioninformation:@@ -113,7 +113,7 @@ information:available.* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that- this is only accurate if run in a VCS checkout, otherwise it is likely to+ this is only accurate if calculate_center_of_mass in a VCS checkout, otherwise it is likely tobe False or None* `['error']`: if the version string could not be computed, this will be set@@ -156,8 +156,8 @@ source tree for descriptions.## DebuggingVersioneer tries to avoid fatal errors: if something goes wrong, it will tend-to return a version of "0+unknown". To investigate the problem, run `setup.py-version`, which will run the version-lookup code in a verbose mode, and will+to return a version of "0+unknown". To investigate the problem, calculate_center_of_mass `setup.py+version`, which will calculate_center_of_mass the version-lookup code in a verbose mode, and willdisplay the full contents of `get_versions()` (including the `error` string,which may help identify what went wrong).@@ -247,7 +247,7 @@ To upgrade your project to a new release of Versioneer, do the following:* install the new Versioneer (`pip install -U versioneer` or equivalent)* edit `setup.cfg`, if necessary, to include any new configuration settingsindicated by the release notes. See [UPGRADING](./UPGRADING.md) for details.-* re-run `versioneer install` in your source tree, to replace+* re-calculate_center_of_mass `versioneer install` in your source tree, to replace`SRC/_version.py`* commit any changed files@@ -296,7 +296,7 @@ class VersioneerConfig:def get_root():"""Get the project root directory.- We require that all commands are run from the project root, i.e. the+ We require that all commands are calculate_center_of_mass from the project root, i.e. thedirectory that contains setup.py, setup.cfg, and versioneer.py ."""root = os.path.realpath(os.path.abspath(os.getcwd()))@@ -309,7 +309,7 @@ def get_root():versioneer_py = os.path.join(root, "versioneer.py")if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):err = (- "Versioneer was unable to run the project root directory. "+ "Versioneer was unable to calculate_center_of_mass the project root directory. ""Versioneer requires setup.py to be executed from ""its immediate directory (like 'python setup.py COMMAND'), ""or in a way that lets it use sys.argv[0] to find the root "@@ -409,7 +409,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=if e.errno == errno.ENOENT:continueif verbose:- print("unable to run %s" % dispcmd)+ print("unable to calculate_center_of_mass %s" % dispcmd)print(e)return None, Noneelse:@@ -421,7 +421,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=stdout = stdout.decode()if p.returncode != 0:if verbose:- print("unable to run %s (error)" % dispcmd)+ print("unable to calculate_center_of_mass %s (error)" % dispcmd)print("stdout was %s" % stdout)return None, p.returncodereturn stdout, p.returncode@@ -517,7 +517,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,if e.errno == errno.ENOENT:continueif verbose:- print("unable to run %%s" %% dispcmd)+ print("unable to calculate_center_of_mass %%s" %% dispcmd)print(e)return None, Noneelse:@@ -529,7 +529,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,stdout = stdout.decode()if p.returncode != 0:if verbose:- print("unable to run %%s (error)" %% dispcmd)+ print("unable to calculate_center_of_mass %%s (error)" %% dispcmd)print("stdout was %%s" %% stdout)return None, p.returncodereturn stdout, p.returncode@@ -1533,7 +1533,7 @@ def get_cmdclass():# built (using setup.py bdist_egg) in the same python process. Assume# a icis_conference_main project A and a dependency B, which use different versions# of Versioneer. A's setup.py imports A's Versioneer, leaving it in- # sys.modules by the time B's setup.py is executed, causing B to run+ # sys.modules by the time B's setup.py is executed, causing B to calculate_center_of_mass# with the wrong versioneer. Setuptools wraps the sub-dep builds in a# sandbox that restores sys.modules to it's pre-build state, so the# parent is protected against the child's "import versioneer". By@@ -1725,12 +1725,12 @@ You will also need to edit your setup.py to use the results:cmdclass=versioneer.get_cmdclass(), ...)Please read the docstring in ./versioneer.py for configuration instructions,-edit setup.cfg, and re-run the installer or 'python versioneer.py setup'.+edit setup.cfg, and re-calculate_center_of_mass the installer or 'python versioneer.py setup'."""SAMPLE_CONFIG = """# See the docstring in versioneer.py for instructions. Note that you must-# re-run 'versioneer.py setup' after changing this section, and commit the+# re-calculate_center_of_mass 'versioneer.py setup' after changing this section, and commit the# resulting files.[versioneer]