Free Motion Capture for Everyone πβ¨
TypeScript
Updating skeleton animation code
jon matthis3c5a0b0bcc01
diff --git a/charuco_board_image_highRes.png b/charuco_board_image_highRes.pngnew file mode 100644index 00000000..9bbc05d2Binary files /dev/null and b/charuco_board_image_highRes.png differdiff --git a/freemocap/dev_scratchpad/__init__.py b/freemocap/dev_scratchpad/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/freemocap/dev_scratchpad/playSkeletonAnimation.py b/freemocap/dev_scratchpad/playSkeletonAnimation.pydeleted file mode 100644index cca022c5..00000000--- a/freemocap/dev_scratchpad/playSkeletonAnimation.py+++ /dev/null@@ -1,124 +0,0 @@-"""-============-3D animation-============--An animated plot in 3D.-from - https://matplotlib.org/2.1.2/gallery/animation/simple_3danim.html-"""-import numpy as np-import matplotlib.pyplot as plt-import mpl_toolkits.mplot3d.axes3d as p3-import matplotlib.animation as animation-from matplotlib.widgets import Slider--#RICH CONSOLE STUFF-from rich import pretty-pretty.install() #makes all print statement output pretty-from rich import inspect-from rich.console import Console-console = Console()-from rich.traceback import install as rich_traceback_install-from rich.markdown import Markdown-rich_traceback_install()--def main():- # Fixing random state for reproducibility- np.random.seed(19680801)---- def Gen_RandLine(length, dims=2):- """- Create a line using a random walk algorithm-- length is the number of points for the line.- dims is the number of dimensions the line has.- """- lineData = np.empty((dims, length))- lineData[:, 0] = np.random.rand(dims)*1e2- for index in range(1, length):- # scaling the random numbers by 0.1 so- # movement is small compared to position.- # subtraction by 0.5 is to change the range to [-0.5, 0.5]- # to allow a line to move backwards.- step = ((np.random.rand(dims) - 0.5) * 1e2)- lineData[:, index] = lineData[:, index - 1] + step*2-- return lineData--- def update_figure(frameNum, dataLines, plotting_data, skel_trajectories):- print(frameNum)-- skel_dottos = plotting_data['skel_dottos']- # for line, dotto, skel_dotto, data, skelTraj in zip(lines,dottos, skel_dottos, dataLines, skel_trajectories):- for thisSkelDotto, thisTraj in zip(skel_dottos,skel_trajectories):- # NOTE: there is no .set_data() for 3 dim data...- # line.set_data(data[0:2, frameNum-4:frameNum])- # line.set_3d_properties(data[2, frameNum-4:frameNum])-- thisSkelDotto.set_data(thisTraj[ frameNum-1, 0:2])- thisSkelDotto.set_3d_properties(thisTraj[ frameNum-1, 2])-- animSlider.set_val(val=frameNum)-- # Attaching 3D axis to the figure- fig = plt.figure()- plt.ion()- plt.show()-- ax3d = p3.Axes3D(fig)- ax3d.set_position([.1, .1, .8, .8]) # [left, bottom, width, height])-- skel_fr_mar_dim = np.load(r"C:\Users\jonma\Dropbox\GitKrakenRepos\freemocap\Data\sesh_21-07-08_131030\DataArrays\openPoseSkel_3d.npy")- skel_trajectories = [skel_fr_mar_dim[:,markerNum,:] for markerNum in range(skel_fr_mar_dim.shape[1])]- numFrames = skel_fr_mar_dim.shape[0]--- # Fifty lines of random 3-D lines- data = [Gen_RandLine(numFrames, 3) for index in range(15)]-- # Creating fifty line objects.- # NOTE: Can't pass empty arrays into 3d version of plot()- plotting_data = dict()- # plotting_data['lines'] = [ax3d.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1],'bo')[0] for dat in data]- plotting_data['skel_dottos'] = [ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1],'ro')[0] for thisTraj in skel_trajectories]-- # Setting the axes properties- ax3d.set_xlim3d([-1e3, 1e3])- ax3d.set_xlabel('X')-- ax3d.set_ylim3d([-1e3, 1e3])- ax3d.set_ylabel('Y')-- ax3d.set_zlim3d([-1e3, 1e3])- ax3d.set_zlabel('Z')-- ax3d.set_title('3D Test')----- #slider- axControls = fig.add_subplot(2,1,2)- axControls.set_position([0.25, 0.01, 0.6, 0.05])- animSlider = Slider(- ax=axControls,- label="FrameNum",- valmin=10,- valmax=numFrames,- valinit=500,- orientation="horizontal"- )- # Creating the Animation object- line_animation = animation.FuncAnimation(fig, update_figure, range(200,numFrames), fargs=(data, plotting_data, skel_trajectories),- interval=1, blit=False)-- plt.draw()- plt.pause(.001) # pause a bit so that plots are updated-- console.print(":sparkle: :skull: :sparkle:")--if __name__ == '__main__':- main()\ No newline at end of filediff --git a/freemocap/dev_scratchpad/play_skeleton_animation.py b/freemocap/dev_scratchpad/play_skeleton_animation.pynew file mode 100644index 00000000..ba5a91ff--- /dev/null+++ b/freemocap/dev_scratchpad/play_skeleton_animation.py@@ -0,0 +1,239 @@++"""+============+3D animation+============++An animated plot in 3D.+from - https://matplotlib.org/2.1.2/gallery/animation/simple_3danim.html+"""+import numpy as np++import matplotlib.pyplot as plt+import mpl_toolkits.mplot3d.axes3d as p3+import matplotlib.animation as animation+from matplotlib.widgets import Slider++import copy++#RICH CONSOLE STUFF+from rich import pretty+pretty.install() #makes all print statement output pretty+from rich import inspect+from rich.console import Console+console = Console()+from rich.traceback import install as rich_traceback_install+from rich.markdown import Markdown++++def PlaySkeletonAnimation(+ session=None,+ vidType=1,+ startFrame=40,+ azimuth=-90,+ elevation=-80,+ useOpenPose=True,+ useMediaPipe=False,+ useDLC=False,+ ):++ def update_figure(frameNum):+ """+ Called by matplotlib animator for each frame.+ """++ skel_dottos = matplotlib_artist_objs['skel_dottos']+ skel_trajectories = figure_data['skel_trajectories|mar|fr_dim']++ body_segments = matplotlib_artist_objs['body']++ #function to update the lines for each body segment+ def update_skel_segments(key):+ """+ updates the Artist of each body segment with the current frame data.+ """+ dict_of_segments_idxs = dict_of_openPoseSegmentIdx_dicts[key]+ dict_of_artists = matplotlib_artist_objs[key]++ for thisItem in dict_of_segments_idxs.items():+ segName = thisItem[0]+ segArtist = dict_of_artists[segName]+ segArtist.set_data((skel_fr_mar_dim[frameNum-1, dict_of_segments_idxs[segName], 0], skel_fr_mar_dim[frameNum-1, dict_of_segments_idxs[segName], 1]))+ segArtist.set_3d_properties(skel_fr_mar_dim[frameNum-1, dict_of_segments_idxs[segName], 2])++ update_skel_segments('body')+ update_skel_segments('rHand')+ update_skel_segments('lHand')+ update_skel_segments('face')++ #Plots the dots!+ marNum = -1+ for thisSkelDotto, thisTraj in zip(skel_dottos,skel_trajectories):+ marNum+=1+ # NOTE: there is no .set_data() for 3 dim data...+ thisSkelDotto.set_data(thisTraj[ frameNum-1, 0:2])+ thisSkelDotto.set_3d_properties(thisTraj[ frameNum-1, 2])+++++ animSlider.set_val(val=frameNum)++ # Attaching 3D axis to the figure+ fig = plt.figure()+ plt.ion()++ ax3d = p3.Axes3D(fig)+ ax3d.set_position([.1, .1, .8, .8]) # [left, bottom, width, height])++++ skel_fr_mar_dim = np.load(r"C:\Users\jonma\Dropbox\GitKrakenRepos\freemocap\Data\sesh_21-07-08_131030\DataArrays\openPoseSkel_3d.npy")+ skel_trajectories = [skel_fr_mar_dim[:,markerNum,:] for markerNum in range(skel_fr_mar_dim.shape[1])]++ figure_data = dict()+ figure_data['skel_trajectories|mar|fr_dim'] = skel_trajectories+ figure_data['skel_fr_mar_dim'] = skel_fr_mar_dim+++++ dict_of_openPoseSegmentIdx_dicts = formatOpenPoseStickIndices() #these will help us draw body and hands stick figures++ def build_segment_artist_dict(dict_of_list_of_segment_idxs):+ """+ Builds a dictionary of line artists for each body segment.+ """+ segNames = list(dict_of_list_of_segment_idxs)++ dict_of_artist_objects = dict()+ for segName in segNames:+ dict_of_artist_objects[segName] = ax3d.plot(+ skel_fr_mar_dim[0,dict_of_list_of_segment_idxs[segName],0],+ skel_fr_mar_dim[0,dict_of_list_of_segment_idxs[segName],1],+ skel_fr_mar_dim[0,dict_of_list_of_segment_idxs[segName],2],+ 'k-'+ )[0]+ return dict_of_artist_objects++++ matplotlib_artist_objs = dict()+ matplotlib_artist_objs['body'] = build_segment_artist_dict(dict_of_openPoseSegmentIdx_dicts['body'])+ matplotlib_artist_objs['rHand'] = build_segment_artist_dict(dict_of_openPoseSegmentIdx_dicts['rHand'])+ matplotlib_artist_objs['lHand'] = build_segment_artist_dict(dict_of_openPoseSegmentIdx_dicts['lHand'])+ matplotlib_artist_objs['face'] = build_segment_artist_dict(dict_of_openPoseSegmentIdx_dicts['face'])++ matplotlib_artist_objs['skel_dottos'] = [ax3d.plot(thisTraj[0, 0:1], thisTraj[1, 0:1], thisTraj[2, 0:1],'r,')[0] for thisTraj in skel_trajectories]+ numFrames = skel_fr_mar_dim.shape[0]+++++ mx = np.nanmean(skel_fr_mar_dim[int(numFrames/2),:,0])+ my = np.nanmean(skel_fr_mar_dim[int(numFrames/2),:,1])+ mz = np.nanmean(skel_fr_mar_dim[int(numFrames/2),:,2])++ axRange = 800#session.board.square_length * 10++ # Setting the axes properties+ ax3d.set_xlim3d([mx-axRange, mx+axRange])+ ax3d.set_xlabel('X')++ ax3d.set_ylim3d([my-axRange, my+axRange])+ ax3d.set_ylabel('Y')++ ax3d.set_zlim3d([mz-axRange, mz+axRange])+ ax3d.set_zlabel('Z')++ ax3d.set_title('3D Test')++ ax3d.view_init(azim=azimuth, elev=elevation)++ #slider+ axControls = fig.add_subplot(2,1,2)+ axControls.set_position([0.25, 0.01, 0.6, 0.05])+ animSlider = Slider(+ ax=axControls,+ label="FrameNum",+ valmin=10,+ valmax=numFrames,+ valinit=10,+ orientation="horizontal"+ )+ # Creating the Animation object+ line_animation = animation.FuncAnimation(fig, update_figure, range(200,numFrames), fargs=(),+ interval=1, blit=False)++ plt.draw()+ plt.pause(.001) # pause a bit so that plots are updated++ console.print(":sparkle: :skull: :sparkle:")+++def formatOpenPoseStickIndices():+ """+ generate dictionary of arrays, each containing the 'connect-the-dots' order to draw a given body segment++ returns:+ openPoseBodySegmentIds= a dictionary of arrays containing indices of individual body segments (Note, a lot of markerless mocap comp sci types like to say 'pose' instead of 'body'. They also use 'pose' to refer to camera 6 DoF position sometimes. Comp sci is frustrating like that lol)+ openPoseHandIds = a dictionary of arrays containing indices of individual hand segments, along with offset to know where to start in the 'skel_fr_mar_dim.shape[1]' part of the array+ """+ dict_of_openPoseSegmentIdx_dicts = dict()++ #make body dictionary+ openPoseBodySegmentIds = dict()+ openPoseBodySegmentIds['head'] = [17, 15, 0, 16, 18, ]+ openPoseBodySegmentIds['spine'] = [0,1,8,5,1, 2, 12, 8, 9, 5, 1, 2, 8]+ openPoseBodySegmentIds['rArm'] = [1, 2, 3, 4, ]+ openPoseBodySegmentIds['lArm'] = [1, 5, 6, 7, ]+ openPoseBodySegmentIds['rLeg'] = [8, 9, 10, 11, 22, 23, 11, 24, ]+ openPoseBodySegmentIds['lLeg'] = [8,12, 13, 14, 19, 20, 14, 21,]+ dict_of_openPoseSegmentIdx_dicts['body'] = openPoseBodySegmentIds++ # Make some handy maps ;D+ openPoseHandIds = dict()+ rHandIDstart = 25+ lHandIDstart = rHandIDstart + 21++ openPoseHandIds['thumb'] = np.array([0, 1, 2, 3, 4, ])+ openPoseHandIds['index'] = np.array([0, 5, 6, 7, 8, ])+ openPoseHandIds['bird']= np.array([0, 9, 10, 11, 12, ])+ openPoseHandIds['ring']= np.array([0, 13, 14, 15, 16, ])+ openPoseHandIds['pinky'] = np.array([0, 17, 18, 19, 20, ])++ rHand_dict = copy.deepcopy(openPoseHandIds.copy()) #copy.deepcopy() is necessary to make sure the dicts are independent of each other+ lHand_dict = copy.deepcopy(rHand_dict)++ for key in rHand_dict:+ rHand_dict[key] += rHandIDstart+ lHand_dict[key] += lHandIDstart++ dict_of_openPoseSegmentIdx_dicts['rHand'] = rHand_dict+ dict_of_openPoseSegmentIdx_dicts['lHand'] = lHand_dict++ #how to face --> :D <--+ openPoseFaceIDs = dict()+ faceIDStart = 67+ #define face parts+ openPoseFaceIDs['jaw'] = np.arange(0,16) + faceIDStart+ openPoseFaceIDs['rBrow'] = np.arange(17,21) + faceIDStart+ openPoseFaceIDs['lBrow'] = np.arange(22,26) + faceIDStart+ openPoseFaceIDs['noseRidge'] = np.arange(27,30) + faceIDStart+ openPoseFaceIDs['noseBot'] = np.arange(31,35) + faceIDStart+ openPoseFaceIDs['rEye'] = np.concatenate((np.arange(36,41), [36])) + faceIDStart+ openPoseFaceIDs['lEye'] = np.concatenate((np.arange(42,47), [42])) + faceIDStart+ openPoseFaceIDs['upperLip'] = np.concatenate((np.arange(48,54), np.flip(np.arange(60, 64)), [48])) + faceIDStart+ openPoseFaceIDs['lowerLip'] = np.concatenate(([60], np.arange(64,67), np.arange(54, 59), [48], [60])) + faceIDStart+ openPoseFaceIDs['rPupil'] = np.array([68]) + faceIDStart+ openPoseFaceIDs['lPupil'] = np.array([69]) + faceIDStart #nice++ dict_of_openPoseSegmentIdx_dicts['face'] = openPoseFaceIDs++ return dict_of_openPoseSegmentIdx_dicts++++if __name__ == '__main__':+ PlaySkeletonAnimation()diff --git a/freemocap/fmc_runme.py b/freemocap/fmc_runme.pyindex ebe4ba61..691b766c 100644--- a/freemocap/fmc_runme.py+++ b/freemocap/fmc_runme.py@@ -11,6 +11,7 @@ from freemocap import (session,webcamGUI)+from freemocap.fmc_pyqtgraph import PlayerDockedWindowfrom pathlib import Path@@ -32,19 +33,19 @@ def Run(sessionID=None,stage=1,useOpenPose=True, openPoseDummyRun = False, useMe- if sesh.useDLC:+ if sesh.useDLC:import deeplabcut as dlcsesh.dlcConfigPath =dlcConfigPath# sesh.dlcConfigPath = Path("C:\\Users\\jonma\\Dropbox\\GitKrakenRepos\\freemocap\\DLC_Models\\PinkGreenRedJugglingBalls-JSM-2021-05-31\\config.yaml")#sesh.dlcConfigPath = Path("C:\\Users\\jonma\\Desktop\\freemocap\\DLC_Models\\PinkGreenRedJugglingBalls-JSM-2021-05-31\\config.yaml")dataFolder = Path.cwd()/'Data'- if dataFolder.exists() and not sesh.sessionID:- subfolders = [f.path for f in os.scandir(dataFolder) 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+ if dataFolder.exists():+ if not sesh.sessionID: #if user has not provided a sessionID, use the most recent session+ subfolders = [f.path for f in os.scandir(dataFolder) 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 subfolderselse: #First time run! Make 'FreeMoCap_Data' Folder (and eventually, prompt to download sample data)dataFolder.mkdir()- sampleDataFolder.mkdir()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`)@@ -165,15 +166,26 @@ def Run(sessionID=None,stage=1,useOpenPose=True, openPoseDummyRun = False, useMe# %% Stage Sevenif stage <= 7:print('Starting Skeleton Plotting')- playskeleton.ReplaySkeleton_matplotlib(- sesh,- vidType=1,- startFrame=40,- azimuth=-90,- elevation=-80,- useOpenPose=sesh.useOpenPose,- useMediaPipe=sesh.useMediaPipe,- useDLC=sesh.useDLC)++ PlaySkeletonAnimation(+ sesh,+ vidType=1,+ startFrame=40,+ azimuth=-90,+ elevation=-80,+ useOpenPose=sesh.useOpenPose,+ useMediaPipe=sesh.useMediaPipe,+ useDLC=sesh.useDLC)++ # playskeleton.ReplaySkeleton_matplotlib(+ # sesh,+ # vidType=1,+ # startFrame=40,+ # azimuth=-90,+ # elevation=-80,+ # useOpenPose=sesh.useOpenPose,+ # useMediaPipe=sesh.useMediaPipe,+ # useDLC=sesh.useDLC)# fmc_pyqtgraph.PlaySkeleton(# sesh,# vidType=1,diff --git a/freemocap/playskeleton.py b/freemocap/playskeleton.pyindex 704f1008..cdacadfa 100644--- a/freemocap/playskeleton.py+++ b/freemocap/playskeleton.py@@ -90,13 +90,27 @@ def ReplaySkeleton_matplotlib(pinky = np.array([0, 17, 18, 19, 20])fig = plt.figure(figsize=(11, 8))-++ vidCapObj_list = []if vidType == 0: #no videosaxMain = fig.add_subplot(111, projection="3d")elif vidType == 1: #one videonumCamSubPlots = 1axMain = fig.add_subplot(121, projection="3d")axCam1 = fig.add_subplot(122)+ vidCapObj_list.append(cv2.VideoCapture(str(syncedVidPathList[1]))) #open the video file for cam 1++ elif vidType == 2: #four video+ figGridSpec = fig.add_gridspec(2,4)+ axMain = fig.add_subplot(figGridSpec[:2,:2],projection='3d')+ axCam1 = fig.add_subplot(figGridSpec[0,2])+ axCam2 = fig.add_subplot(figGridSpec[0,3])+ axCam3 = fig.add_subplot(figGridSpec[1,2])+ axCam4 = fig.add_subplot(figGridSpec[1,3])+ vidCapObj_list.append(cv2.VideoCapture(str(syncedVidPathList[1]))) #open the video file for cam 1+ vidCapObj_list.append(cv2.VideoCapture(str(syncedVidPathList[3])))+ vidCapObj_list.append(cv2.VideoCapture(str(syncedVidPathList[4])))+ vidCapObj_list.append(cv2.VideoCapture(str(syncedVidPathList[6])))#make a list of video capture objects to load images from as needed for later plotfor camNum in range(numCamSubPlots):@@ -132,7 +146,14 @@ def ReplaySkeleton_matplotlib(sk_z = skel_fr_mar_dim[fr, :, 2] # skeleton z dataaxMain.scatter3D(sk_x, sk_y, sk_z, marker=".", color="k", s=4.0)- axMain.plot(sk_x[head], sk_y[head], sk_z[head], linestyle="-", color="g", linewidth=1.0)++ axMain.plot(+ sk_x[head],+ sk_y[head],+ sk_z[head],+ linestyle="-",+ color="g",+ linewidth=1.0)axMain.plot(sk_x[spine],@@ -143,17 +164,26 @@ def ReplaySkeleton_matplotlib(linewidth=1.0,)axMain.plot(- sk_x[rArm], sk_y[rArm], sk_z[rArm], linestyle="-", color="r", linewidth=1.0- )- axMain.plot(- sk_x[lArm], sk_y[lArm], sk_z[lArm], linestyle="-", color="b", linewidth=1.0- )- axMain.plot(- sk_x[rLeg], sk_y[rLeg], sk_z[rLeg], linestyle="-", color="r", linewidth=1.0- )+ sk_x[rArm],+ sk_y[rArm],+ sk_z[rArm],+ linestyle="-",+ color="r",+ linewidth=1.0+ )+axMain.plot(- sk_x[lLeg], sk_y[lLeg], sk_z[lLeg], linestyle="-", color="b", linewidth=1.0- )+ sk_x[lArm],+ sk_y[lArm],+ sk_z[lArm],+ linestyle="-",+ color="b",+ linewidth=1.0)++ axMain.plot(sk_x[rLeg], sk_y[rLeg], sk_z[rLeg], linestyle="-", color="r", linewidth=1.0)++ axMain.plot(sk_x[lLeg], sk_y[lLeg], sk_z[lLeg], linestyle="-", color="b", linewidth=1.0)+axMain.plot(sk_x[rFoot],sk_y[rFoot],@@ -255,6 +285,7 @@ def ReplaySkeleton_matplotlib(color="b",linewidth=1.0,)+if useMediaPipe:# plot mediapipemp_sk_x = mediaPipe_skel_fr_mar_dim[fr, :, 0] # skeleton x data@@ -311,4 +342,4 @@ def ReplaySkeleton_matplotlib(frameName = str(fr).zfill(6)saveFrameName = "{}.png".format(frameName)saveFramePath = session.imOutPath / saveFrameName- fig.savefig(saveFramePath)+ fig.savefig(saveFramePath)\ No newline at end of filediff --git a/freemocap_runme_script.py b/freemocap_runme_script.pyindex 04ac8938..6d2f52c9 100644--- a/freemocap_runme_script.py+++ b/freemocap_runme_script.py@@ -2,4 +2,4 @@ import freemocap as fmcfrom pathlib import PathdlcConfigPath = Path(r"C:\Users\jonma\Dropbox\DLC_Models\PinkGreenRedJugglingBalls-JSM-2021-05-31\config.yaml")-fmc.RunMe(stage=4, openPoseDummyRun=True, dlcConfigPath=dlcConfigPath)\ No newline at end of file+fmc.RunMe(sessionID = 'sesh_21-07-08_131030', stage=7, openPoseDummyRun=True, useDLC = False, dlcConfigPath=dlcConfigPath)\ No newline at end of file