Skip to content

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

TypeScript

implement new blender output

Jon411fdf5374d4
diff --git a/freemocap/fmc_runme.py b/freemocap/fmc_runme.py
index 983b1858..16e7f6bf 100644
--- a/freemocap/fmc_runme.py
+++ b/freemocap/fmc_runme.py
@@ -45,8 +45,8 @@ thisStage = 0 #global
# TODO: Replace the below functions with the RunMe options.
def RunMe(sessionID=None,
stage=1,
- useOpenPose=False,
- runOpenPose = True,
+ useOpenPose=False,
+ runOpenPose = True,
useMediaPipe=True,
runMediaPipe=True,
useDLC=False,
@@ -64,15 +64,15 @@ def RunMe(sessionID=None,
resetBlenderExe = False,
get_synced_unix_timestamps = True,
):
- """
+ """
Starts the freemocap pipeline based on either user-input values, or default values. Creates a new session class instance (called sesh)
based on the specified inputs. Checks for previous user preferences and choices if they exist, or will prompt the user for new choices
if they don't. Runs the initialization for the system and runs each stage of the pipeline.
- """
-
+ """
+
welcome_md = Markdown("""# Welcome to FreeMoCap βœ¨πŸ’€βœ¨ """)
console.print(welcome_md)
-
+
sesh = session.Session()
sesh.sessionID = sessionID
@@ -86,7 +86,7 @@ def RunMe(sessionID=None,
sesh.startFrame = startFrame
sesh.get_synced_unix_timestamps = get_synced_unix_timestamps
- # %% Startup
+ # %% Startup
startup.get_user_preferences(sesh,stage)
if sesh.useDLC and stage<5:
@@ -95,11 +95,11 @@ def RunMe(sessionID=None,
if stage > 1:
startup.get_data_folder_path(sesh)
-
- if sesh.sessionID == None:
+
+ if sesh.sessionID == None:
subfolders = [f.path for f in os.scandir(sesh.dataFolderPath) if f.is_dir()] # copy-pasta from who knows where
sesh.sessionID = Path(subfolders[-1]).stem # grab the name of the last folder in the list of subfolders
-
+
console.rule()
print('Running ' + str(sesh.sessionID) + ' from ' + str(sesh.dataFolderPath))
console.rule()
@@ -108,7 +108,7 @@ def RunMe(sessionID=None,
subprocessPath = here/'fmc_blender.py'
blenderPath = startup.get_blender_path(sesh,resetBlenderExe)
-
+
board = CharucoBoard(7, 5,
#square_length=1, # here, in mm but any unit works (JSM NOTE - just using '1' so resulting units will be in 'charuco squarelenghts`)
#marker_length=.8,
@@ -119,7 +119,7 @@ def RunMe(sessionID=None,
marker_bits=4, dict_size=250)
sesh.board = board
-
+
# %% Initialization
if stage == 1:
@@ -130,12 +130,12 @@ def RunMe(sessionID=None,
sesh.initialize(stage)
# %% Stage One
-
+
if stage <= 1:
thisStage=1
- console.rule(style="color({})".format(14))
- console.rule('Starting Video Recordings'.upper(), style="color({})".format(14))
- console.rule(style="color({})".format(14))
+ console.rule(style="color({})".format(14))
+ console.rule('Starting Video Recordings'.upper(), style="color({})".format(14))
+ console.rule(style="color({})".format(14))
runcams.RecordCams(sesh, sesh.cam_inputs, sesh.parameterDictionary, sesh.rotationInputs)
sesh.save_session()
@@ -146,10 +146,10 @@ def RunMe(sessionID=None,
# %% Stage Two
if stage <= 2:
thisStage=2
- console.rule(style="color({})".format(thisStage))
- console.rule('Synchronizing Recorded Videos'.upper(),style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
+ console.rule(style="color({})".format(thisStage))
+ console.rule('Synchronizing Recorded Videos'.upper(),style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
+
runcams.SyncCams(sesh, sesh.timeStampData,sesh.numCamRange,sesh.vidNames,sesh.camIDs)
sesh.save_session()
else:
@@ -158,12 +158,12 @@ def RunMe(sessionID=None,
# %% Stage Three
if stage <= 3:
thisStage=3
- console.rule(style="color({})".format(thisStage))
- console.rule('Starting Capture Volume Calibration'.upper(),style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
+ console.rule('Starting Capture Volume Calibration'.upper(),style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
console.print(Padding('Using Anipose to calculate 6 degree-of-freedom position (and distortion coeffs) of each camera based on detected charuco boards. This information is used to create a Camera Projection Matrix for each camera, which is later used in the 3d reconstruction stage', (1,4)), overflow="fold", justify='center',style="color({})".format(thisStage))
- console.rule('See https://anipose.org for details', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
+ console.rule('See https://anipose.org for details', style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
if sesh.numFrames is None:
a_sync_vid_path = list(sesh.syncedVidPath.glob('*.mp4'))
@@ -173,7 +173,7 @@ def RunMe(sessionID=None,
sesh.cgroup, sesh.mean_charuco_fr_mar_xyz = calibrate.CalibrateCaptureVolume(sesh,board, calVideoFrameLength)
- ##this is supposed to cycle through tyhe videos with different windows to try to get Anipose to work. I can't get the dang thing working because something weird happens where a Thread will get spawned in one of the inner functions (maybe related to tqdm?) and that iteration will jump out of the try/except
+ ##this is supposed to cycle through tyhe videos with different windows to try to get Anipose to work. I can't get the dang thing working because something weird happens where a Thread will get spawned in one of the inner functions (maybe related to tqdm?) and that iteration will jump out of the try/except
# try:
# sesh.cgroup, sesh.mean_charuco_fr_mar_xyz = calibrate.CalibrateCaptureVolume(sesh,board, calVideoFrameLength)
# # anipose_success = True
@@ -188,9 +188,9 @@ def RunMe(sessionID=None,
# cal_video_frame_range = [round(sesh.numFrames*.25), round(sesh.numFrames*.5)]
# else:
# cal_video_frame_range = [0, round(sesh.numFrames*.25)]
-
+
# for anipose_iter in range(4):
-
+
# console.rule('Anipose Failed - Reprocessing - Iteration #{}'.format(anipose_iter), style="color({})".format(thisStage))
# console.rule('Trying again with frame range {} - {}'.format(cal_video_frame_range[0], cal_video_frame_range[1]), style="color({})".format(thisStage))
@@ -200,11 +200,11 @@ def RunMe(sessionID=None,
# except:
# console.print_exception()
# cal_video_frame_range = [cal_video_frame_range[0]+round(sesh.numFrames*.25), cal_video_frame_range[0]+round(sesh.numFrames*.5)]
-
+
# if cal_video_frame_range[1] > sesh.numFrames:
# console.print('[bold red] -Sorry, we couldn\'t get Anipose calibration to complete sucessfully. Are you using a Charuco board made with the parameters described in the ReadMe (here\s a sample png -https://github.com/jonmatthis/freemocap/blob/main/charuco_board_image.png ). Is the board clearly visible to each camera? Is there glare on it from from any of the camera\'s perspective? Is it too far away from the cameras? Is your `exposure` set low enough that the black squares are black (not grey)?')
-
+
print('Anipose Calibration Successful!')
@@ -214,35 +214,35 @@ def RunMe(sessionID=None,
# %% Stage Four
if stage <= 4:
thisStage=4
- console.rule(style="color({})".format(thisStage))
- console.rule('Starting 2D Point Trackers'.upper(),style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
+ console.rule('Starting 2D Point Trackers'.upper(),style="color({})".format(thisStage))
stage4_msg ='This step implements various computer vision that track the skeleton (and other objects) in the 2d videos, to produce the data that will be combined with the `camera projection matrices` from the calibration stage to produce the estimates of 3d movement. \n \n Each algorithm is different, but most involve using [bold magenta] convolutional neural networks [/bold magenta] trained from labeled videos to produce a 2d probability map of the likelihood that the tracked bodypart/object/feature (e.g. \'LeftElbow\') is in a given location. \n \n The peak of that distrubtion on each frame is recorded as the pixel-location of that item on that frame (e.g. \'LeftElbow(pixel-x, pixel-y, confidence\') where the a confidence value proportional to the underlying probability distribution (i.e. tall peaks in the probablitiy distribution indicate high confidence that the LeftElbow actually is at this pixel-x, pixel-y location) \n \nThis part is crazy future tech sci fi stuff. Seriously unbelievable this kind of thing is possible ✨'
console.print(Padding(stage4_msg, (1,4)), overflow="fold", justify='center',style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
+ console.rule(style="color({})".format(thisStage))
+
if sesh.useMediaPipe:
- console.rule(style="color({})".format(thisStage))
- console.rule('Running MediaPipe skeleton tracker - https://google.github.io/mediapipe', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
+ console.rule(style="color({})".format(thisStage))
+ console.rule('Running MediaPipe skeleton tracker - https://google.github.io/mediapipe', style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
+
if runMediaPipe:
fmc_mediapipe.runMediaPipe(sesh)
sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC = fmc_mediapipe.parseMediaPipe(sesh)
-
-
+
+
else:
print('`runMediaPipe` set to False, so we\'re loading MediaPipe data from npy file')
sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC = np.load(sesh.dataArrayPath/'mediaPipeData_2d.npy', allow_pickle=True)
-
+
sesh.mediaPipeSkel_fr_mar_xyz, sesh.mediaPipeSkel_reprojErr = reconstruct3D.reconstruct3D(sesh,sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=reconstructionConfidenceThreshold)
-
+
np.save(sesh.dataArrayPath/'mediaPipeSkel_3d.npy', sesh.mediaPipeSkel_fr_mar_xyz) #save data to npy
- np.save(sesh.dataArrayPath/'mediaPipeSkel_reprojErr.npy', sesh.mediaPipeSkel_reprojErr) #save data to npy
-
+ np.save(sesh.dataArrayPath/'mediaPipeSkel_reprojErr.npy', sesh.mediaPipeSkel_reprojErr) #save data to npy
+
#smoooooooooth, just a bit
smoothWinLength = 5
smoothOrder = 3
@@ -251,22 +251,22 @@ def RunMe(sessionID=None,
sesh.mediaPipeSkel_fr_mar_xyz[:,mm,dim] = savgol_filter(sesh.mediaPipeSkel_fr_mar_xyz[:,mm,dim], smoothWinLength, smoothOrder)
np.save(sesh.dataArrayPath/'mediaPipeSkel_3d_smoothed.npy', sesh.mediaPipeSkel_fr_mar_xyz) #save data to npy
-
+
sesh.save_session()
-
+
if sesh.useOpenPose:
- console.rule(style="color({})".format(thisStage))
- console.rule('Running OpenPose skeleton tracker - https://github.com/CMU-Perceptual-Computing-Lab/openpose', style="color({})".format(thisStage))
console.rule(style="color({})".format(thisStage))
-
+ console.rule('Running OpenPose skeleton tracker - https://github.com/CMU-Perceptual-Computing-Lab/openpose', style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
+
fmc_openpose.runOpenPose(sesh, runOpenPose=runOpenPose)
sesh.openPoseData_nCams_nFrames_nImgPts_XYC = fmc_openpose.parseOpenPose(sesh)
sesh.openPoseSkel_fr_mar_xyz, sesh.openPoseSkel_reprojErr = reconstruct3D.reconstruct3D(sesh,sesh.openPoseData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=reconstructionConfidenceThreshold)
np.save(sesh.dataArrayPath/'openPoseSkel_3d.npy', sesh.openPoseSkel_fr_mar_xyz) #save data to npy
np.save(sesh.dataArrayPath/'openPoseSkel_reprojErr.npy', sesh.openPoseSkel_reprojErr) #save data to npy
-
+
smoothWinLength = 5
smoothOrder = 3
for dim in range(sesh.openPoseSkel_fr_mar_xyz.shape[2]):
@@ -274,22 +274,22 @@ def RunMe(sessionID=None,
sesh.openPoseSkel_fr_mar_xyz[:,mm,dim] = savgol_filter(sesh.openPoseSkel_fr_mar_xyz[:,mm,dim], smoothWinLength, smoothOrder)
np.save(sesh.dataArrayPath/'openPoseSkel_3d_smoothed.npy', sesh.openPoseSkel_fr_mar_xyz) #save data to npy
-
+
sesh.save_session()
sesh.syncedVidList = []
if sesh.useDLC:
-
- console.rule(style="color({})".format(thisStage))
- console.rule('Running DeepLabCut :mouse: - https://deeplabcut.org', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
+
+ console.rule(style="color({})".format(thisStage))
+ console.rule('Running DeepLabCut :mouse: - https://deeplabcut.org', style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
+
for vid in sesh.syncedVidPath.glob('*.mp4'):
sesh.syncedVidList.append(str(vid))
-
+
for config_path in dlc_config_paths:
- dlc.analyze_videos(config_path,sesh.syncedVidList, destfolder= sesh.dlcDataPath, save_as_csv=True)
+ dlc.analyze_videos(config_path,sesh.syncedVidList, destfolder= sesh.dlcDataPath, save_as_csv=True)
sesh.dlcData_nCams_nFrames_nImgPts_XYC = fmc_deeplabcut.parseDeepLabCut(sesh, config_path)
sesh.dlc_fr_mar_xyz, sesh.dlc_reprojErr = reconstruct3D.reconstruct3D(sesh,sesh.dlcData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=reconstructionConfidenceThreshold)
np.save(sesh.dataArrayPath/'deepLabCut_3d.npy', sesh.dlc_fr_mar_xyz) #save data to npy
@@ -305,33 +305,40 @@ def RunMe(sessionID=None,
try:
if useBlender == True:
thisStage=5
- console.rule(style="color({})".format(thisStage))
- console.rule('Exporting Files...'.upper(), style="color({})".format(thisStage))
- console.rule('Hijacking Blender\'s file format converters to export FreeMoCap data as various file format (.blend, .usd, .gltf, .fbx)', style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
+ console.rule(style="color({})".format(thisStage))
+ console.rule('Exporting Files...'.upper(), style="color({})".format(thisStage))
+ console.rule('Hijacking Blender\'s file format converters to export FreeMoCap data as various file format (.blend, .usd, .gltf, .fbx)', style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
-
- #blenderPath = Path('C:\Program Files\Blender Foundation\Blender 2.93')
- #os.chdir(blenderExePath)
path_to_this_py_file = Path(__file__).parent.resolve()
- fmc_blender_script_path = path_to_this_py_file /'fmc_blender.py'
- with console.status('Stuffing data into a Blender scene...'):
- output = subprocess.run([str(blenderPath), "--background", "--python", str(fmc_blender_script_path), "--", str(sesh.dataArrayPath/'mediaPipeSkel_3d_smoothed.npy'), str(sesh.dataArrayPath), sesh.sessionID], capture_output=True, text=True, check=True)
- print(output)
+ fmc_blender_script_path = path_to_this_py_file /'freemocap_blender_megascript.py'
+
+ command_str = str(blenderPath) + " --background" + " --python " + str(fmc_blender_script_path) + " -- " + str(sesh.sessionPath)
+ # command_str = [str(blenderPath), "--background", "--python", str(fmc_blender_script_path), "--", str(sesh.sessionPath)]
+ blender_process = subprocess.Popen(
+ command_str,
+ shell=False,
+ stdout=subprocess.PIPE)
+ while True:
+ output = blender_process.stdout.readline()
+ if blender_process.poll() is not None:
+ break
+ if output:
+ print(output.strip().decode())
+
except:
console.print_exception()
-
+
# %% Stage 6 - Make Animation
if stage <= 6:
thisStage=6
- console.rule(style="color({})".format(thisStage))
- console.rule('Creating the Skreleton animation!'.upper(),style="color({})".format(thisStage))
- console.print('The video creation is very slow. All of the animation making code is crazy slow, tbh. Sorry about that, future iterations will be better lol :sweat_smile:',overflow="fold", justify='center',style="color({})".format(thisStage))
- console.rule(style="color({})".format(thisStage))
-
-
+ console.rule(style="color({})".format(thisStage))
+ console.rule('Creating the Skreleton animation!'.upper(),style="color({})".format(thisStage))
+ console.print('The video creation is very slow. All of the animation making code is crazy slow, tbh. Sorry about that, future iterations will be better lol :sweat_smile:',overflow="fold", justify='center',style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
+
+
play_skeleton_animation.PlaySkeletonAnimation(
sesh,
@@ -344,22 +351,22 @@ def RunMe(sessionID=None,
recordVid = recordVid,
showAnimation=showAnimation,
)
- console.rule(style="color({})".format(thisStage))
+ console.rule(style="color({})".format(thisStage))
else:
print('Skipping Skeleton Plotting')
- console.rule(style="color({})".format(13))
- console.rule('All Done!'.upper(), style="color({})".format(13))
- console.rule(style="color({})".format(13))
- console.rule('Session Data folder is at: ', style="color({})".format(13))
- console.rule(str(sesh.sessionPath), style="color({})".format(13))
- console.rule(style="color({})".format(13))
- console.rule(style="color({})".format(10))
- console.rule("Thank you for supporting the FreeMoCap Project", style="color({})".format(10))
- console.rule(style="color({})".format(10))
- console.rule(style="color({})".format(13))
- console.print('~βœ¨πŸ’€βœ¨~',justify="center")
- console.print('❀️', justify="center")
- console.rule(style="color({})".format(13))
- console.rule(style="color({})".format(14))
+ console.rule(style="color({})".format(13))
+ console.rule('All Done!'.upper(), style="color({})".format(13))
+ console.rule(style="color({})".format(13))
+ console.rule('Session Data folder is at: ', style="color({})".format(13))
+ console.rule(str(sesh.sessionPath), style="color({})".format(13))
+ console.rule(style="color({})".format(13))
+ console.rule(style="color({})".format(10))
+ console.rule("Thank you for supporting the FreeMoCap Project", style="color({})".format(10))
+ console.rule(style="color({})".format(10))
+ console.rule(style="color({})".format(13))
+ console.print('~βœ¨πŸ’€βœ¨~',justify="center")
+ console.print('❀️', justify="center")
+ console.rule(style="color({})".format(13))
+ console.rule(style="color({})".format(14))
diff --git a/freemocap/freemocap_blender_megascript.py b/freemocap/freemocap_blender_megascript.py
new file mode 100644
index 00000000..3801afa6
--- /dev/null
+++ b/freemocap/freemocap_blender_megascript.py
@@ -0,0 +1,1238 @@
+import bpy
+import numpy as np
+from pathlib import Path
+import sys
+
+#######################################################################
+##% Session path
+# #get session path as command line argument
+argv = sys.argv
+argv = argv[argv.index("--") + 1:]
+session_path = argv[0]
+print(str(session_path))
+session_path = Path(session_path)
+path_to_mediapipe_npy = session_path / 'DataArrays' / 'mediaPipeSkel_3d_smoothed.npy'
+
+
+#######################################################################
+#%% load mediapipe data
+#%%
+print('loading data')
+# %%
+mediapipe_skel_fr_mar_dim = np.load(path_to_mediapipe_npy)
+mediapipe_skel_fr_mar_dim = mediapipe_skel_fr_mar_dim/1000 #convert to meters
+
+body_marker_range = np.arange(0,33)
+right_hand_marker_range = np.arange(33, 33+21)
+left_hand_marker_range = np.arange(33+21, 33+21+21)
+face_marker_range = np.arange(left_hand_marker_range[-1], mediapipe_skel_fr_mar_dim.shape[1])
+
+body_skel_fr_mar_dim = mediapipe_skel_fr_mar_dim[:, body_marker_range, :,]
+right_hand_fr_mar_dim = mediapipe_skel_fr_mar_dim[:, right_hand_marker_range, :,]
+left_hand_fr_mar_dim = mediapipe_skel_fr_mar_dim[:, left_hand_marker_range, :,]
+face_fr_mar_dim = mediapipe_skel_fr_mar_dim[:, face_marker_range, :,]
+
+
+#%% Session Specific stuff
+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
+
+
+########################
+## Find Good Clean Frame
+frame_nan_counts = []
+for this_frame in range(mediapipe_skel_fr_mar_dim.shape[0]):
+ frame_nan_counts.append(np.sum(np.isnan(mediapipe_skel_fr_mar_dim[this_frame,:,0])))
+
+good_clean_frame_number = np.argmin(frame_nan_counts) # the frame with the fewest nans (i.e. hopefully a frame where all tracked points are visible)
+
+#######################################################################
+#%% Mediapipe tracked point names
+mediapipe_tracked_point_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",
+ "right_hand_wrist",
+ "right_hand_thumb_cmc",
+ "right_hand_thumb_mcp",
+ "right_hand_thumb_ip",
+ "right_hand_thumb_tip",
+ "right_hand_index_finger_mcp",
+ "right_hand_index_finger_pip",
+ "right_hand_index_finger_dip",
+ "right_hand_index_finger_tip",
+ "right_hand_middle_finger_mcp",
+ "right_hand_middle_finger_pip",
+ "right_hand_middle_finger_dip",
+ "right_hand_middle_finger_tip",
+ "right_hand_ring_finger_mcp",
+ "right_hand_ring_finger_pip",
+ "right_hand_ring_finger_dip",
+ "right_hand_ring_finger_tip",
+ "right_hand_pinky_finger_mcp",
+ "right_hand_pinky_finger_pip",
+ "right_hand_pinky_finger_dip",
+ "right_hand_pinky_finger_tip",
+ "left_hand_wrist",
+ "left_hand_thumb_cmc",
+ "left_hand_thumb_mcp",
+ "left_hand_thumb_ip",
+ "left_hand_thumb_tip",
+ "left_hand_index_finger_mcp",
+ "left_hand_index_finger_pip",
+ "left_hand_index_finger_dip",
+ "left_hand_index_finger_tip",
+ "left_hand_middle_finger_mcp",
+ "left_hand_middle_finger_pip",
+ "left_hand_middle_finger_dip",
+ "left_hand_middle_finger_tip",
+ "left_hand_ring_finger_mcp",
+ "left_hand_ring_finger_pip",
+ "left_hand_ring_finger_dip",
+ "left_hand_ring_finger_tip",
+ "left_hand_pinky_finger_mcp",
+ "left_hand_pinky_finger_pip",
+ "left_hand_pinky_finger_dip",
+ "left_hand_pinky_finger_tip",
+ ]
+
+
+#####################################################################
+## Blender Stuff
+#####################################################################
+
+#####################################################################
+###%% clear scene
+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
+
+#######################################################################
+#%% create world origin
+
+bpy.ops.object.empty_add(type='ARROWS')
+world_origin_axes = bpy.context.active_object
+world_origin_axes.name = 'world_origin' #will stay at origin
+# inspect(world_origin_axes, methods=True)
+
+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 empties
+print('loading {} empties on {} frames'.format(len(mediapipe_tracked_point_names), number_of_frames))
+
+empty_size = .01
+
+for this_point_index, this_point_name in enumerate(mediapipe_tracked_point_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
+
+ if 'face' in this_point_name:
+ this_empty.scale = [empty_size/4]*3
+ if 'hand' in this_point_name:
+ this_empty.scale = [empty_size/2]*3
+ else:
+ 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
+left_ear_index = 7
+right_ear_index = 8
+#######################################################################
+print('creating virtual markers')
+print('head_center - midway between left and right ears')
+hips_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
+mediapipe_tracked_point_names.append(this_empty.name)
+
+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('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
+mediapipe_tracked_point_names.append(this_empty.name)
+
+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
+mediapipe_tracked_point_names.append(this_empty.name)
+
+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 - mean of R/L shoulders and R/L hips')
+chest_xyz = (neck_xyz + hips_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
+mediapipe_tracked_point_names.append(this_empty.name)
+
+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)
+
+print('Done loading empties :D')
+
+
+######################################################################
+## Fit Rigify metarig armatures to empties
+
+bpy.context.scene.frame_set(good_clean_frame_number)
+
+#each bone name has to match one in the Blender Rigify Human Metarig, or it will be ignored
+metarig_bone_empty_pairs_dict_of_dicts = {
+"hand.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_index',
+},
+"forearm.L": {
+ 'head': 'left_elbow',
+ 'tail': 'left_wrist',
+},
+"upper_arm.L": {
+ 'head': 'left_shoulder',
+ 'tail': 'left_elbow',
+},
+"shoulder.L": {
+ 'head': 'neck_center',
+ 'tail': 'left_shoulder',
+},
+"hand.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_index',
+},
+"forearm.R": {
+ 'head': 'right_elbow',
+ 'tail': 'right_wrist',
+},
+"upper_arm.R": {
+ 'head': 'right_shoulder',
+ 'tail': 'right_elbow',
+},
+"shoulder.R": {
+ 'head': 'neck_center',
+ 'tail': 'right_shoulder',
+},
+"thigh.L": {
+ 'head': 'left_hip',
+ 'tail': 'left_knee',
+},
+"shin.L": {
+ 'head': 'left_knee',
+ 'tail': 'left_ankle',
+},
+"heel.02.L": {
+ 'head': 'left_heel',
+ 'tail': 'left_ankle',
+},
+"foot.L": {
+ 'head': 'left_ankle',
+ 'tail': 'left_foot_index',
+},
+"toe.L": {
+ 'head': 'left_foot_index',
+ 'tail': 'left_heel',
+},
+"thigh.R": {
+ 'head': 'right_hip',
+ 'tail': 'right_knee',
+},
+"shin.R": {
+ 'head': 'right_knee',
+ 'tail': 'right_ankle',
+},
+"heel.02.R": {
+ 'head': 'right_heel',
+ 'tail': 'right_ankle',
+},
+"foot.R": {
+ 'head': 'right_ankle',
+ 'tail': 'right_foot_index',
+},
+"toe.R": {
+ 'head': 'right_foot_index',
+ 'tail': 'right_heel',
+},
+"pelvis.L": {
+ 'head': 'hip_center',
+ 'tail': 'left_hip',
+},
+"pelvis.R": {
+ 'head': 'hip_center',
+ 'tail': 'right_hip',
+},
+"spine": {
+ 'head': 'hip_center',
+ 'tail': 'chest_center',
+},
+"spine.001": {
+ 'head': 'chest_center',
+ 'tail': 'neck_center',
+},
+"spine.002": {
+ 'head': 'neck_center',
+ 'tail': 'head_center',
+},
+"spine.003": {
+ 'head': 'head_center',
+ 'tail': 'nose',
+},
+"palm.01.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_index_finger_mcp',
+},
+"palm.02.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_middle_finger_mcp',
+},
+"palm.03.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_ring_finger_mcp',
+},
+"palm.04.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_pinky_finger_mcp',
+},
+
+"thumb.01.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_thumb_mcp',
+},
+"thumb.02.R": {
+ 'head': 'right_hand_thumb_mcp',
+ 'tail': 'right_hand_thumb_ip',
+},
+"thumb.03.R": {
+ 'head': 'right_hand_thumb_ip',
+ 'tail': 'right_hand_thumb_tip',
+},
+
+"f_index.01.R": {
+ 'head': 'right_hand_index_finger_mcp',
+ 'tail': 'right_hand_index_finger_pip',
+},
+"f_index.02.R": {
+ 'head': 'right_hand_index_finger_pip',
+ 'tail': 'right_hand_index_finger_dip',
+},
+"f_index.03.R": {
+ 'head': 'right_hand_index_finger_dip',
+ 'tail': 'right_hand_index_finger_tip',
+},
+
+"f_middle.01.R": {
+ 'head': 'right_hand_middle_finger_mcp',
+ 'tail': 'right_hand_middle_finger_pip',
+},
+"f_middle.02.R": {
+ 'head': 'right_hand_middle_finger_pip',
+ 'tail': 'right_hand_middle_finger_dip',
+},
+"f_middle.03.R": {
+ 'head': 'right_hand_middle_finger_dip',
+ 'tail': 'right_hand_middle_finger_tip',
+},
+
+"f_ring.01.R": {
+ 'head': 'right_hand_ring_finger_mcp',
+ 'tail': 'right_hand_ring_finger_pip',
+},
+"f_ring.02.R": {
+ 'head': 'right_hand_ring_finger_pip',
+ 'tail': 'right_hand_ring_finger_dip',
+},
+"f_ring.03.R": {
+ 'head': 'right_hand_ring_finger_dip',
+ 'tail': 'right_hand_ring_finger_tip',
+},
+
+"f_pinky.01.R": {
+ 'head': 'right_hand_pinky_finger_mcp',
+ 'tail': 'right_hand_pinky_finger_pip',
+},
+"f_pinky.02.R": {
+ 'head': 'right_hand_pinky_finger_pip',
+ 'tail': 'right_hand_pinky_finger_dip',
+},
+"f_pinky.03.R": {
+ 'head': 'right_hand_pinky_finger_dip',
+ 'tail': 'right_hand_pinky_finger_tip',
+},
+"thumb.01.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_thumb_mcp',
+},
+"thumb.02.L": {
+ 'head': 'left_hand_thumb_mcp',
+ 'tail': 'left_hand_thumb_ip',
+},
+"thumb.03.L": {
+ 'head': 'left_hand_thumb_ip',
+ 'tail': 'left_hand_thumb_tip',
+},
+"palm.01.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_index_finger_mcp',
+},
+"palm.02.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_middle_finger_mcp',
+},
+"palm.03.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_ring_finger_mcp',
+},
+"palm.04.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_pinky_finger_mcp',
+},
+"f_index.01.L": {
+ 'head': 'left_hand_index_finger_mcp',
+ 'tail': 'left_hand_index_finger_pip',
+},
+"f_index.02.L": {
+ 'head': 'left_hand_index_finger_pip',
+ 'tail': 'left_hand_index_finger_dip',
+},
+"f_index.03.L": {
+ 'head': 'left_hand_index_finger_dip',
+ 'tail': 'left_hand_index_finger_tip',
+},
+
+"f_middle.01.L": {
+ 'head': 'left_hand_middle_finger_mcp',
+ 'tail': 'left_hand_middle_finger_pip',
+},
+"f_middle.02.L": {
+ 'head': 'left_hand_middle_finger_pip',
+ 'tail': 'left_hand_middle_finger_dip',
+},
+"f_middle.03.L": {
+ 'head': 'left_hand_middle_finger_dip',
+ 'tail': 'left_hand_middle_finger_tip',
+},
+"f_ring.01.L": {
+ 'head': 'left_hand_ring_finger_mcp',
+ 'tail': 'left_hand_ring_finger_pip',
+},
+"f_ring.02.L": {
+ 'head': 'left_hand_ring_finger_pip',
+ 'tail': 'left_hand_ring_finger_dip',
+},
+"f_ring.03.L": {
+ 'head': 'left_hand_ring_finger_dip',
+ 'tail': 'left_hand_ring_finger_tip',
+},
+"f_pinky.01.L": {
+ 'head': 'left_hand_pinky_finger_mcp',
+ 'tail': 'left_hand_pinky_finger_pip',
+},
+"f_pinky.02.L": {
+ 'head': 'left_hand_pinky_finger_pip',
+ 'tail': 'left_hand_pinky_finger_dip',
+},
+"f_pinky.03.L": {
+ 'head': 'left_hand_pinky_finger_dip',
+ 'tail': 'left_hand_pinky_finger_tip',
+},
+
+}
+
+
+#%% create metarig
+bpy.ops.object.armature_human_metarig_add()
+this_metarig = bpy.context.active_object
+
+#%% loop through dictionary - set head and tail of each bone's to the relevant empty
+# bpy.ops.object.posemode_toggle()
+try:
+ bpy.ops.object.mode_set(mode='EDIT')
+except:
+ pass
+
+for this_bone in list(this_metarig.data.bones):
+ this_bone_name = this_bone.name
+ print(f'--{this_bone_name}--')
+
+ this_edit_bone= this_metarig.data.edit_bones[this_bone_name] # note this is using EDIT_bones, not regular bones b/c blender is a wild wacky place
+
+ if this_bone_name in metarig_bone_empty_pairs_dict_of_dicts:
+ this_bone_dict = metarig_bone_empty_pairs_dict_of_dicts[this_bone_name]
+
+ this_head_empty_name = this_bone_dict['head']
+ this_tail_empty_name = this_bone_dict['tail']
+ print('setting (bone:head->tail){}:{}->{})'.format(this_bone_name, this_head_empty_name, this_tail_empty_name))
+
+ if this_tail_empty_name is not None:
+ print(f'setting bone: {this_bone_name}: head: {bpy.data.objects[this_head_empty_name].location}, tail: {bpy.data.objects[this_tail_empty_name].location}')
+ this_edit_bone.head = bpy.data.objects[this_head_empty_name].location
+ this_edit_bone.tail = bpy.data.objects[this_tail_empty_name].location
+ else: #remove bones with no tail (and/or head) until we figure out a better plan
+ print(f'removing bone: {this_bone_name}')
+ this_metarig.data.edit_bones.remove(this_edit_bone)
+ else:
+ print(f'removing bone: {this_bone_name}')
+ this_metarig.data.edit_bones.remove(this_edit_bone)
+
+try:
+ bpy.ops.object.mode_set(mode='OBJECT')
+except:
+ pass
+
+
+
+
+#######################################################
+#### Damped track bones to empties
+bpy.ops.object.mode_set(mode='OBJECT')
+armature_name = 'metarig'
+this_armature = bpy.data.objects[armature_name]
+
+rig_constraint_dict_of_dicts = {
+ "spine": {
+ 'COPY_LOCATION': 'hip_center',
+ 'DAMPED_TRACK': 'chest_center',
+ },
+ "spine.001": {
+ 'DAMPED_TRACK': 'neck_center',
+ },
+ "spine.002": {
+ 'DAMPED_TRACK': 'head_center',
+ },
+ "spine.003": {
+ 'DAMPED_TRACK': 'nose',
+ },
+ "pelvis.L": {
+ 'DAMPED_TRACK': 'left_hip',
+ },
+ "thigh.L": {
+ 'COPY_LOCATION': 'left_hip',
+ 'DAMPED_TRACK': 'left_knee',
+ },
+ "shin.L": {
+ 'DAMPED_TRACK': 'left_ankle',
+ },
+ "foot.L": {
+ 'DAMPED_TRACK': 'left_foot_index',
+ },
+ "heel.02.L": {
+ 'DAMPED_TRACK': 'left_ankle',
+ },
+ "shoulder.L": {
+ 'COPY_LOCATION': 'neck_center',
+ 'DAMPED_TRACK': 'left_shoulder',
+ },
+ "upper_arm.L": {
+ 'DAMPED_TRACK': 'left_elbow',
+ },
+ "forearm.L": {
+ 'DAMPED_TRACK': 'left_wrist',
+ },
+ "hand.L": {
+ 'DAMPED_TRACK': 'left_index',
+ },
+ "pelvis.R": {
+ 'DAMPED_TRACK': 'right_hip',
+ },
+ "thigh.R": {
+ 'COPY_LOCATION': 'right_hip',
+ 'DAMPED_TRACK': 'right_knee',
+ },
+ "shin.R": {
+ 'DAMPED_TRACK': 'right_ankle',
+ },
+ "foot.R": {
+ 'DAMPED_TRACK': 'right_foot_index',
+ },
+ "heel.02.R": {
+ 'DAMPED_TRACK': 'right_ankle',
+ },
+ "shoulder.R": {
+ 'COPY_LOCATION': 'neck_center',
+ 'DAMPED_TRACK': 'right_shoulder',
+ },
+ "upper_arm.R": {
+ 'DAMPED_TRACK': 'right_elbow',
+ },
+ "forearm.R": {
+ 'DAMPED_TRACK': 'right_wrist',
+ },
+ "hand.R": {
+ 'DAMPED_TRACK': 'right_index',
+ },
+ "thumb.01.R": {
+ 'COPY_LOCATION': 'right_wrist',
+ 'DAMPED_TRACK': 'right_hand_thumb_mcp',
+ },
+ "thumb.02.R": {
+ 'DAMPED_TRACK': 'right_hand_thumb_ip',
+ },
+ "thumb.02.R": {
+ 'DAMPED_TRACK': 'right_hand_thumb_tip',
+ },
+ "palm.01.R": {
+ 'COPY_LOCATION': 'right_wrist',
+ 'DAMPED_TRACK': 'right_hand_index_finger_mcp',
+ },
+ "f_index.01.R": {
+ 'DAMPED_TRACK': 'right_hand_index_finger_pip',
+ },
+ "f_index.02.R": {
+ 'DAMPED_TRACK': 'right_hand_index_finger_dip',
+ },
+ "f_index.03.R": {
+ 'DAMPED_TRACK': 'right_hand_index_finger_tip',
+ },
+ "palm.02.R": {
+ 'COPY_LOCATION': 'right_wrist',
+ 'DAMPED_TRACK': 'right_hand_middle_finger_mcp',
+ },
+ "f_middle.01.R": {
+ 'DAMPED_TRACK': 'right_hand_middle_finger_pip',
+ },
+ "f_middle.02.R": {
+ 'DAMPED_TRACK': 'right_hand_middle_finger_dip',
+ },
+ "f_middle.03.R": {
+ 'DAMPED_TRACK': 'right_hand_middle_finger_tip',
+ },
+ "palm.03.R": {
+ 'COPY_LOCATION': 'right_wrist',
+ 'DAMPED_TRACK': 'right_hand_ring_finger_mcp',
+ },
+ "f_ring.01.R": {
+ 'DAMPED_TRACK': 'right_hand_ring_finger_pip',
+ },
+ "f_ring.02.R": {
+ 'DAMPED_TRACK': 'right_hand_ring_finger_dip',
+ },
+ "f_ring.03.R": {
+ 'DAMPED_TRACK': 'right_hand_ring_finger_tip',
+ },
+ "palm.04.R": {
+ 'COPY_LOCATION': 'right_wrist',
+ 'DAMPED_TRACK': 'right_hand_pinky_finger_mcp',
+ },
+ "f_pinky.01.R": {
+ 'DAMPED_TRACK': 'right_hand_pinky_finger_pip',
+ },
+ "f_pinky.02.R": {
+ 'DAMPED_TRACK': 'right_hand_pinky_finger_dip',
+ },
+ "f_pinky.03.R": {
+ 'DAMPED_TRACK': 'right_hand_pinky_finger_tip',
+ },
+ "thumb.01.L": {
+ 'COPY_LOCATION': 'left_wrist',
+ 'DAMPED_TRACK': 'left_hand_thumb_mcp',
+ },
+ "thumb.02.L": {
+ 'DAMPED_TRACK': 'left_hand_thumb_ip',
+ },
+ "thumb.03.L": {
+ 'DAMPED_TRACK': 'left_hand_thumb_tip',
+ },
+ "palm.01.L": {
+ 'COPY_LOCATION': 'left_wrist',
+ 'DAMPED_TRACK': 'left_hand_index_finger_mcp',
+ },
+ "f_index.01.L": {
+ 'DAMPED_TRACK': 'left_hand_index_finger_pip',
+ },
+ "f_index.02.L": {
+ 'DAMPED_TRACK': 'left_hand_index_finger_dip',
+ },
+ "f_index.03.L": {
+ 'DAMPED_TRACK': 'left_hand_index_finger_tip',
+ },
+ "palm.02.L": {
+ 'COPY_LOCATION': 'left_wrist',
+ 'DAMPED_TRACK': 'left_hand_middle_finger_mcp',
+ },
+ "f_middle.01.L": {
+ 'DAMPED_TRACK': 'left_hand_middle_finger_pip',
+ },
+ "f_middle.02.L": {
+ 'DAMPED_TRACK': 'left_hand_middle_finger_dip',
+ },
+ "f_middle.03.L": {
+ 'DAMPED_TRACK': 'left_hand_middle_finger_tip',
+ },
+ "palm.03.L": {
+ 'COPY_LOCATION': 'left_wrist',
+ 'DAMPED_TRACK': 'left_hand_ring_finger_mcp',
+ },
+ "f_ring.01.L": {
+ 'DAMPED_TRACK': 'left_hand_ring_finger_pip',
+ },
+ "f_ring.02.L": {
+ 'DAMPED_TRACK': 'left_hand_ring_finger_dip',
+ },
+ "f_ring.03.L": {
+ 'DAMPED_TRACK': 'left_hand_ring_finger_tip',
+ },
+ "palm.04.L": {
+ 'COPY_LOCATION': 'left_wrist',
+ 'DAMPED_TRACK': 'left_hand_pinky_finger_mcp',
+ },
+ "f_pinky.01.L": {
+ 'DAMPED_TRACK': 'left_hand_pinky_finger_pip',
+ },
+ "f_pinky.02.L": {
+ 'DAMPED_TRACK': 'left_hand_pinky_finger_dip',
+ },
+ "f_pinky.03.L": {
+ 'DAMPED_TRACK': 'left_hand_pinky_finger_tip',
+ },
+}
+
+#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}')
+
+ this_bone= this_armature.pose.bones[this_bone_name]
+
+ 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 object
+
+##############
+## create extra bones
+
+extra_bone_empty_pairs_dict_of_dicts = {
+"hand.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_index',
+},
+"forearm.L": {
+ 'head': 'left_elbow',
+ 'tail': 'left_wrist',
+},
+}
+
+###################################################################
+#### Create Stick Figure Mesh
+
+stick_figure_mesh_edge_pairs_dict_of_dicts = {
+
+ "forearm.L": {
+ 'head': 'left_elbow',
+ 'tail': 'left_wrist',
+ },
+ "upper_arm.L": {
+ 'head': 'left_shoulder',
+ 'tail': 'left_elbow',
+ },
+ "shoulder.L": {
+ 'head': 'neck_center',
+ 'tail': 'left_shoulder',
+ },
+ "forearm.R": {
+ 'head': 'right_elbow',
+ 'tail': 'right_wrist',
+ },
+ "upper_arm.R": {
+ 'head': 'right_shoulder',
+ 'tail': 'right_elbow',
+ },
+ "shoulder.R": {
+ 'head': 'neck_center',
+ 'tail': 'right_shoulder',
+ },
+ "thigh.L": {
+ 'head': 'left_hip',
+ 'tail': 'left_knee',
+ },
+ "shin.L": {
+ 'head': 'left_knee',
+ 'tail': 'left_ankle',
+ },
+ "heel.02.L": {
+ 'head': 'left_heel',
+ 'tail': 'left_ankle',
+ },
+ "foot.L": {
+ 'head': 'left_ankle',
+ 'tail': 'left_foot_index',
+ },
+ "toe.L": {
+ 'head': 'left_foot_index',
+ 'tail': 'left_heel',
+ },
+ "thigh.R": {
+ 'head': 'right_hip',
+ 'tail': 'right_knee',
+ },
+ "shin.R": {
+ 'head': 'right_knee',
+ 'tail': 'right_ankle',
+ },
+ "heel.02.R": {
+ 'head': 'right_heel',
+ 'tail': 'right_ankle',
+ },
+ "foot.R": {
+ 'head': 'right_ankle',
+ 'tail': 'right_foot_index',
+ },
+ "toe.R": {
+ 'head': 'right_foot_index',
+ 'tail': 'right_heel',
+ },
+ "pelvis.L": {
+ 'head': 'hip_center',
+ 'tail': 'left_hip',
+ },
+ "pelvis.R": {
+ 'head': 'hip_center',
+ 'tail': 'right_hip',
+ },
+ "spine": {
+ 'head': 'hip_center',
+ 'tail': 'chest_center',
+ },
+ "spine.001": {
+ 'head': 'chest_center',
+ 'tail': 'neck_center',
+ },
+ "spine.002": {
+ 'head': 'neck_center',
+ 'tail': 'head_center',
+ },
+ "spine.003": {
+ 'head': 'head_center',
+ 'tail': 'nose',
+ },
+ "palm.01.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_index_finger_mcp',
+ },
+ "palm.02.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_middle_finger_mcp',
+ },
+ "palm.03.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_ring_finger_mcp',
+ },
+ "palm.04.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_pinky_finger_mcp',
+ },
+
+ "thumb.01.R": {
+ 'head': 'right_wrist',
+ 'tail': 'right_hand_thumb_cmc',
+ },
+ "thumb.02.R": {
+ 'head': 'right_hand_thumb_cmc',
+ 'tail': 'right_hand_thumb_mcp',
+ },
+ "thumb.03.R": {
+ 'head': 'right_hand_thumb_mcp',
+ 'tail': 'right_hand_thumb_ip',
+ },
+ "thumb.04.R": {
+ 'head': 'right_hand_thumb_ip',
+ 'tail': 'right_hand_thumb_tip',
+ },
+ "f_index.01.R": {
+ 'head': 'right_hand_index_finger_mcp',
+ 'tail': 'right_hand_index_finger_pip',
+ },
+ "f_index.02.R": {
+ 'head': 'right_hand_index_finger_pip',
+ 'tail': 'right_hand_index_finger_dip',
+ },
+ "f_index.03.R": {
+ 'head': 'right_hand_index_finger_dip',
+ 'tail': 'right_hand_index_finger_tip',
+ },
+ "f_middle.01.R": {
+ 'head': 'right_hand_middle_finger_mcp',
+ 'tail': 'right_hand_middle_finger_pip',
+ },
+ "f_middle.02.R": {
+ 'head': 'right_hand_middle_finger_pip',
+ 'tail': 'right_hand_middle_finger_dip',
+ },
+ "f_middle.03.R": {
+ 'head': 'right_hand_middle_finger_dip',
+ 'tail': 'right_hand_middle_finger_tip',
+ },
+ "f_ring.01.R": {
+ 'head': 'right_hand_ring_finger_mcp',
+ 'tail': 'right_hand_ring_finger_pip',
+ },
+ "f_ring.02.R": {
+ 'head': 'right_hand_ring_finger_pip',
+ 'tail': 'right_hand_ring_finger_dip',
+ },
+ "f_ring.03.R": {
+ 'head': 'right_hand_ring_finger_dip',
+ 'tail': 'right_hand_ring_finger_tip',
+ },
+
+ "f_pinky.01.R": {
+ 'head': 'right_hand_pinky_finger_mcp',
+ 'tail': 'right_hand_pinky_finger_pip',
+ },
+ "f_pinky.02.R": {
+ 'head': 'right_hand_pinky_finger_pip',
+ 'tail': 'right_hand_pinky_finger_dip',
+ },
+ "f_pinky.03.R": {
+ 'head': 'right_hand_pinky_finger_dip',
+ 'tail': 'right_hand_pinky_finger_tip',
+ },
+ "thumb.01.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_thumb_cmc',
+ },
+ "thumb.02.L": {
+ 'head': 'left_hand_thumb_cmc',
+ 'tail': 'left_hand_thumb_mcp',
+ },
+ "thumb.03.L": {
+ 'head': 'left_hand_thumb_mcp',
+ 'tail': 'left_hand_thumb_ip',
+ },
+ "thumb.04.L": {
+ 'head': 'left_hand_thumb_ip',
+ 'tail': 'left_hand_thumb_tip',
+ },
+ "palm.01.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_index_finger_mcp',
+ },
+ "palm.02.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_middle_finger_mcp',
+ },
+ "palm.03.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_ring_finger_mcp',
+ },
+ "palm.04.L": {
+ 'head': 'left_wrist',
+ 'tail': 'left_hand_pinky_finger_mcp',
+ },
+ "f_index.01.L": {
+ 'head': 'left_hand_index_finger_mcp',
+ 'tail': 'left_hand_index_finger_pip',
+ },
+ "f_index.02.L": {
+ 'head': 'left_hand_index_finger_pip',
+ 'tail': 'left_hand_index_finger_dip',
+ },
+ "f_index.03.L": {
+ 'head': 'left_hand_index_finger_dip',
+ 'tail': 'left_hand_index_finger_tip',
+ },
+ "f_middle.01.L": {
+ 'head': 'left_hand_middle_finger_mcp',
+ 'tail': 'left_hand_middle_finger_pip',
+ },
+ "f_middle.02.L": {
+ 'head': 'left_hand_middle_finger_pip',
+ 'tail': 'left_hand_middle_finger_dip',
+ },
+ "f_middle.03.L": {
+ 'head': 'left_hand_middle_finger_dip',
+ 'tail': 'left_hand_middle_finger_tip',
+ },
+ "f_ring.01.L": {
+ 'head': 'left_hand_ring_finger_mcp',
+ 'tail': 'left_hand_ring_finger_pip',
+ },
+ "f_ring.02.L": {
+ 'head': 'left_hand_ring_finger_pip',
+ 'tail': 'left_hand_ring_finger_dip',
+ },
+ "f_ring.03.L": {
+ 'head': 'left_hand_ring_finger_dip',
+ 'tail': 'left_hand_ring_finger_tip',
+ },
+ "f_pinky.01.L": {
+ 'head': 'left_hand_pinky_finger_mcp',
+ 'tail': 'left_hand_pinky_finger_pip',
+ },
+ "f_pinky.02.L": {
+ 'head': 'left_hand_pinky_finger_pip',
+ 'tail': 'left_hand_pinky_finger_dip',
+ },
+ "f_pinky.03.L": {
+ 'head': 'left_hand_pinky_finger_dip',
+ 'tail': 'left_hand_pinky_finger_tip',
+ },
+ }
+
+mediapipe_virtual_markers_weights_dict = {
+ 'head_center':{
+ 'right_ear': .5,
+ 'left_ear': .5
+ },
+ 'neck_center':{
+ 'right_shoulder': .5,
+ 'left_shoulder': .5
+ },
+ 'hip_center':{
+ 'right_hip': .5,
+ 'left_hip': .5
+ },
+ 'chest_center':{
+ 'right_shoulder': .25,
+ 'left_shoulder': .25,
+ 'right_hip': .25,
+ 'left_hip': .25,
+ },
+}
+
+print('loading data as stick figure mesh \o/')
+#######################################################################
+
+#%% create virtual marker points (redundant from above, I think ? )
+
+
+
+current_frame = bpy.data.scenes[0].frame_current
+virtual_point_index_dict = {}
+for this_virtual_marker_dict in mediapipe_virtual_markers_weights_dict.items():
+ this_virtual_marker_name = this_virtual_marker_dict[0]
+ these_weighted_points = []
+ for this_weighted_point_dict in this_virtual_marker_dict[1].items():
+ this_point_name = this_weighted_point_dict[0]
+
+ this_weight = this_weighted_point_dict[1]
+ these_weighted_points.append(
+ mediapipe_skel_fr_mar_dim[
+ :,
+ mediapipe_tracked_point_names.index(this_point_name),
+ :
+ ]*this_weight
+ )
+ this_virtual_point_fr_xyz = np.sum(these_weighted_points, axis=0)
+ this_virtual_point_fr_mar_xyz = np.expand_dims(this_virtual_point_fr_xyz, axis=1)
+ mediapipe_skel_fr_mar_dim = np.append(mediapipe_skel_fr_mar_dim,this_virtual_point_fr_mar_xyz, axis=1)
+ virtual_point_index_dict[this_virtual_marker_name] = mediapipe_skel_fr_mar_dim.shape[1]-1
+ print(f'Virtual marker: {this_virtual_marker_name} created at marker index {mediapipe_skel_fr_mar_dim.shape[1]-1}')
+
+
+#%% define edges
+
+
+edges = []
+#regular data
+for this_bone_dict in stick_figure_mesh_edge_pairs_dict_of_dicts.items():
+ edge_name = this_bone_dict[0]
+ head_name = this_bone_dict[1]['head']
+ tail_name = this_bone_dict[1]['tail']
+
+
+ try:
+
+ head_index = mediapipe_tracked_point_names.index(head_name)
+ tail_index = mediapipe_tracked_point_names.index(tail_name)
+
+ if 'center' in head_name: #virtual markers are acting weird so we're brute forcing it :-/ this will fail if there is a virtual marker without 'center' in the name....
+ head_index = virtual_point_index_dict[head_name]
+ if 'center' in tail_name:
+ tail_index = virtual_point_index_dict[tail_name]
+
+ this_edge =(head_index, tail_index)
+
+ edges.append(this_edge)
+ print(f'edge created for bone: ({this_bone_dict[0]} : {head_name}-{tail_name}), indicies({this_edge[0]},{this_edge[1]})')
+ except:
+ print(f'edge FAILED for for bone:{this_bone_dict[0]} : {head_name}-{tail_name}')
+ pass
+
+
+
+
+##############################
+#%% Create mesh
+try:
+ bpy.ops.object.mode_set(mode='OBJECT')
+except:
+ pass
+
+stick_figure_mesh = bpy.data.meshes.new('stick_figure_mesh')
+
+vertices = mediapipe_skel_fr_mar_dim[current_frame,:,:]
+#edges defined above
+faces = []
+
+stick_figure_mesh.from_pydata(vertices, edges, faces)
+stick_figure_mesh.update()
+# make object from mesh
+stick_figure_mesh_object = bpy.data.objects.new('stick_figure_mesh', stick_figure_mesh)
+# make collection
+mesh_collection = bpy.data.collections.new('mesh_collection')
+bpy.context.scene.collection.children.link(mesh_collection)
+# add object to scene collection
+mesh_collection.objects.link(stick_figure_mesh_object)
+
+bpy.context.view_layer.objects.active = bpy.data.objects['stick_figure_mesh']
+bpy.ops.object.mode_set(mode='EDIT')
+
+#### skin that mesh!
+print('skinning mesh \o/')
+bpy.data.objects['stick_figure_mesh'].modifiers.new('stick_figure_mesh_skin', 'SKIN')
+print('resizing mesh')
+skin_radius = .025
+bpy.ops.transform.skin_resize(value=(skin_radius, skin_radius, skin_radius))
+
+
+########
+# # parent mesh to armature
+print('parenting mesh to armarture with automatic weights...')
+bpy.ops.object.mode_set(mode='OBJECT')
+bpy.data.objects['stick_figure_mesh'].parent = this_metarig
+bpy.context.view_layer.objects.active = this_metarig
+bpy.context.active_object.select_set(True)
+bpy.data.objects['stick_figure_mesh'].select_set(True)
+bpy.ops.object.parent_set(type='ARMATURE_AUTO')
+
+
+#####################
+## Load nSynched Videos
+try:
+ print('loading videos as planes...')
+ vidFolderPath = session_path / 'SyncedVideos'
+
+ world_origin = bpy.data.objects['world_origin']
+
+ number_of_videos = len(list(vidFolderPath.glob('*.mp4')))
+
+ vid_location_scale = 3
+
+
+ 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:
+ print('Failed to load videos to Blender scene - You might need to install the "images as planes" addon to this version of Blender')
+
+# save .blend file
+sessionID = session_path.stem
+blend_file_save_path = session_path / (sessionID + '.blend')
+print(f"Saving Blender output file to: {str(blend_file_save_path)}")
+bpy.ops.wm.save_as_mainfile(filepath= str(blend_file_save_path) )
\ No newline at end of file