Free Motion Capture for Everyone πβ¨
TypeScript
Simultaneous DLC + MediaPipe + OpenPose Support!
jon matthis8e2914e54692
diff --git a/freemocap/calibrate.py b/freemocap/calibrate.pyindex eae7dfc2..9ea6de6d 100644--- a/freemocap/calibrate.py+++ b/freemocap/calibrate.py@@ -1,5 +1,4 @@from aniposelib.cameras import CameraGroup-from freemocap import stolenfromaniposefrom aniposelib.utils import load_pose2d_fnamesimport numpy as np@@ -7,7 +6,7 @@ import cv2import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D-from freemocap import reconstruct3D, stolenfromanipose+from freemocap import reconstruct3D, fmc_aniposeimport osfrom rich.progress import track@@ -25,7 +24,7 @@ def CalibrateCaptureVolume(session,board):cam_names.append(str(count))session.numCams = count- cgroup = stolenfromanipose.CameraGroup.from_names(cam_names, fisheye=True) #Looking through their code... it looks lke the 'fisheye=True' doesn't do much (see 2020-03-29 obsidian note)+ cgroup = fmc_anipose.CameraGroup.from_names(cam_names, fisheye=True) #Looking through their code... it looks lke the 'fisheye=True' doesn't do much (see 2020-03-29 obsidian note)@@ -105,13 +104,12 @@ def CalibrateCaptureVolume(session,board):except:print('failed frame:', frame)continue- charuco_nCams_nFrames_nImgPts_XY = np.array(charucoarray)+ charuco_nCams_nFrames_nImgPts_XY = np.squeeze(np.array(charucoarray))session.charuco_nCams_nFrames_nImgPts_XY = charuco_nCams_nFrames_nImgPts_XY- charuco_params = charuco_nCams_nFrames_nImgPts_XY.shape[0:3]- charuco_fr_mar_dim = reconstruct3D.reconstruct3D(session,charuco_nCams_nFrames_nImgPts_XY,charuco_params)+ charuco_fr_mar_dim = reconstruct3D.reconstruct3D(session,charuco_nCams_nFrames_nImgPts_XY)mean_charuco_fr_mar_dim = np.nanmean(charuco_fr_mar_dim,axis = 0)@@ -135,6 +133,9 @@ def CalibrateCaptureVolume(session,board):mx = np.nanmean(x)my = np.nanmean(y)mz = np.nanmean(z)+++ax1.scatter(x,y,z, marker='o')ax1.set_title('Mean Charuco Point Positions')@@ -149,14 +150,11 @@ def CalibrateCaptureVolume(session,board):ax1.scatter(cgroup.cameras[camNum].tvec[0], cgroup.cameras[camNum].tvec[1], cgroup.cameras[camNum].tvec[2], marker = 'p')-- mx = np.nanmean(mx)- my = np.nanmean(my)- mz = np.nanmean(mz)+ axRange = board.square_length*5- ax1.set_xlim(mx-100,mx+100)- ax1.set_ylim(my-100,my+100)- ax1.set_zlim(mz-100,mz+100)+ ax1.set_xlim(mx-axRange,mx+axRange)+ ax1.set_ylim(my-axRange,my+axRange)+ ax1.set_zlim(mz-axRange,mz+axRange)# #charuco points over time# ax2 = fig.add_subplot(122)diff --git a/freemocap/stolenfromanipose.py b/freemocap/fmc_anipose.pysimilarity index 100%rename from freemocap/stolenfromanipose.pyrename to freemocap/fmc_anipose.pydiff --git a/freemocap/fmc_deeplabcut.py b/freemocap/fmc_deeplabcut.pynew file mode 100644index 00000000..715ce81a--- /dev/null+++ b/freemocap/fmc_deeplabcut.py@@ -0,0 +1,82 @@+# -*- coding: utf-8 -*-+"""+Created on Fri Feb 26 12:42:08 2021++@author: Rontc+"""+import glob+import numpy as np+import pandas as pd+import matplotlib.pyplot as plt+import yaml+from pathlib import Path+import h5py++++++def parseDeepLabCut(session): # NOTE this is assuming both the dlc config file and dlc data h5 foles are in the same folder specified in the session.dlcDataPath, if that is not the case either dlcconfig or h5files variable need to be changed++ dlcConfig = session.dlcConfigPath #File path for dlcConfig file+++ with open(dlcConfig) as configFile:+ #Open the config file+ configList = yaml.load(configFile, Loader = yaml.FullLoader)+ for item, doc in configList.items(): #For each item in the config file+ if item == 'bodyparts': #If the item is bodyparts+ bodypartList = doc #Set that list to a variable+ if item == 'skeleton': #If the item is skeleton+ skeletonList = doc #Set that list to a variable++ h5files =session.dlcDataPath.glob('*.h5') #Take all h5 files from folder++ numCams = int(session.numCams)#Get num of cams+ numFrames = session.numFrames+1#Get num of frames++ numPoints = len(bodypartList)# Get amount of points tracked+ dlcData_nCams_nFrames_nImgPts_XYC = np.ndarray([numCams, numFrames, numPoints, 3]) # Create empty array for dlc points++ nn=0#counter for each camera+ for data in h5files:#Loop throuxgh each camera+ with h5py.File(data) as f:#Open each h5 file+ fullDataGroup = f.get('df_with_missing')#Open main h5 group+ dataTable = fullDataGroup.get('table')#Open datatable with all DLC tracked points+ for ii in range(len(dataTable)):#Loop through each frame+ dataFromOneFrame = dataTable[ii] #Assign frame to varible+ idx =(len(dataFromOneFrame[1])/3) #index for reshaping data+ sortedFrame = np.array(dataFromOneFrame[1]) #Put data in numoy array+ dlcData_nCams_nFrames_nImgPts_XYC[nn,ii,:,:] =sortedFrame.reshape(int(idx),3) #Reshape the data into the correct form+ nn+=1++ if session.debug:+ fig = plt.figure()++ ax1 = fig.add_subplot(221)+ ax2 = fig.add_subplot(222)+ ax3 = fig.add_subplot(223)+ ax4 = fig.add_subplot(224)++ cam1im = session.firstImage_nCams_list[0]+ cam2im = session.firstImage_nCams_list[1]+ cam3im = session.firstImage_nCams_list[2]+ cam4im = session.firstImage_nCams_list[3]++ ax1.imshow(cam1im)+ ax1.plot(dlcData_nCams_nFrames_nImgPts_XYC[0,0,:,0],dlcData_nCams_nFrames_nImgPts_XYC[0,0,:,1])++ ax2.imshow(cam2im)+ ax2.plot(dlcData_nCams_nFrames_nImgPts_XYC[1,0,:,0],dlcData_nCams_nFrames_nImgPts_XYC[1,0,:,1])++ ax3.imshow(cam3im)+ ax3.plot(dlcData_nCams_nFrames_nImgPts_XYC[2,0,:,0],dlcData_nCams_nFrames_nImgPts_XYC[2,0,:,1])++ ax4.imshow(cam4im)+ ax4.plot(dlcData_nCams_nFrames_nImgPts_XYC[3,0,:,0],dlcData_nCams_nFrames_nImgPts_XYC[3,0,:,1])++ plt.show()++ np.save(session.dataArrayPath/'deepLabCutData_2d.npy', dlcData_nCams_nFrames_nImgPts_XYC)++ return dlcData_nCams_nFrames_nImgPts_XYC\ No newline at end of filediff --git a/freemocap/fmc_mediapipe.py b/freemocap/fmc_mediapipe.pynew file mode 100644index 00000000..4ad1e4ff--- /dev/null+++ b/freemocap/fmc_mediapipe.py@@ -0,0 +1,201 @@+import os+from pathlib import Path+import glob+import json++import numpy as np+from rich.progress import Progress+from ruamel.yaml import YAML+import cv2+import h5py+import mediapipe as mp+from pathlib import Path+mp_drawing = mp.solutions.drawing_utils+mp_holistic = mp.solutions.holistic++def runMediaPipe(session, dummyRun=False):++ mediaPipe_jsonPathList = [] #list to hold the paths to the json files+ mediaPipe_imgPathList = []+ mediaPipe_imgPathList_yaml = []+ mediaPipe_jsonPathList_yaml = []++ with mp_holistic.Holistic() as holistic:+ eachCamerasData = [] #Create an empty list that holds each cameras data+ for thisVidPath in session.syncedVidPath.iterdir(): #Run MediaPipe 'Holistic' (body, hands, face) tracker on each video in the raw video folder+ if thisVidPath.suffix =='.mp4': #NOTE - at some point we should build some list of 'synced video names' and check against that++ vidPath = session.mediaPipeDataPath / thisVidPath.stem+ jsonPath = vidPath / 'json'+ jsonPath.mkdir(parents=True, exist_ok=True) #this camera's json files (with keypoints)+ imgPath = vidPath / 'images'+ imgPath.mkdir(parents=True, exist_ok=True)+ mediaPipe_jsonPathList.append(jsonPath)+ mediaPipe_imgPathList.append(imgPath)+ mediaPipe_imgPathList_yaml.append(str(imgPath))+ mediaPipe_jsonPathList_yaml.append(str(jsonPath))+ mediaPipe_dataList = [] #Create an empty list for mediapipes data+ if not dummyRun:+ cap = cv2.VideoCapture(str(thisVidPath))++ frameNum = -1+ numFrames = cap.get(cv2.CAP_PROP_FRAME_COUNT)+ success, image = cap.read() #load first image from video++ with Progress() as progress:+ progressBar = progress.add_task('[magenta]MediaPiping: {}'.format(thisVidPath.name), total=numFrames) #make progressbar++ while success:++ if frameNum%5==0:+ progress.update(progressBar, advance=5) #increment progress bar everyh 5th frame++ frameNum += 1++ image_height, image_width, _ = image.shape++ results = holistic.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) # THIS IS WHERE THE MAGIC HAPENS (ps. Convert the BGR image to RGB before processing.)++ try:+ results.pose_landmarks.landmark+ try:+ results.left_hand_landmarks.landmark+ try:+ results.right_hand_landmarks.landmark+ try:+ results.face_landmarks.landmark+ f=9+ except:+ pass+ except:+ pass+ except:+ pass+ except:+ pass++ mediaPipe_dataList.append(results)#Append data to mediapipe data list+++ saveImages = True+ if saveImages:+ # Draw pose, left and right hands, and face landmarks on the image.+ annotated_image = image.copy()+ mp_drawing.draw_landmarks(+ annotated_image, results.face_landmarks, mp_holistic.FACE_CONNECTIONS)+ mp_drawing.draw_landmarks(+ annotated_image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS)+ mp_drawing.draw_landmarks(+ annotated_image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS)+ mp_drawing.draw_landmarks(+ annotated_image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS)++ #save annotated image+ frameName = str(frameNum).zfill(6)++ cv2.imwrite(str(imgPath)+ '/' + frameName + '.png', annotated_image)++ #load the next image (will break `while-loop` on the last frame)+ success, image = cap.read()#load next image from video+ f=9+ eachCamerasData.append(mediaPipe_dataList)#Append that cameras data for every frame to the camera datalist++ session.image_height = image_height+ session.image_width = image_width++ session.mediaPipe_jsonPathList = mediaPipe_jsonPathList+ session.mediaPipe_imgPathList = mediaPipe_imgPathList++ yaml = YAML()+ data = yaml.load(session.yamlPath)+ data['mediaPipe_imgPathList'] = mediaPipe_imgPathList_yaml+ data['mediaPipe_jsonPathList'] = mediaPipe_jsonPathList_yaml+ yaml.dump(data, session.yamlPath)+ session.mediaPipeData = eachCamerasData+++def parseMediaPipe(session):+ numCams = len(session.mediaPipeData) #Get number of cameras+ numFrames = len(session.mediaPipeData[0]) #Get number of frames+ #numBodyPoints = len(np.max(session.mediaPipeData[0][:].pose_landmarks.landmark[:]))#Get number of body points+ #numFacePoints = len(np.max(session.mediaPipeData[0][:].face_landmarks.landmark[:]))#Get number of face points+ #numLeftHandPoints = len(np.max(session.mediaPipeData[0][:].left_hand_landmarks.landmark[:]))#Get number of right hand points+ #numRightHandPoints = len(np.max(session.mediaPipeData[0][:].right_hand_landmarks.landmark[:]))#Get number of left hand points+ numBodyPoints = 33+ numFacePoints = 468+ numHandPoints = 21++ numTrackedPoints = numBodyPoints+numHandPoints*2+numFacePoints #Get total points++ #Create array of nans the size of number of cams, frame, points, XYC+ mediaPipeData_nCams_nFrames_nImgPts_XYC = np.empty((int(numCams),int(numFrames),int(numTrackedPoints),3)) # create empty array+ mediaPipeData_nCams_nFrames_nImgPts_XYC[:] = np.NaN #Fill it with NaNs!++ for camNum in range(numCams):#Loop through each camera+ for frNum in range(numFrames): #Loop through each frame+ # make empty arrays for thisFrame's data+ thisFrame_X = np.empty(numTrackedPoints)+ thisFrame_X[:] = np.nan+ thisFrame_Y = thisFrame_X.copy()+ thisFrame_C = thisFrame_X.copy()++ fullFrame = True+ if frNum == 107:+ f=9+ try:+ #pull out ThisFrame's mediapipe data (`mpData.pose_landmarks.landmark` returns something iterable Β―\_(γ)_/Β―)+ thisFrame_poseDataLandMarks = session.mediaPipeData[camNum][frNum].pose_landmarks.landmark # body ('pose') data+ #stuff body data into pre-allocated nan array+ thisFrame_X[:numBodyPoints] = [pp.x for pp in thisFrame_poseDataLandMarks] #PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels+ thisFrame_Y[:numBodyPoints] = [pp.y for pp in thisFrame_poseDataLandMarks] #PoseY data+ thisFrame_C[:numBodyPoints] = [pp.visibility for pp in thisFrame_poseDataLandMarks] #'visibility' is MediaPose's 'confidence' measure in range [0,1]+ except:+ fullFrame = False+++ # Right hand data+ try:+ thisFrame_rHandDataLandMarks = session.mediaPipeData[camNum][frNum].right_hand_landmarks.landmark #right hand data+ thisFrame_X[numBodyPoints+1:numBodyPoints+1+numHandPoints] = [pp.x for pp in thisFrame_rHandDataLandMarks] #PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels+ thisFrame_Y[numBodyPoints+1:numBodyPoints+1+numHandPoints] = [pp.y for pp in thisFrame_rHandDataLandMarks] #PoseY data+ thisFrame_C[numBodyPoints+1:numBodyPoints+1+numHandPoints] = [pp.visibility for pp in thisFrame_rHandDataLandMarks] #'visibility' is MediaPose's 'confidence' measure in range [0,1]+ except:+ fullFrame = False++ # Left hand data+ try:+ thisFrame_lHandDataLandMarks = session.mediaPipeData[camNum][frNum].left_hand_landmarks.landmark #left hand data+ thisFrame_X[numBodyPoints+numHandPoints+1:numBodyPoints+1+numHandPoints*2] = [pp.x for pp in thisFrame_lHandDataLandMarks] #PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels+ thisFrame_Y[numBodyPoints+numHandPoints+1:numBodyPoints+1+numHandPoints*2] = [pp.y for pp in thisFrame_lHandDataLandMarks] #PoseY data+ thisFrame_C[numBodyPoints+numHandPoints+1:numBodyPoints+1+numHandPoints*2] = [pp.visibility for pp in thisFrame_lHandDataLandMarks] #'visibility' is MediaPose's 'confidence' measure in range [0,1]+ except:+ fullFrame = False++ #FaceMeshData+ try:+ thisFrame_faceDataLandMarks = session.mediaPipeData[camNum][frNum].face_landmarks.landmark # face (mesh) data+ thisFrame_X[numBodyPoints+numHandPoints*2+1:-1] = [pp.x for pp in thisFrame_faceDataLandMarks] #PoseX data - Normalized screen coords (in range [0, 1]) - need multiply by image resultion for pixels+ thisFrame_Y[numBodyPoints+numHandPoints*2:-1] = [pp.y for pp in thisFrame_faceDataLandMarks] #PoseY data+ #NOTE - There's also Z data in here+ thisFrame_C[numBodyPoints+numHandPoints*2:-1] = [pp.visibility for pp in thisFrame_faceDataLandMarks] #'visibility' is MediaPose's 'confidence' measure in range [0,1]+ except:+ fullFrame = False++ if fullFrame:+ f=9++ #stuff this frame's data into pre-allocated mediaPipeData_.... array+ mediaPipeData_nCams_nFrames_nImgPts_XYC[camNum,frNum,:,0] = thisFrame_X+ mediaPipeData_nCams_nFrames_nImgPts_XYC[camNum,frNum,:,1] = thisFrame_Y+ mediaPipeData_nCams_nFrames_nImgPts_XYC[camNum,frNum,:,2] = thisFrame_C+++ #convert from normalized screen coordinates to pixel coordinates+ mediaPipeData_nCams_nFrames_nImgPts_XYC[:,:,:,0] *= session.image_height+ mediaPipeData_nCams_nFrames_nImgPts_XYC[:,:,:,1] *= session.image_width++ np.save(session.dataArrayPath/'mediaPipe_2d.npy', mediaPipeData_nCams_nFrames_nImgPts_XYC)++++ return mediaPipeData_nCams_nFrames_nImgPts_XYC\ No newline at end of filediff --git a/freemocap/runopenpose.py b/freemocap/fmc_openpose.pysimilarity index 92%rename from freemocap/runopenpose.pyrename to freemocap/fmc_openpose.pyindex ab223ed3..09a4998a 100644--- a/freemocap/runopenpose.py+++ b/freemocap/fmc_openpose.py@@ -118,17 +118,12 @@ def parseOpenPose(session):- openPoseData_nCams_nFrames_nImgPts_XY = openPoseData_nCams_nFrames_nImgPts_XYC[:,:,:,0:2].copy()- openpose_confidence = openPoseData_nCams_nFrames_nImgPts_XYC[:,:,:,2].copy()-- openpose_score_threshold = .3- openPoseData_nCams_nFrames_nImgPts_XY[openpose_confidence < openpose_score_threshold] = np.nan #replace low confidence points with '-- session.dataFrameHeader = dataFrameHeader- session.numImgPoints = numImgPoints++ # session.dataFrameHeader = dataFrameHeader+ # session.numImgPoints = numImgPointssession.numFrames = frameNum #NOTE - Need to find a safer way to get this number- path_to_openpose_2d = session.dataArrayPath/'openPoseData_nCams_nFrames_nImgPts_XY.npy'- np.save(path_to_openpose_2d, openPoseData_nCams_nFrames_nImgPts_XY)+ path_to_openpose_2d = session.dataArrayPath/'openPoseData_2d.npy'+ np.save(path_to_openpose_2d, openPoseData_nCams_nFrames_nImgPts_XYC)- return openPoseData_nCams_nFrames_nImgPts_XY\ No newline at end of file+ return openPoseData_nCams_nFrames_nImgPts_XYC\ No newline at end of filediff --git a/freemocap/initialization.py b/freemocap/initialization.pyindex 11d945b1..32fe0cc8 100644--- a/freemocap/initialization.py+++ b/freemocap/initialization.py@@ -7,13 +7,16 @@ import pandas as pdimport numpy as npfrom freemocap.webcam import recordGUI,camsetup-from freemocap import recordingconfig, stolenfromanipose+from freemocap import recordingconfig, fmc_aniposedef initialize(session, stage, board):print('Starting initialization for stage {}'.format(stage))#if stage == 1:filepath = Path.cwd()++ session.board = board+# %% Stage One Initializationif stage == 1:@@ -171,11 +174,10 @@ def initialize(session, stage, board):session.config_settings = recordingconfig.load_config_yaml(session.yamlPath) #config settings = paths and camera parameter inputsrecordingconfig.load_session_paths(session,session.config_settings) #add paths to session class- session.mediaPipe_imgPathList = session.config_settings['mediaPipe_imgPathList']- session.numCams = len(session.mediaPipe_imgPathList)+ session.openPose_imgPathList = session.config_settings['openPose_imgPathList']+ session.numCams = len(session.openPose_imgPathList)- session.mean_charuco_fr_mar_dim = np.load(session.dataArrayPath/'charuco_points.npy')- session.skel_fr_mar_dim = np.load(session.dataArrayPath/'skeleton_points.npy')+if stage == 8:diff --git a/freemocap/playskeleton.py b/freemocap/playskeleton.pyindex aa142012..153565c2 100644--- a/freemocap/playskeleton.py+++ b/freemocap/playskeleton.py@@ -143,22 +143,39 @@ from pathlib import Path# plt.show()-def ReplaySkeleton(session, vidType, startframe,azimuth,elevation):+def ReplaySkeleton( session,+ vidType=1,+ startFrame=40,+ azimuth=-90,+ elevation=-80,+ useOpenPose=True,+ useMediaPipe=False,+ useDLC=False):- if session.mean_charuco_fr_mar_dim is None:- session.mean_charuco_fr_mar_dim = np.load(session.dataArrayPath/'charuco_points.npy')-- if session.skel_fr_mar_dim is None:- session.skel_fr_mar_dim = np.load(session.dataArrayPath/'skeleton_points.npy')++ mean_charuco_fr_mar_dim = np.load(session.dataArrayPath/'charuco_points.npy')- camImgPathList = {}+ if useOpenPose:+ skel_fr_mar_dim = np.load(session.dataArrayPath/'openPoseSkel_3d.npy')- if session.mediaPipe_imgPathList is None:- session.mediaPipe_imgPathList = session.config_settings['mediaPipe_imgPathList']- session.numCams = len(session.mediaPipe_imgPathList)+ if useMediaPipe:+ mediaPipe_skel_fr_mar_dim = np.load(session.dataArrayPath/'mediaPipeSkel_3d.npy')++ if useDLC:+ dlc_fr_mar_dim = np.load(session.dataArrayPath/'deepLabCut_3d.npy')+ dlc0 = np.squeeze(dlc_fr_mar_dim[:,0,:])+ dlc1 = np.squeeze(dlc_fr_mar_dim[:,1,:])+ dlc2 = np.squeeze(dlc_fr_mar_dim[:,2,:])+ ballTrailLen = 4++ if useOpenPose:+ imgPathList = session.config_settings['openPose_imgPathList']+ session.numCams = len(session.openPose_imgPathList)++ camImgPathList = {}for cam in range(session.numCams):- camImgPathList[cam] = list(sorted(Path(session.mediaPipe_imgPathList[cam]).glob('*.png')))+ camImgPathList[cam] = list(sorted(Path(imgPathList[cam]).glob('*.png')))session.numFrames = len(camImgPathList[cam]) #will need to perhaps put a check in on whether numFrames between cameras are the same@@ -196,7 +213,7 @@ def ReplaySkeleton(session, vidType, startframe,azimuth,elevation):# fig.tight_layout(h_pad = 5)axMain.view_init(azim = azimuth, elev= elevation)plt.ion()- for fr in range(startframe,session.numFrames):+ for fr in range(startFrame,session.numFrames):fig.suptitle(['Frame# - ', str(fr)])axMain.cla()@@ -204,54 +221,77 @@ def ReplaySkeleton(session, vidType, startframe,azimuth,elevation):axCam1.cla()- char_x = session.mean_charuco_fr_mar_dim[:][:,0]- char_y = session.mean_charuco_fr_mar_dim[:][:,1]- char_z = session.mean_charuco_fr_mar_dim[:][:,2]-- if session.useOpenPose:- sk_x = session.skel_fr_mar_dim[fr,:,0] #skeleton x data- sk_y = session.skel_fr_mar_dim[fr,:,1] #skeleton y data- sk_z = session.skel_fr_mar_dim[fr,:,2] #skeleton z data-- axMain.scatter3D(sk_x,sk_y,sk_z, marker='.',color = 'k', s=4.)- axMain.plot(sk_x[head],sk_y[head],sk_z[head], linestyle='-', color='g', linewidth = 1.)- axMain.plot(sk_x[spine],sk_y[spine],sk_z[spine], linestyle='-', color = 'g', linewidth = 1.)- axMain.plot(sk_x[rArm],sk_y[rArm],sk_z[rArm], linestyle='-', color = 'r', linewidth = 1.)- axMain.plot(sk_x[lArm],sk_y[lArm],sk_z[lArm], linestyle='-', color = 'b', linewidth = 1.)- axMain.plot(sk_x[rLeg],sk_y[rLeg],sk_z[rLeg], linestyle='-', color = 'r', linewidth = 1.)- axMain.plot(sk_x[lLeg],sk_y[lLeg],sk_z[lLeg], linestyle='-', color = 'b', linewidth = 1.)- axMain.plot(sk_x[rFoot],sk_y[rFoot],sk_z[rFoot], linestyle='-', color = 'r', linewidth = 1.)- axMain.plot(sk_x[lFoot],sk_y[lFoot],sk_z[lFoot], linestyle='-', color = 'b', linewidth = 1.)-- # plot handybois- # right hand- axMain.plot(sk_x[thumb+rHandIDstart],sk_y[thumb+rHandIDstart],sk_z[thumb+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)- axMain.plot(sk_x[index+rHandIDstart],sk_y[index+rHandIDstart],sk_z[index+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)- axMain.plot(sk_x[bird+rHandIDstart],sk_y[bird+rHandIDstart],sk_z[bird+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)- axMain.plot(sk_x[ring+rHandIDstart],sk_y[ring+rHandIDstart],sk_z[ring+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)- axMain.plot(sk_x[pinky+rHandIDstart],sk_y[pinky+rHandIDstart],sk_z[pinky+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)-- #left hand- axMain.plot(sk_x[thumb+lHandIDstart],sk_y[thumb+lHandIDstart],sk_z[thumb+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)- axMain.plot(sk_x[index+lHandIDstart],sk_y[index+lHandIDstart],sk_z[index+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)- axMain.plot(sk_x[bird+lHandIDstart],sk_y[bird+lHandIDstart],sk_z[bird+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)- axMain.plot(sk_x[ring+lHandIDstart],sk_y[ring+lHandIDstart],sk_z[ring+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)- axMain.plot(sk_x[pinky+lHandIDstart],sk_y[pinky+lHandIDstart],sk_z[pinky+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)+ char_x = mean_charuco_fr_mar_dim[:][:,0]+ char_y = mean_charuco_fr_mar_dim[:][:,1]+ char_z = mean_charuco_fr_mar_dim[:][:,2]+++ #plot skeleton (openPose by default)++ sk_x = skel_fr_mar_dim[fr,:,0] #skeleton x data+ sk_y = skel_fr_mar_dim[fr,:,1] #skeleton y data+ sk_z = skel_fr_mar_dim[fr,:,2] #skeleton z data++ axMain.scatter3D(sk_x,sk_y,sk_z, marker='.',color = 'k', s=4.)+ axMain.plot(sk_x[head],sk_y[head],sk_z[head], linestyle='-', color='g', linewidth = 1.)+ axMain.plot(sk_x[spine],sk_y[spine],sk_z[spine], linestyle='-', color = 'g', linewidth = 1.)+ axMain.plot(sk_x[rArm],sk_y[rArm],sk_z[rArm], linestyle='-', color = 'r', linewidth = 1.)+ axMain.plot(sk_x[lArm],sk_y[lArm],sk_z[lArm], linestyle='-', color = 'b', linewidth = 1.)+ axMain.plot(sk_x[rLeg],sk_y[rLeg],sk_z[rLeg], linestyle='-', color = 'r', linewidth = 1.)+ axMain.plot(sk_x[lLeg],sk_y[lLeg],sk_z[lLeg], linestyle='-', color = 'b', linewidth = 1.)+ axMain.plot(sk_x[rFoot],sk_y[rFoot],sk_z[rFoot], linestyle='-', color = 'r', linewidth = 1.)+ axMain.plot(sk_x[lFoot],sk_y[lFoot],sk_z[lFoot], linestyle='-', color = 'b', linewidth = 1.)++ # plot handybois+ # right hand+ axMain.plot(sk_x[thumb+rHandIDstart],sk_y[thumb+rHandIDstart],sk_z[thumb+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)+ axMain.plot(sk_x[index+rHandIDstart],sk_y[index+rHandIDstart],sk_z[index+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)+ axMain.plot(sk_x[bird+rHandIDstart],sk_y[bird+rHandIDstart],sk_z[bird+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)+ axMain.plot(sk_x[ring+rHandIDstart],sk_y[ring+rHandIDstart],sk_z[ring+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)+ axMain.plot(sk_x[pinky+rHandIDstart],sk_y[pinky+rHandIDstart],sk_z[pinky+rHandIDstart], linestyle='-', color = 'r', linewidth = 1.)++ #left hand+ axMain.plot(sk_x[thumb+lHandIDstart],sk_y[thumb+lHandIDstart],sk_z[thumb+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)+ axMain.plot(sk_x[index+lHandIDstart],sk_y[index+lHandIDstart],sk_z[index+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)+ axMain.plot(sk_x[bird+lHandIDstart],sk_y[bird+lHandIDstart],sk_z[bird+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)+ axMain.plot(sk_x[ring+lHandIDstart],sk_y[ring+lHandIDstart],sk_z[ring+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)+ axMain.plot(sk_x[pinky+lHandIDstart],sk_y[pinky+lHandIDstart],sk_z[pinky+lHandIDstart], linestyle='-', color = 'b', linewidth = 1.)++ #plot mediapipe+ mp_sk_x = mediaPipe_skel_fr_mar_dim[fr,:,0] #skeleton x data+ mp_sk_y = mediaPipe_skel_fr_mar_dim[fr,:,1] #skeleton y data+ mp_sk_z = mediaPipe_skel_fr_mar_dim[fr,:,2] #skeleton z data+ axMain.scatter3D(mp_sk_x, mp_sk_y, mp_sk_z, marker='.',color = 'g', s=8.)++ #plot deeplabcut++ dlc_x = dlc_fr_mar_dim[fr,:,0]+ dlc_y = dlc_fr_mar_dim[fr,:,1]+ dlc_z = dlc_fr_mar_dim[fr,:,2]++ axMain.scatter3D(dlc_x,dlc_y,dlc_z, marker='o',color = 'r', s=24.)+#plot charuco gridaxMain.scatter(char_x,char_y,char_z, marker='o')# #plot camera positions (I think...)# for camNum in range(len(session.cgroup.cameras)):# axMain.scatter(session.cgroup.cameras[camNum].tvec[0], session.cgroup.cameras[camNum].tvec[1], session.cgroup.cameras[camNum].tvec[2], marker = 'p')+ axRange = session.board.square_length*10+ mx = np.nanmean(char_x)+ my = np.nanmean(char_y)+ mz = np.nanmean(char_z)++ axMain.set_xlim(mx-axRange,mx+axRange)+ axMain.set_ylim(my-axRange,my+axRange)+ axMain.set_zlim(mz-axRange,mz+axRange)axMain.set_xlabel('x')axMain.set_ylabel('y')axMain.set_zlabel('z')- axMain.set_xlim(-100,100)- axMain.set_ylim(-100,100)- axMain.set_zlim(100,300)+if vidType ==0:passdiff --git a/freemocap/reconstruct3D.py b/freemocap/reconstruct3D.pyindex cc45155e..9edadceb 100644--- a/freemocap/reconstruct3D.py+++ b/freemocap/reconstruct3D.py@@ -1,23 +1,36 @@-from freemocap import stolenfromanipose+from freemocap import fmc_anipose+import numpy as np-def reconstruct3D(session, data_nCams_nFrames_nImgPts_XY,data_params):+def reconstruct3D(session, data_nCams_nFrames_nImgPts_XYC, confidenceThreshold = .3):if session.cgroup is None: #load the calibration settings into the session class if it hasn't been alreadycalibrationFile = '{}_calibration.yaml'.format(session.sessionID)session.cameraConfigFilePath = session.sessionPath/calibrationFile- session.cgroup = stolenfromanipose.CameraGroup.load(session.cameraConfigFilePath)+ session.cgroup = fmc_anipose.CameraGroup.load(session.cameraConfigFilePath)- n_cams, n_frames, n_trackedPoints = data_params++ nCams, nFrames, nImgPts, nDims = data_nCams_nFrames_nImgPts_XYC.shape++ if nDims == 3:++ data_nCams_nFrames_nImgPts_X = np.squeeze(data_nCams_nFrames_nImgPts_XYC[:,:,:,0].copy())+ data_nCams_nFrames_nImgPts_Y = np.squeeze(data_nCams_nFrames_nImgPts_XYC[:,:,:,1].copy())+ confidence = np.squeeze(data_nCams_nFrames_nImgPts_XYC[:,:,:,2].copy())- #assert numDims == 2, 'Problem with your data! Not enough dimensions'+ data_nCams_nFrames_nImgPts_X[confidence < confidenceThreshold] = np.nan #replace low confidence points with 'nan'+ data_nCams_nFrames_nImgPts_Y[confidence < confidenceThreshold] = np.nan+ data_nCams_nFrames_nImgPts_XY =np.stack((data_nCams_nFrames_nImgPts_X, data_nCams_nFrames_nImgPts_Y), axis=3)++ if nDims == 2:+ data_nCams_nFrames_nImgPts_XY = data_nCams_nFrames_nImgPts_XYC- dataFlat_nCams_nTotalPoints_XY = data_nCams_nFrames_nImgPts_XY.reshape(n_cams, -1, 2) #reshape data to collapse across 'frames' so it becomes [numCams, numFrames*numPoints, XY]+ dataFlat_nCams_nTotalPoints_XY = data_nCams_nFrames_nImgPts_XY.reshape(nCams, -1, 2) #reshape data to collapse across 'frames' so it becomes [numCams, numFrames*numPoints, XY]data3d_flat = session.cgroup.triangulate(dataFlat_nCams_nTotalPoints_XY, progress=True)dataReprojerr_flat = session.cgroup.reprojection_error(data3d_flat, dataFlat_nCams_nTotalPoints_XY, mean=True)##return:- data_fr_mar_dim = data3d_flat.reshape(n_frames, n_trackedPoints, 3)- dataReprojErr_fr_mar_err = dataReprojerr_flat.reshape(n_frames, n_trackedPoints)+ data_fr_mar_dim = data3d_flat.reshape(nFrames, nImgPts, 3)+ dataReprojErr_fr_mar_err = dataReprojerr_flat.reshape(nFrames, nImgPts)return data_fr_mar_dimdiff --git a/freemocap/recordingconfig.py b/freemocap/recordingconfig.pyindex a7bdfd85..74d0645d 100644--- a/freemocap/recordingconfig.py+++ b/freemocap/recordingconfig.py@@ -33,12 +33,16 @@ def createSession(session,filepath, existing_data = False):session.calVidPath = session.sessionPath/'CalVideos'session.calVidPath.mkdir(exist_ok = True)pathList.append(session.calVidPath)-- session.mediaPipeDataPath = session.sessionPath/'OpenPoseData'++ session.openPoseDataPath = session.sessionPath/'OpenPoseData'+ session.openPoseDataPath.mkdir(exist_ok = True)+ pathList.append(session.mediaPipeDataPath)++ session.mediaPipeDataPath = session.sessionPath/'MediaPipeData'session.mediaPipeDataPath.mkdir(exist_ok = True)pathList.append(session.mediaPipeDataPath)- session.dlcDataPath = session.sessionPath / 'DLCdata' / 'videos'+ session.dlcDataPath = session.sessionPath / 'DLCdata'session.dlcDataPath.mkdir(exist_ok = True, parents = True)pathList.append(session.dlcDataPath)@@ -127,6 +131,7 @@ def load_session_paths(session,config_settings):session.syncedVidPath = Path(configPaths['syncedVidPath'])session.calVidPath = Path(configPaths['calVidPath'])session.mediaPipeDataPath = Path(configPaths['mediaPipeDataPath'])+ session.openPoseDataPath = Path(configPaths['openPoseDataPath'])session.dlcDataPath = Path(configPaths['dlcDataPath'])session.imOutPath = Path(configPaths['imOutPath'])session.dataArrayPath = Path(configPaths['dataArrayPath'])diff --git a/freemocap/runmediapipe.py b/freemocap/runmediapipe.pydeleted file mode 100644index e9b12ba7..00000000--- a/freemocap/runmediapipe.py+++ /dev/null@@ -1,145 +0,0 @@-import os-from pathlib import Path-import glob-import json--import numpy as np-from rich.progress import track-from ruamel.yaml import YAML-import cv2-import h5py-import mediapipe as mp-from pathlib import Path-mp_drawing = mp.solutions.drawing_utils-mp_holistic = mp.solutions.holistic--def runMediaPipe(session, dummyRun=False):-- mediaPipe_jsonPathList = [] #list to hold the paths to the json files- mediaPipe_imgPathList = []- mediaPipe_imgPathList_yaml = []- mediaPipe_jsonPathList_yaml = []-- with mp_holistic.Holistic() as holistic:- eachCamerasData = [] #Create an empty list that holds each cameras data- for thisVidPath in session.syncedVidPath.iterdir(): #Run MediaPipe 'Holistic' (body, hands, face) tracker on each video in the raw video folder- if thisVidPath.suffix =='.mp4': #NOTE - at some point we should build some list of 'synced video names' and check against that- print('MediaPiping: ', thisVidPath.name )- vidPath = session.mediaPipeDataPath / thisVidPath.stem- jsonPath = vidPath / 'json'- jsonPath.mkdir(parents=True, exist_ok=True) #this camera's json files (with keypoints)- imgPath = vidPath / 'images'- imgPath.mkdir(parents=True, exist_ok=True)- mediaPipe_jsonPathList.append(jsonPath)- mediaPipe_imgPathList.append(imgPath)- mediaPipe_imgPathList_yaml.append(str(imgPath))- mediaPipe_jsonPathList_yaml.append(str(jsonPath))- mediaPipe_dataList = [] #Create an empty list for mediapipes data- if not dummyRun:- cap = cv2.VideoCapture(str(thisVidPath))- frameNum = -1- success, image = cap.read() #load first image from video- while success:- frameNum += 1- image_height, image_width, _ = image.shape-- results = holistic.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) # THIS IS WHERE THE MAGIC HAPENS (ps. Convert the BGR image to RGB before processing.)- mediaPipe_dataList.append(results)#Append data to mediapipe data list-- # Draw pose, left and right hands, and face landmarks on the image.- annotated_image = image.copy()- mp_drawing.draw_landmarks(- annotated_image, results.face_landmarks, mp_holistic.FACE_CONNECTIONS)- mp_drawing.draw_landmarks(- annotated_image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS)- mp_drawing.draw_landmarks(- annotated_image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS)- mp_drawing.draw_landmarks(- annotated_image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS)-- #save annotated image- frameName = str(frameNum).zfill(6)-- cv2.imwrite(str(imgPath)+ '/' + frameName + '.png', annotated_image)-- #load the next image (will break `while-loop` on the last frame)- success, image = cap.read()#load next image from video- f=9- eachCamerasData.append(mediaPipe_dataList)#Append that cameras data for every frame to the camera datalist--- session.mediaPipe_jsonPathList = mediaPipe_jsonPathList- session.mediaPipe_imgPathList = mediaPipe_imgPathList-- yaml = YAML()- data = yaml.load(session.yamlPath)- data['mediaPipe_imgPathList'] = mediaPipe_imgPathList_yaml- data['mediaPipe_jsonPathList'] = mediaPipe_jsonPathList_yaml- yaml.dump(data, session.yamlPath)- session.mediaPipeData = eachCamerasData---def parseMediaPipe(session):- numCams = len(session.mediaPipeData) #Get number of cameras- numFrames = len(session.mediaPipeData[0]) #Get number of frames- #numBodyPoints = len(np.max(session.mediaPipeData[0][:].pose_landmarks.landmark[:]))#Get number of body points- #numFacePoints = len(np.max(session.mediaPipeData[0][:].face_landmarks.landmark[:]))#Get number of face points- #numLeftHandPoints = len(np.max(session.mediaPipeData[0][:].left_hand_landmarks.landmark[:]))#Get number of right hand points- #numRightHandPoints = len(np.max(session.mediaPipeData[0][:].right_hand_landmarks.landmark[:]))#Get number of left hand points- numBodyPoints = 33- numFacePoints = 468- numLeftHandPoints = 21- numRightHandPoints = 21-- numPoints = numBodyPoints+numFacePoints+numLeftHandPoints+numRightHandPoints #Get total points- mediaPipe_nCams_nFrames_nImgPts_XYC = np.ndarray((int(numCams),int(numFrames),int(numPoints),3)) #Create empty array the size of number of cams, frame, points, XYC- for nn in range(numCams):#Loop through each camera- for ii in range(numFrames): #Loop through each frame- for jj in range(numBodyPoints):- if session.mediaPipeData[0][ii].pose_landmarks is None: #If that point is not detected- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,0] = np.nan #Add nan value to that index- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,1] = np.nan #Add nan value to that index- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,2] = np.nan #Add nan value to that index- else:- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,0] = session.mediaPipeData[0][ii].pose_landmarks.landmark[jj].x#Take x pos of that point- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,1] = session.mediaPipeData[0][ii].pose_landmarks.landmark[jj].y#Take y pos of that point- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj,2] = session.mediaPipeData[0][ii].pose_landmarks.landmark[jj].visibility#Take visibility(confidence) pos of that point- for jj in range(numFacePoints):- if session.mediaPipeData[0][ii].face_landmarks is None: #If that point is not detected- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,0] = np.nan #Add nan value to that index- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,1] = np.nan #Add nan value to that index- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,2] = np.nan #Add nan value to that index- else:- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,0] = session.mediaPipeData[0][ii].face_landmarks.landmark[jj].x#Take x pos of that point- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,1] = session.mediaPipeData[0][ii].face_landmarks.landmark[jj].y#Take y pos of that point- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints,2] = session.mediaPipeData[0][ii].face_landmarks.landmark[jj].visibility#Take visibility(confidence) pos of that point- for jj in range(numRightHandPoints):- if session.mediaPipeData[0][ii].right_hand_landmarks is None: #If that point is not detected- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,0] = np.nan #Add nan value to that index- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,1] = np.nan #Add nan value to that index- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,2] = np.nan #Add nan value to that index- else:- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,0] = session.mediaPipeData[0][ii].right_hand_landmarks.landmark[jj].x#Take x pos of that point- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,1] = session.mediaPipeData[0][ii].right_hand_landmarks.landmark[jj].y#Take y pos of that point- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints,2] = session.mediaPipeData[0][ii].right_hand_landmarks.landmark[jj].visibility#Take visibility(confidence) pos of that point- for jj in range(numLeftHandPoints):- if session.mediaPipeData[0][ii].left_hand_landmarks is None: #If that point is not detected- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,0] = np.nan #Add nan value to that index- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,1] = np.nan #Add nan value to that index- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,2] = np.nan #Add nan value to that index- else:- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,0] = session.mediaPipeData[0][ii].left_hand_landmarks.landmark[jj].x#Take x pos of that point- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,1] = session.mediaPipeData[0][ii].left_hand_landmarks.landmark[jj].y#Take y pos of that point- mediaPipe_nCams_nFrames_nImgPts_XYC[nn,ii,jj+numBodyPoints+numFacePoints+numRightHandPoints,2] = session.mediaPipeData[0][ii].left_hand_landmarks.landmark[jj].visibility#Take visibility(confidence) pos of that point- #print(session.mediaPipe_datalist[0].pose_landmarks.landmark[0].x)-- path_to_mediapipe_2d = session.dataArrayPath/'mediaPipeData_nCams_nFrames_nImgPts_XY.npy'-- mediaPipeData_nCams_nFrames_nImgPts_XY = mediaPipe_nCams_nFrames_nImgPts_XYC[:,:,:,0:2].copy()- np.save(path_to_mediapipe_2d, mediaPipeData_nCams_nFrames_nImgPts_XY)------ return mediaPipeData_nCams_nFrames_nImgPts_XY\ No newline at end of filediff --git a/freemocap/session.py b/freemocap/session.pyindex 0ffe4476..ec7b4754 100644--- a/freemocap/session.py+++ b/freemocap/session.py@@ -1,12 +1,10 @@class Session: #session like "recording session"- def __init__(self, useOpenPose, useDLC):+ def __init__(self):self.sessionID = '' #The sessionID tag will be used to generate files names and whatnotself.sessionPath = '' #The folder where the to-be-processed videos live (in a folder called "synced Vids")self.numCams = ''#The number of cameras used in this recording sessionself.openPoseDataPath = ''#Where the open pose data livesself.dlcDataPath = ''#Where the DLC data lives- self.useOpenPose = useOpenPose- self.useDLC = useDLCself.openPoseExePath = r'C:\openpose'self.cam_inputs = Nonediff --git a/runme_fmc_staged.py b/runme_fmc_staged.pyindex a2847339..577c719b 100644--- a/runme_fmc_staged.py+++ b/runme_fmc_staged.py@@ -1,4 +1,4 @@-from freemocap import createvideo, initialization, runcams, calibrate, runmediapipe, reconstruct3D, playskeleton, session+from freemocap import createvideo, initialization, runcams, calibrate, fmc_mediapipe, fmc_openpose, fmc_deeplabcut, reconstruct3D, playskeleton, sessionfrom pathlib import Pathimport os@@ -7,15 +7,24 @@ from aniposelib.boards import CharucoBoard, Checkerboardimport numpy as np+sesh = session.Session()+++useOpenPose= True+useMediaPipe = True+useDLC=True++if useDLC:+ import deeplabcut as dlc+ sesh.dlcConfigPath = Path("C:\\Users\\jonma\\Dropbox\\GitKrakenRepos\\freemocap\\DLC_Models\\PinkGreenRedJugglingBalls-JSM-2021-05-31\\config.yaml")-sesh = session.Session(useOpenPose=True,useDLC=False)# %% Inputs to edit-stage = 1 #set your starting stage here (stage = 1 will run the pipeline from webcams)-sesh.debug = True+stage = 7 #set your starting stage here (stage = 1 will run the pipeline from webcams)+sesh.debug = False-sesh.sessionID = '' #fill in if you are running from Stage 2 onwards+sesh.sessionID = 'sesh_21-05-31_111833' #fill in if you are running from Stage 2 onwardsif not sesh.sessionID:dataFolder = Path.cwd()/'Data'subfolders = [ f.path for f in os.scandir(dataFolder) if f.is_dir() ] #copy-pasta from who knows where@@ -24,8 +33,8 @@ if not sesh.sessionID: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,- square_length = 7,- marker_length = 6.8,+ square_length = 121,+ marker_length = 96,marker_bits=4, dict_size=250)@@ -39,7 +48,7 @@ board = CharucoBoard(7, 5,initialization.initialize(sesh,stage,board)# %% Stage One-if not stage > 1:+if stage <= 1:print()print('Starting Video Recordings')runcams.RecordCams(sesh, sesh.cam_inputs, sesh.parameterDictionary, sesh.rotationInputs)@@ -48,7 +57,7 @@ else:# %% Stage Two-if not stage > 2:+if stage <= 2:print()print('Starting Video Syncing')runcams.SyncCams(sesh, sesh.timeStampData,sesh.numCamRange,sesh.vidNames,sesh.camIDs)@@ -56,7 +65,7 @@ else:print('Skipping Video Syncing')# %% Stage Three-if not stage > 3:+if stage <= 3:print()print('Starting Calibration')sesh.cgroup, sesh.mean_charuco_fr_mar_dim = calibrate.CalibrateCaptureVolume(sesh,board)@@ -64,43 +73,72 @@ else:print('Skipping Calibration')# %% Stage Four-if not stage > 4:- print()- print('Starting Run MediaPipe')- runmediapipe.runMediaPipe(sesh)+if stage <= 4:+ print('Starting Track Image Points')+ if useMediaPipe:+ fmc_mediapipe.runMediaPipe(sesh)+ sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC = fmc_mediapipe.parseMediaPipe(sesh)+ sesh.mediaPipeSkel_fr_mar_dim = reconstruct3D.reconstruct3D(sesh,sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=.1)+ np.save(sesh.dataArrayPath/'mediaPipeSkel_3d.npy', sesh.mediaPipeSkel_fr_mar_dim) #save data to npy++ if useOpenPose:+ fmc_openpose.runOpenPose(sesh, dummyRun=False)+ sesh.openPoseData_nCams_nFrames_nImgPts_XYC = fmc_openpose.parseOpenPose(sesh)+ sesh.openPoseskel_fr_mar_dim = reconstruct3D.reconstruct3D(sesh,sesh.openPoseData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=.1)+ np.save(sesh.dataArrayPath/'openPoseSkel_3d.npy', sesh.openPoseskel_fr_mar_dim) #save data to npy++ if useDLC:+ syncedVidList = []+ for vid in sesh.syncedVidPath.glob('*.mp4'):+ syncedVidList.append(str(vid))++ dlc.analyze_videos(sesh.dlcConfigPath,syncedVidList, destfolder= sesh.dlcDataPath, save_as_csv=True)+ sesh.dlcData_nCams_nFrames_nImgPts_XYC = fmc_deeplabcut.parseDeepLabCut(sesh)+ sesh.dlc_fr_mar_dim = reconstruct3D.reconstruct3D(sesh,sesh.dlcData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=.95)+ np.save(sesh.dataArrayPath/'deepLabCut_3d.npy', sesh.dlc_fr_mar_dim) #save data to npy+else:print('Skipping Run MediaPipe')-# %% Stage Five-if not stage > 5:- print()- print('Starting Parse MediaPipe')- sesh.mediaPipeData_nCams_nFrames_nImgPts_XY = runmediapipe.parseMediaPipe(sesh)-else:- print('Skipping Parse MediaPipe')+# # %% Stage Five+# if not stage > 5:+# print('Starting Parse MediaPipe')+# sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC = fmc_mediapipe.parseMediaPipe(sesh)+# else:+# print('Skipping Parse MediaPipe')-# %% Stage Six-if not stage > 6:- print()- print('Starting Skeleton Reconstruction')- mediaPipe_params = sesh.mediaPipeData_nCams_nFrames_nImgPts_XY.shape[0:3]- sesh.skel_fr_mar_dim = reconstruct3D.reconstruct3D(sesh,sesh.mediaPipeData_nCams_nFrames_nImgPts_XY, mediaPipe_params)- path_to_skel_points = sesh.dataArrayPath/'skeleton_points.npy'- np.save(path_to_skel_points, sesh.skel_fr_mar_dim)-else:- print('Skipping Skeleton Reconstruction')++# # %% Stage Six+# if not stage > 6:+# print()+# print('Starting Skeleton Reconstruction')+# sesh.skel_fr_mar_dim = reconstruct3D.reconstruct3D(sesh,sesh.mediaPipeData_nCams_nFrames_nImgPts_XYC, confidenceThreshold=.1)++# path_to_skel_points = sesh.dataArrayPath/'skeleton_points.npy'+# np.save(path_to_skel_points, sesh.skel_fr_mar_dim)+# else:+# print('Skipping Skeleton Reconstruction')++# %% Stage Seven-if not stage > 7:- print()+if stage <= 7:print('Starting Skeleton Plotting')- playskeleton.ReplaySkeleton(sesh,1,40,-90,-75)+ playskeleton.ReplaySkeleton(+ sesh,+ vidType=1,+ startFrame=40,+ azimuth=-90,+ elevation=-80,+ useOpenPose=useOpenPose,+ useMediaPipe=useMediaPipe,+ useDLC=useDLC)else:print('Skipping Skeleton Plotting')# %% Stage Eight-if not stage > 8:+if stage <= 8:print()print('Starting Video Creation')createvideo.createVideo(sesh)