-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathutilsSync.py
More file actions
1935 lines (1656 loc) · 85.7 KB
/
utilsSync.py
File metadata and controls
1935 lines (1656 loc) · 85.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import cv2
import logging
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import pchip_interpolate
from scipy.ndimage import gaussian_filter1d
from scipy.signal import butter, gaussian, find_peaks, sosfiltfilt
from scipy import signal
import scipy.linalg
from utils import (getOpenPoseMarkerNames, getOpenPoseFaceMarkers,
delete_multiple_element)
from utilsChecker import (loadPklVideo, unpackKeypointList,
keypointsToBoundingBox, calcReprojectionError,
triangulateMultiviewVideo)
from utilsCameraPy3 import Camera
from defaults import DEFAULT_SYNC_VER
# %%
def synchronizeVideos(CameraDirectories, trialRelativePath, pathPoseDetector,
undistortPoints=False, CamParamDict=None,
confidenceThreshold=0.3,
filtFreqs={'gait':12,'default':30},
imageBasedTracker=False, cams2Use=['all'],
poseDetector='OpenPose', trialName=None, bbox_thr=0.8,
resolutionPoseDetection='default',
visualizeKeypointAnimation=False,
syncVer=DEFAULT_SYNC_VER):
markerNames = getOpenPoseMarkerNames()
# Create list of cameras.
if cams2Use[0] == 'all':
cameras2Use = list(CameraDirectories.keys())
else:
cameras2Use = cams2Use
cameras2Use_in = copy.deepcopy(cameras2Use)
# Initialize output lists
pointList = []
confList = []
CameraDirectories_selectedCams = {}
CamParamList_selectedCams = []
for cam in cameras2Use:
CameraDirectories_selectedCams[cam] = CameraDirectories[cam]
CamParamList_selectedCams.append(CamParamDict[cam])
# Load data.
camsToExclude = []
for camName in CameraDirectories_selectedCams:
cameraDirectory = CameraDirectories_selectedCams[camName]
videoFullPath = os.path.normpath(os.path.join(cameraDirectory,
trialRelativePath))
trialPrefix, _ = os.path.splitext(
os.path.basename(trialRelativePath))
if poseDetector == 'OpenPose':
outputPklFolder = "OutputPkl_" + resolutionPoseDetection
elif poseDetector == 'mmpose':
outputPklFolder = "OutputPkl_mmpose_" + str(bbox_thr)
openposePklDir = os.path.join(outputPklFolder, trialName)
pathOutputPkl = os.path.join(cameraDirectory, openposePklDir)
ppPklPath = os.path.join(pathOutputPkl, trialPrefix+'_rotated_pp.pkl')
key2D, confidence = loadPklVideo(
ppPklPath, videoFullPath, imageBasedTracker=imageBasedTracker,
poseDetector=poseDetector,confidenceThresholdForBB=0.3)
thisVideo = cv2.VideoCapture(videoFullPath.replace('.mov', '_rotated.avi'))
frameRate = np.round(thisVideo.get(cv2.CAP_PROP_FPS))
if key2D.shape[1] == 0 and confidence.shape[1] == 0:
camsToExclude.append(camName)
else:
pointList.append(key2D)
confList.append(confidence)
# If video is not existing, the corresponding camera should be removed.
idx_camToExclude = []
for camToExclude in camsToExclude:
cameras2Use.remove(camToExclude)
CameraDirectories_selectedCams.pop(camToExclude)
idx_camToExclude.append(cameras2Use_in.index(camToExclude))
# By removing the cameras in CamParamDict and CameraDirectories, we
# modify those dicts in main, which is needed for the next stages.
CamParamDict.pop(camToExclude)
CameraDirectories.pop(camToExclude)
delete_multiple_element(CamParamList_selectedCams, idx_camToExclude)
# Creates a web animation for each camera's keypoints. For debugging.
if visualizeKeypointAnimation:
import plotly.express as px
import plotly.io as pio
pio.renderers.default = 'browser'
for i,data in enumerate(pointList):
nPoints,nFrames,_ = data.shape
# Reshape the 3D numpy array to 2D, preserving point and frame indices
data_reshaped = np.copy(data).reshape(-1, 2)
# Create DataFrame
df = pd.DataFrame(data_reshaped, columns=['x', 'y'])
# Add columns for point number and frame number
df['Point'] = np.repeat(np.arange(nPoints), nFrames)
df['Frame'] = np.tile(np.arange(nFrames), nPoints)
# Reorder columns if needed
df = df[['Point', 'Frame', 'x', 'y']]
# Create a figure and add an animated scatter plot
fig = px.scatter(df,x='x', y='y', title="Cam " + str(i),
animation_frame='Frame',
range_x=[0, 1200], range_y=[1200,0],
color='Point', color_continuous_scale=px.colors.sequential.Viridis)
# Show the animation
fig.show()
# Synchronize keypoints.
pointList, confList, nansInOutList,startEndFrameList = synchronizeVideoKeypoints(
pointList, confList, confidenceThreshold=confidenceThreshold,
filtFreqs=filtFreqs, sampleFreq=frameRate, visualize=False,
maxShiftSteps=2*frameRate, CameraParams=CamParamList_selectedCams,
cameras2Use=cameras2Use,
CameraDirectories=CameraDirectories_selectedCams, trialName=trialName,
syncVer=syncVer)
if undistortPoints:
if CamParamList_selectedCams is None:
raise Exception('Need to have CamParamList to undistort Images')
# nFrames = pointList[0].shape[1]
unpackedPoints = unpackKeypointList(pointList) ;
undistortedPoints = []
for points in unpackedPoints:
undistortedPoints.append(undistort2Dkeypoints(
points, CamParamList_selectedCams, useIntrinsicMatAsP=True))
pointList = repackKeypointList(undistortedPoints)
pointDir = {}
confDir = {}
nansInOutDir = {}
startEndFrames = {}
for iCam, camName in enumerate(CameraDirectories_selectedCams):
pointDir[camName] = pointList[iCam]
confDir[camName] = confList[iCam]
nansInOutDir[camName] = nansInOutList[iCam]
startEndFrames[camName] = startEndFrameList[iCam]
return pointDir, confDir, markerNames, frameRate, nansInOutDir, startEndFrames, cameras2Use
# %%
def synchronizeVideoKeypoints(keypointList, confidenceList,
confidenceThreshold=0.3,
filtFreqs = {'gait':12,'default':500},
sampleFreq=30, visualize=False, maxShiftSteps=30,
isGait=False, CameraParams = None,
cameras2Use=['none'],CameraDirectories = None,
trialName=None, trialID='',
syncVer=DEFAULT_SYNC_VER):
visualize2Dkeypoint = False # this is a visualization just for testing what filtered input data looks like
# keypointList is a mCamera length list of (nmkrs,nTimesteps,2) arrays of camera 2D keypoints
logging.info(f'Synchronizing Keypoints using version {syncVer}')
# Deep copies such that the inputs do not get modified.
c_CameraParams = copy.deepcopy(CameraParams)
c_cameras2Use = copy.deepcopy(cameras2Use)
c_CameraDirectoryDict = copy.deepcopy(CameraDirectories)
# Turn Camera Dict into List
c_CameraDirectories = list(c_CameraDirectoryDict.values())
# Check if one camera has only 0s as confidence scores, which would mean
# no one has been properly identified. We want to kick out this camera
# from the synchronization and triangulation. We do that by popping out
# the corresponding data before syncing and add back 0s later.
badCameras = []
for icam, conf in enumerate(confidenceList):
if np.max(conf) == 0.0:
badCameras.append(icam)
idxBadCameras = [badCameras[i]-i for i in range(len(badCameras))]
cameras2NotUse = []
for idxBadCamera in idxBadCameras:
print('{} kicked out of synchronization'.format(
c_cameras2Use[idxBadCamera]))
cameras2NotUse.append(c_cameras2Use[idxBadCamera])
keypointList.pop(idxBadCamera)
confidenceList.pop(idxBadCamera)
c_CameraParams.pop(idxBadCamera)
c_cameras2Use.pop(idxBadCamera)
c_CameraDirectories.pop(idxBadCamera)
markerNames = getOpenPoseMarkerNames()
mkrDict = {mkr:iMkr for iMkr,mkr in enumerate(markerNames)}
# First, remove occluded markers
footMkrs = {'right':[mkrDict['RBigToe'], mkrDict['RSmallToe'], mkrDict['RHeel'],mkrDict['RAnkle']],
'left':[mkrDict['LBigToe'], mkrDict['LSmallToe'], mkrDict['LHeel'],mkrDict['LAnkle']]}
armMkrs = {'right':[mkrDict['RElbow'], mkrDict['RWrist']],
'left':[mkrDict['LElbow'], mkrDict['LWrist']]}
plt.close('all')
# Copy for visualization
keypointListUnfilt = copy.deepcopy(keypointList)
# remove occluded foot markers (uses large differences in confidence)
keypointList,confidenceList = zip(*[removeOccludedSide(keys,conf,footMkrs,confidenceThreshold,visualize=False) for keys,conf in zip(keypointList,confidenceList)])
# remove occluded arm markers
keypointList,confidenceList = zip(*[removeOccludedSide(keys,conf,armMkrs,confidenceThreshold,visualize=False) for keys,conf in zip(keypointList,confidenceList)])
# Copy for visualization
keypointListOcclusionRemoved = copy.deepcopy(keypointList)
# Don't change these. The ankle markers are used for gait detector
markers4VertVel = [mkrDict['RAnkle'], mkrDict['LAnkle']] # R&L Ankles and Heels did best. There are some issues though - like when foot marker velocity is aligned with camera ray
markers4HandPunch = [mkrDict['RWrist'], mkrDict['LWrist'],mkrDict['RShoulder'],mkrDict['LShoulder']]
markers4Ankles = [mkrDict['RAnkle'],mkrDict['LAnkle']]
# find velocity signals for synchronization
nCams = len(keypointList)
vertVelList = []
mkrSpeedList = []
inHandPunchVertPositionList = []
inHandPunchConfidenceList = []
allMarkerList = []
for (keyRaw,conf) in zip(keypointList,confidenceList):
keyRaw_clean, _, _, _ = clean2Dkeypoints(keyRaw,conf,confidenceThreshold=0.3,nCams=nCams,linearInterp=True)
keyRaw_clean_smooth = smoothKeypoints(keyRaw_clean, sdKernel=3)
inHandPunchVertPositionList.append(getPositions(keyRaw_clean_smooth,markers4HandPunch,direction=1))
inHandPunchConfidenceList.append(conf[markers4HandPunch])
vertVelList.append(getVertVelocity(keyRaw_clean_smooth)) # doing it again b/c these settings work well for synchronization
mkrSpeedList.append(getMarkerSpeed(keyRaw_clean_smooth,markers4VertVel,confidence=conf,averageVels=False)) # doing it again b/c these settings work well for synchronization
allMarkerList.append(keyRaw_clean_smooth)
# Prepare hand punch data
# Clip the end of the hand punch data to the shortest length of the hand punch data
min_hand_frames = min(np.shape(p)[1] for p in inHandPunchVertPositionList)
inHandPunchVertPositionList = [p[:, :min_hand_frames] for p in inHandPunchVertPositionList]
inHandPunchConfidenceList = [c[:, :min_hand_frames] for c in inHandPunchConfidenceList]
# For sync 1.1, we keep the original input (inHandPunchVertPositionList)
# but make a copy that is clipped after checks below (for sync 1.0)
clippedHandPunchVertPositionList = copy.deepcopy(inHandPunchVertPositionList)
clippedHandPunchConfidenceList = copy.deepcopy(inHandPunchConfidenceList)
# Prepare data for syncing without hand punch
# Find indices with high confidence that overlap between cameras with
# ankle markers.
# Note: Could get creative and do camera pair syncing in the future, based
# on cameras with greatest amount of overlapping confidence.
overlapInds_clean, minConfLength_all = findOverlap(confidenceList,
markers4VertVel)
# If no overlap found, try with fewer cameras.
c_nCams = len(confidenceList)
while not np.any(overlapInds_clean) and c_nCams>2:
print("Could not find overlap with {} cameras - trying with {} cameras".format(c_nCams, c_nCams-1))
cam_list = [i for i in range(nCams)]
# All possible combination with c_nCams-1 cameras.
from itertools import combinations
combs = set(combinations(cam_list, c_nCams-1))
overlapInds_clean_combs = []
for comb in combs:
confidenceList_sel = [confidenceList[i] for i in list(comb)]
overlapInds_clean_c, minConfLength_c = findOverlap(
confidenceList_sel, markers4VertVel)
overlapInds_clean_combs.append(overlapInds_clean_c.flatten())
longest_stretch = 0
for overlapInds_clean_comb in overlapInds_clean_combs:
stretch_size = overlapInds_clean_comb.shape[0]
if stretch_size > longest_stretch:
longest_stretch = stretch_size
overlapInds_clean = overlapInds_clean_comb
c_nCams -= 1
# If no overlap found, return 0s.
if not np.any(overlapInds_clean):
keypointsSync = []
confidenceSync = []
nansInOutSync = []
for i in range(len(cameras2Use)):
keypointsSync.insert(i, np.zeros((keypointList[0].shape[0], 10,
keypointList[0].shape[2])))
confidenceSync.insert(i, np.zeros((keypointList[0].shape[0], 10)))
nansInOutSync.insert(i, np.array([np.nan, np.nan]))
return keypointsSync, confidenceSync, nansInOutSync
[idxStart, idxEnd] = [np.min(overlapInds_clean), np.max(overlapInds_clean)]
idxEnd += 1 # Python indexing system.
# Take max shift between cameras into account.
idxStart = int(np.max([0,idxStart - maxShiftSteps]))
idxEnd = int(np.min([idxEnd+maxShiftSteps,minConfLength_all]))
# Re-sample the lists
vertVelList = [v[idxStart:idxEnd] for v in vertVelList]
mkrSpeedList = [v[:,idxStart:idxEnd] for v in mkrSpeedList]
clippedHandPunchVertPositionList = [p[:,idxStart:idxEnd] for p in clippedHandPunchVertPositionList]
clippedHandPunchConfidenceList = [c[:,idxStart:idxEnd] for c in clippedHandPunchConfidenceList]
allMarkerList = [p[:,idxStart:idxEnd] for p in allMarkerList]
confSyncList= [c[:,idxStart:idxEnd] for c in confidenceList]
# We do this again, since it might have changed after finding the overlap period.
keypointList = list(keypointList)
confidenceList = list(confidenceList)
badCamerasOverlap = []
for icam, conf in enumerate(confSyncList):
if np.mean(conf) <= 0.01: # Looser than sum=0 to disregard very few frames with data
badCamerasOverlap.append(icam)
idxbadCamerasOverlap = [badCamerasOverlap[i]-i for i in range(len(badCamerasOverlap))]
for idxbadCameraOverlap in idxbadCamerasOverlap:
print('{} kicked out of synchronization - after overlap check'.format(
c_cameras2Use[idxbadCameraOverlap]))
cameras2NotUse.append(c_cameras2Use[idxbadCameraOverlap])
keypointList.pop(idxbadCameraOverlap)
confidenceList.pop(idxbadCameraOverlap)
c_CameraParams.pop(idxbadCameraOverlap)
c_cameras2Use.pop(idxbadCameraOverlap)
c_CameraDirectories.pop(idxbadCameraOverlap)
vertVelList.pop(idxbadCameraOverlap)
mkrSpeedList.pop(idxbadCameraOverlap)
clippedHandPunchVertPositionList.pop(idxbadCameraOverlap)
clippedHandPunchConfidenceList.pop(idxbadCameraOverlap)
inHandPunchVertPositionList.pop(idxbadCameraOverlap)
inHandPunchConfidenceList.pop(idxbadCameraOverlap)
allMarkerList.pop(idxbadCameraOverlap)
confSyncList.pop(idxbadCameraOverlap)
nCams = len(keypointList)
# Detect activities, which determines sync function and filtering
# that gets used
# Gait trial: Input right and left ankle marker speeds. Gait should be
# detected for all cameras (all but one camera is > 2 cameras) for the
# trial to be considered a gait trial.
try:
isGait = detectGaitAllVideos(mkrSpeedList,allMarkerList,confSyncList,markers4Ankles,sampleFreq)
except:
isGait = False
print('Detect gait activity algorithm failed.')
# Hand punch: Input right and left wrist and shoulder positions.
# Different sync versions use different input data, handled by
# dispatcher function detectHandPunchAllVideos.
isHandPunch, handForPunch, handPunchRange = \
detectHandPunchAllVideos(syncVer,
clippedHandPunchVertPositionList=clippedHandPunchVertPositionList,
clippedHandPunchConfidenceList=clippedHandPunchConfidenceList,
inHandPunchVertPositionList=inHandPunchVertPositionList,
inHandPunchConfidenceList=inHandPunchConfidenceList,
sampleFreq=sampleFreq,
)
if isHandPunch:
syncActivity = 'handPunch'
elif isGait:
syncActivity = 'gait'
else:
syncActivity = 'general'
logging.info(f'Using {syncActivity} sync function.')
# Select filtering frequency based on if it is gait
if isGait:
filtFreq = filtFreqs['gait']
else:
filtFreq = filtFreqs['default']
# Filter keypoint data
# sdKernel = sampleFreq/(2*np.pi*filtFreq) # not currently used, but in case using gaussian smoother (smoothKeypoints function) instead of butterworth to filter keypoints
keyFiltList = []
confFiltList = []
confSyncFiltList = []
nansInOutList = []
for (keyRaw,conf) in zip(keypointList,confidenceList):
keyRaw_clean, conf_clean, nans_in_out, conf_sync_clean = clean2Dkeypoints(keyRaw,conf,confidenceThreshold,nCams=nCams)
keyRaw_clean_filt = filterKeypointsButterworth(keyRaw_clean,filtFreq,sampleFreq,order=4)
keyFiltList.append(keyRaw_clean_filt)
confFiltList.append(conf_clean)
confSyncFiltList.append(conf_sync_clean)
nansInOutList.append(nans_in_out)
# Copy for visualization
keypointListFilt = copy.deepcopy(keyFiltList)
confidenceListFilt = copy.deepcopy(confFiltList)
confidenceSyncListFilt = copy.deepcopy(confSyncFiltList)
# find nSample shift relative to the first camera
# nSamps = keypointList[0].shape[1]
shiftVals = []
shiftVals.append(0)
timeVecs = []
tStartEndVec = np.zeros((len(keypointList),2))
for iCam,vertVel in enumerate(vertVelList):
timeVecs.append(np.arange(keypointList[iCam].shape[1]))
if iCam>0:
# if no keypoints in Cam0 or the camera of interest, do not use cross_corr to sync.
if np.max(np.abs(vertVelList[iCam])) == 0 or np.max(np.abs(vertVelList[0])) == 0:
lag = 0
elif syncActivity == 'general':
dataForReproj = {'CamParamList':c_CameraParams,
'keypointList':keypointListFilt,
'cams2UseReproj': [0, c_cameras2Use.index(c_cameras2Use[iCam])],
'confidence': confidenceSyncListFilt,
'cameras2Use': c_cameras2Use
}
corVal,lag = cross_corr(vertVel,vertVelList[0],multCorrGaussianStd=maxShiftSteps/2,
visualize=False,dataForReproj=dataForReproj,
frameRate=sampleFreq) # gaussian curve gets multipled by correlation plot - helping choose the smallest shift value for periodic motions
elif syncActivity == 'gait':
dataForReproj = {'CamParamList':c_CameraParams,
'keypointList':keypointListFilt,
'cams2UseReproj': [0, c_cameras2Use.index(c_cameras2Use[iCam])],
'confidence': confidenceSyncListFilt,
'cameras2Use': c_cameras2Use
}
corVal,lag = cross_corr_multiple_timeseries(mkrSpeedList[iCam],
mkrSpeedList[0],
multCorrGaussianStd=maxShiftSteps/2,
dataForReproj=dataForReproj,
visualize=False,
frameRate=sampleFreq)
elif syncActivity == 'handPunch':
corVal,lag = syncHandPunch(syncVer,
clippedHandPunchVertPositionList=[clippedHandPunchVertPositionList[i] for i in [0,iCam]],
inHandPunchVertPositionList=[inHandPunchVertPositionList[i] for i in [0,iCam]],
clippedHandPunchConfidenceList=[clippedHandPunchConfidenceList[i] for i in [0,iCam]],
inHandPunchConfidenceList=[inHandPunchConfidenceList[i] for i in [0,iCam]],
handForPunch=handForPunch,
maxShiftSteps=maxShiftSteps,
handPunchRange=handPunchRange,
frameRate=sampleFreq,
)
if np.abs(lag) > maxShiftSteps: # if this fails and we get a lag greater than maxShiftSteps (units=timesteps)
lag = 0
print('Did not use cross correlation to sync {} - computed shift was greater than specified {} frames. Shift set to 0.'.format(c_cameras2Use[iCam], maxShiftSteps))
shiftVals.append(lag)
timeVecs[iCam] = timeVecs[iCam] - shiftVals[iCam]
tStartEndVec[iCam,:] = [timeVecs[iCam][0], timeVecs[iCam][-1]]
# align signals - will start at the latest-starting frame (most negative shift) and end at
# nFrames - the end of the earliest starting frame (nFrames - max shift)
tStart = np.max(tStartEndVec[:,0])
tEnd = np.min(tStartEndVec[:,1])
keypointsSync = []
confidenceSync = []
startEndFrames = []
nansInOutSync = []
for iCam,key in enumerate(keyFiltList):
# Trim the keypoints and confidence lists
confidence = confFiltList[iCam]
iStart = int(np.argwhere(timeVecs[iCam]==tStart))
iEnd = int(np.argwhere(timeVecs[iCam]==tEnd))
keypointsSync.append(key[:,iStart:iEnd+1,:])
confidenceSync.append(confidence[:,iStart:iEnd+1])
if shiftVals[iCam] > 0:
shiftednNansInOut = nansInOutList[iCam] - shiftVals[iCam]
else:
shiftednNansInOut = nansInOutList[iCam]
nansInOutSync.append(shiftednNansInOut)
# Save start and end frames to list, so can rewrite videos in
# triangulateMultiviewVideo
startEndFrames.append([iStart,iEnd])
# Plot synchronized velocity curves
if visualize:
# Vert Velocity
f, (ax0,ax1) = plt.subplots(1,2)
for (timeVec,vertVel) in zip(timeVecs,vertVelList):
ax0.plot(timeVec[range(len(vertVel))],vertVel)
legNames = [c_cameras2Use[iCam] for iCam in range(len(vertVelList))]
ax0.legend(legNames)
ax0.set_title('summed vertical velocities')
# Marker speed
for (timeVec,mkrSpeed) in zip(timeVecs,mkrSpeedList):
ax1.plot(timeVec[range(len(vertVel))],mkrSpeed[2])
legNames = [c_cameras2Use[iCam] for iCam in range(len(vertVelList))]
ax1.legend(legNames)
ax1.set_title('Right Ankle Speed')
# Plot a single marker trajectory to see effect of filtering and occlusion removal
if visualize2Dkeypoint:
nCams = len(keypointListFilt)
nCols = int(np.ceil(nCams/2))
mkr = mkrDict['RBigToe']
mkrXY = 0 # x=0, y=1
fig = plt.figure()
fig.set_size_inches(12,7,forward=True)
for camNum in range(nCams):
ax = plt.subplot(2,nCols,camNum+1)
ax.set_title(c_cameras2Use[iCam])
ax.set_ylabel('yPos (pixel)')
ax.set_xlabel('frame')
ax.plot(keypointListUnfilt[camNum][mkr,:,mkrXY],linewidth = 2)
ax.plot(keypointListOcclusionRemoved[camNum][mkr,:,mkrXY],linewidth=1.6)
ax.plot(keypointListFilt[camNum][mkr,:,mkrXY],linewidth=1.3)
# find indices where conf> thresh or nan (the marker is used in triangulation)
usedInds = np.argwhere(np.logical_or(confidenceListFilt[camNum][mkr,:] > confidenceThreshold ,
np.isnan(confidenceListFilt[camNum][mkr,:])))
if len(usedInds) > 0:
ax.plot(usedInds,keypointListFilt[camNum][mkr,usedInds,mkrXY],linewidth=1)
ax.set_ylim((.9*np.min(keypointListFilt[camNum][mkr,usedInds,mkrXY]),1.1*np.max(keypointListFilt[camNum][mkr,usedInds,mkrXY])))
else:
ax.text(0.5,0.5,'no data used',horizontalalignment='center',transform=ax.transAxes)
plt.tight_layout()
ax.legend(['unfilt','occlusionRemoved','filt','used for triang'],bbox_to_anchor=(1.05,1))
# We need to add back the cameras that have been kicked out.
# We just add back zeros, they will be kicked out of the triangulation.
idxCameras2NotUse = [cameras2Use.index(cam) for cam in cameras2NotUse]
for idxCamera2NotUse in idxCameras2NotUse:
keypointsSync.insert(idxCamera2NotUse, np.zeros(keypointsSync[0].shape))
confidenceSync.insert(idxCamera2NotUse, np.zeros(confidenceSync[0].shape))
nansInOutSync.insert(idxCamera2NotUse, np.array([np.nan, np.nan]))
startEndFrames.insert(idxCamera2NotUse, None)
return keypointsSync, confidenceSync, nansInOutSync, startEndFrames
# %%
def removeOccludedSide(key2D,confidence,mkrInds,confThresh,visualize=False):
key2D_out = np.copy(key2D)
confidence_out = np.copy(confidence)
#Parameters
confDif = .2 # the difference in mean confidence between R and L sided markers. If dif > confDif, must be occluded
rMkrs = mkrInds['right']
lMkrs = mkrInds['left']
# nan confidences should be turned to 0 at this point...not sure why I used a nanmean
rConf = np.nanmean(confidence_out[rMkrs,:],axis=0)
lConf = np.nanmean(confidence_out[lMkrs,:],axis=0)
dConf = rConf-lConf
if visualize:
plt.figure()
plt.plot(rConf,color='r')
plt.plot(lConf,color='k')
plt.plot(dConf,color=(.5,.5,.5))
plt.legend(['rightConfidence','leftConfidence','dConf'])
plt.xlabel('frame')
plt.ylabel('mean confidence')
rOccluded = np.where(np.logical_and(np.less(dConf,confDif) , np.less(rConf,confThresh)))[0]
lOccluded = np.where(np.logical_and(np.greater(dConf,confDif) , np.less(lConf,confThresh)))[0]
# if inleading and exiting values are in occluded list, don't change them
def zeroPad(occInds,nSamps):
# Default: not setting confidence of any indices to 0
zeroInds = np.empty([0],dtype=np.int64)
if len(occInds) == 0:
return occInds,zeroInds
# find gaps
dInds = np.diff(occInds,prepend=1)
#all first vals
if occInds[0] == 0:
#special case - occlusion starts at beginning but there are no gaps afterwards
if not any(dInds>1):
zeroInds = np.concatenate((zeroInds, np.copy(occInds)))
occInds = []
return occInds, zeroInds
else:
# otherwise, remove in-leading indices
firstGap = np.argwhere(dInds>1)[0]
occInds = np.delete(occInds,np.arange(firstGap))
dInds = np.delete(dInds,np.arange(firstGap))
zeroInds = np.concatenate((zeroInds, np.arange(firstGap)))
#all end vals
if occInds[-1] == nSamps-1:
#special case - occlusion goes to end but there are no gaps beforehand
if not any(dInds>1):
zeroInds = np.concatenate((zeroInds, np.copy(occInds)))
occInds = []
else:
# otherwise, remove end zeros
lastGap = np.argwhere(dInds>1)[-1]
occInds_init = np.copy(occInds)
occInds = np.delete(occInds,np.arange(lastGap,len(occInds)))
zeroInds = np.concatenate((zeroInds, np.arange(occInds_init[lastGap[0]],occInds_init[-1]+1)))
return occInds, zeroInds
nSamps = len(rConf)
# Assumes that occlusion can't happen starting in first frame or ending in last frame. Looks for first "gap"
rOccluded,rZeros = zeroPad(rOccluded,nSamps)
lOccluded,lZeros = zeroPad(lOccluded,nSamps)
# Couldn't figure out how to index multidimensions...
# Set occlusion confidences to nan. Later, the keypoints with associated nan confidence will be cubic splines,
# and the confidence will get set to something like 0.5 for weighted triangulation in utilsCameraPy3
for mkr in lMkrs:
if np.count_nonzero(confidence_out[mkr,:]>0)>3:
lNan = np.intersect1d(lOccluded,np.arange(np.argwhere(confidence_out[mkr,:]>0)[1],np.argwhere(confidence_out[mkr,:]>0)[-1])) # don't add nans to 0 pad
else:
lNan = np.array([],dtype='int64')
key2D_out[mkr,lNan.astype(int),:] = np.nan
confidence_out[mkr,lNan.astype(int)] = np.nan
confidence_out[mkr,lZeros] = 0
for mkr in rMkrs:
if np.count_nonzero(confidence_out[mkr,:]>0)>3:
rNan = np.intersect1d(rOccluded,np.arange(np.argwhere(confidence_out[mkr,:]>0)[1],np.argwhere(confidence_out[mkr,:]>0)[-1])) # don't add nans to 0 pad
else:
rNan = np.array([],dtype='int64')
key2D_out[mkr,rNan.astype(int),:] = np.nan
confidence_out[mkr,rNan.astype(int)] = np.nan
confidence_out[mkr,rZeros] = 0
if visualize:
# TESTING
rConf = np.nanmean(confidence_out[rMkrs,:],axis=0)
lConf = np.nanmean(confidence_out[lMkrs,:],axis=0)
dConf = rConf-lConf
plt.figure()
plt.plot(rConf,color='r')
plt.plot(lConf,color='k')
plt.plot(dConf,color=(.5,.5,.5))
plt.legend(['rightFootConfidence','leftFootConfidence','dConf'])
plt.xlabel('frame')
plt.ylabel('mean confidence')
return key2D_out, confidence_out
# %%
def clean2Dkeypoints(key2D, confidence, confidenceThreshold=0.5, nCams=2,
linearInterp=False):
key2D_out = np.copy(key2D)
confidence_out = np.copy(confidence)
confidence_sync_out = np.copy(confidence)
nMkrs = key2D_out.shape[0]
markerNames = getOpenPoseMarkerNames()
# Turn all 0s into nans.
key2D_out[key2D_out==0] = np.nan
# Turn low confidence values to 0s if >2 cameras and nans otherwise.
for i in range(nMkrs):
# If a marker has at least two frames with positive confidence,
# then identify frames where confidence is lower than threshold.
if len(np.argwhere(confidence_out[i,:]>0))>2:
nanInds = np.where(confidence_out[i,:] < confidenceThreshold)
# If a marker doesn't have two frames with positive confidence,
# then return empty list.
else:
nanInds = []
faceMarkers = getOpenPoseFaceMarkers()[0]
# no warning if face marker
if not markerNames[i] in faceMarkers:
print('There were <2 frames with >0 confidence for {}'.format(
markerNames[i]))
# Turn low confidence values to 0s if >2 cameras.
# Frames with confidence values of 0s are ignored during triangulation.
if nCams>2:
confidence_out[i,nanInds] = 0
# Turn low confidence values to nans if 2 cameras.
# Frames with nan confidence values are splined, and nan confidences
# are replaced by 0.5 during triangulation.
else:
confidence_out[i,nanInds] = np.nan
# Turn inleading and exiting nans into 0s
idx_nonnans = ~np.isnan(confidence_out[i,:])
idx_nonzeros = confidence_out[i,:] != 0
idx_nonnanszeros = idx_nonnans & idx_nonzeros
if True in idx_nonnanszeros:
idx_nonnanszeros_first = np.where(idx_nonnanszeros)[0][0]
idx_nonnanszeros_last = np.where(idx_nonnanszeros)[0][-1]
confidence_out[i,:idx_nonnanszeros_first] = 0
confidence_out[i,idx_nonnanszeros_last:] = 0
else:
confidence_out[i,:] = 0
# Turn low confidence values to 0s for confidence_sync_out whatever
# the number of cameras; confidence_sync_out is used for
# calculating the reprojection error, and using nans rather than
# 0s might affect the outcome.
confidence_sync_out[i,nanInds] = 0
# Turn inleading and exiting nans into 0s
idx_nonnans = ~np.isnan(confidence_sync_out[i,:])
idx_nonzeros = confidence_sync_out[i,:] != 0
idx_nonnanszeros = idx_nonnans & idx_nonzeros
if True in idx_nonnanszeros:
idx_nonnanszeros_first = np.where(idx_nonnanszeros)[0][0]
idx_nonnanszeros_last = np.where(idx_nonnanszeros)[0][-1]
confidence_sync_out[i,:idx_nonnanszeros_first] = 0
confidence_sync_out[i,idx_nonnanszeros_last:] = 0
else:
confidence_sync_out[i,:] = 0
# Turn keypoint values to nan if confidence is low. Keypoints with nan
# will be interpolated. In cases with more than 2 cameras, this will
# have no impact on triangulation, since corresponding confidence is 0.
# But with 2 cameras, we need the keypoint 2D coordinates to
# be interpolated. In both cases, not relying on garbage keypoints for
# interpolation matters when computing keypoint speeds, which are used
# for synchronization.
key2D_out[i,nanInds,:] = np.nan
# Helper function.
def nan_helper(y):
return np.isnan(y), lambda z: z.nonzero()[0]
# Interpolate keypoints with nans.
for i in range(nMkrs):
for j in range(2):
if np.isnan(key2D_out[i,:,j]).all(): # only nans
key2D_out[i,:,j] = 0
elif np.isnan(key2D_out[i,:,j]).any(): # partially nans
nans, x = nan_helper(key2D_out[i,:,j])
if linearInterp:
# Note: with linear interpolation, values are carried over
# backward and forward for inleading and exiting nans.
key2D_out[i,nans,j] = np.interp(x(nans), x(~nans),
key2D_out[i,~nans,j])
else:
# Note: with cubic interpolate, values are garbage for
# inleading and exiting nans.
try:
key2D_out[i,:,j] = pchip_interpolate(
x(~nans), key2D_out[i,~nans,j],
np.arange(key2D_out.shape[1]))
except:
key2D_out[i,nans,j] = np.interp(x(nans), x(~nans),
key2D_out[i,~nans,j])
# Keep track of inleading and exiting nans when less than 3 cameras.
if nCams>2:
nans_in_out = np.array([np.nan, np.nan])
else:
_, idxFaceMarkers = getOpenPoseFaceMarkers()
nans_in = []
nans_out = []
for i in range(nMkrs):
if i not in idxFaceMarkers:
idx_nans = np.isnan(confidence_out[i,:])
if False in idx_nans:
nans_in.append(np.where(idx_nans==False)[0][0])
nans_out.append(np.where(idx_nans==False)[0][-1])
else:
nans_in.append(np.nan)
nans_out.append(np.nan)
in_max = np.max(np.asarray(nans_in))
out_min = np.min(np.asarray(nans_out))
nans_in_out = np.array([in_max, out_min])
return key2D_out, confidence_out, nans_in_out, confidence_sync_out
# %% Find indices with high confidence that overlap between cameras.
def findOverlap(confidenceList, markers4VertVel):
c_confidenceList = copy.deepcopy(confidenceList)
# Find overlapping indices.
confMean = [
np.mean(cMat[markers4VertVel,:],axis=0) for cMat in c_confidenceList]
minConfLength = np.min(np.array([len(x) for x in confMean]))
confArray = np.array([x[0:minConfLength] for x in confMean])
minConfidence = np.nanmin(confArray,axis=0)
confThresh = .5*np.nanmax(minConfidence)
overlapInds = np.asarray(np.where(minConfidence>confThresh))
# Find longest stretch of high confidence.
difOverlap = np.diff(overlapInds)
# Create array with last elements of continuous stretches
# (more than 2 timesteps between high confidence).
unConfidentInds = np.argwhere(np.squeeze(difOverlap)>4)
# Identify and select the longest continuous stretch.
if unConfidentInds.shape[0] > 0:
# First stretch (ie, between 0 and first unconfident index).
stretches = []
stretches.append(np.arange(0, unConfidentInds[0]+1))
# Middle stretches.
if unConfidentInds.shape[0] >1:
for otherStretch in range(unConfidentInds.shape[0]-1):
stretches.append(np.arange(unConfidentInds[otherStretch]+1,
unConfidentInds[otherStretch+1]+1))
# Last stretch (ie, between last unconfident index and last element).
stretches.append(np.arange(unConfidentInds[-1]+1,
overlapInds.shape[1]))
# Identify longest stretch.
longestStretch = stretches[
np.argmax([stretch.shape[0] for stretch in stretches])]
# Select longest stretch
overlapInds_clean = overlapInds[0,longestStretch]
else:
overlapInds_clean = overlapInds
return overlapInds_clean, minConfLength
# %%
def detectHandPunchAllVideos_v1(handPunchPositionList,sampleFreq,punchDurationThreshold=3):
isPunch = []
for pos in handPunchPositionList:
isPunchThisVid = []
relPosList = []
maxIndList = []
for iSide in range(2):
relPos = -np.diff(pos[(iSide, iSide+2),:],axis=0) # vertical position of wrist over shoulder
relPosList.append(relPos)
maxInd = np.argmax(relPos)
maxIndList.append(maxInd)
maxPos = relPos[:,maxInd]
isPunchThisVid.append(False)
if maxPos>0:
zeroCrossings = np.argwhere(np.diff(np.sign(np.squeeze(relPos))) != 0)
if any(zeroCrossings>maxInd) and any(zeroCrossings<maxInd):
startLength = np.abs(np.min([zeroCrossings-maxInd]))/sampleFreq
endLength = np.abs(np.min([-zeroCrossings+maxInd]))
if (startLength+endLength)/sampleFreq<punchDurationThreshold:
isPunchThisVid[-1] = True
# Ensure only one arm is punching
hand = None
isPunch.append(False)
if isPunchThisVid[0]:
if relPosList[1][:,maxIndList[0]] < 0:
isPunch[-1] = True
hand = 'r'
elif isPunchThisVid[1]:
if relPosList[0][:,maxIndList[1]] < 0:
isPunch[-1] = True
hand = 'l'
isTrialPunch = all(isPunch)
return isTrialPunch, hand
# %%
def detectHandPunchAllVideos_v2(handPunchPositionList, confList, sampleFreq,
punchDurationLimits=(0.2, 3.0), confThresh=0.5,
maxPosSimilarityThresh=0.5, maxConfGap=4):
"""
Detects a hand punch event across all cameras, determines which hand
(left or right) performed the punch, and finds the consensus frame
range of the punch event. Uses wrist-over-shoulder position signals
and confidence values.
Args:
handPunchPositionList (list of np.ndarray):
List of arrays (one per camera), each of shape (4, nFrames),
containing the vertical positions of the right wrist, left wrist,
right shoulder, and left shoulder over time.
Expected order: [r_wrist, l_wrist, r_shoulder, l_shoulder].
confList (list of np.ndarray):
List of arrays (one per camera), each of shape (4, nFrames),
containing the confidence values for the corresponding markers in
handPunchPositionList. Required for this function.
sampleFreq (float):
The sampling frequency (frames per second) of the video data.
punchDurationLimits (tuple, optional):
(min_duration, max_duration) in seconds for a punch event.
Default is (0.2, 3).
confThresh (float, optional):
Confidence threshold multiplier for determining high-confidence
stretches. Default is 0.5.
maxPosSimilarityThresh (float, optional):
Threshold for how similar two punch heights can be on the same arm
before the punch is considered ambiguous. Default is 0.5.
maxConfGap (int, optional):
Maximum allowed gap (in frames) of low confidence within a
high-confidence stretch. Default is 4.
Returns:
isTrialPunch (bool):
True if a valid punch is detected in all cameras and by the same
hand, False otherwise.
hand (str or None):
'r' if the right hand performed the punch, 'l' if the left hand,
or None if no valid punch is found.
handPunchRange (list or None):
[start_idx, end_idx] of the possible punch event (frame indices)
across all cameras, or None if no valid punch is found.
"""
if confList is None:
raise Exception('list of confidences need to be passed in to "conf"')
# all positions and confs should have the same number of markers and frames
if any(np.shape(p) != np.shape(handPunchPositionList[0]) for p in handPunchPositionList):
raise Exception('all positions should have the same number of markers')
if any(np.shape(c) != np.shape(handPunchPositionList[0]) for c in confList):
raise Exception('all confs should have the same number of frames')
punch_duration_min, punch_duration_max = punchDurationLimits
# Loop over each camera, adding cleanest possible punch event for each camera.
cam_punch_list = []
for pos, conf in zip(handPunchPositionList, confList):
valid_stretches = []
# Loop over each side, starting with right side of arrays in
# handPunchPositionList.
# Expected order: ['r_wrist', 'l_wrist', 'r_shoulder', 'l_shoulder']
for side, indices in zip(['r', 'l'], [
{'wrist': 0, 'shoulder': 2, 'other_wrist': 1, 'other_shoulder': 3},
{'wrist': 1, 'shoulder': 3, 'other_wrist': 0, 'other_shoulder': 2}
]):
# Find the highest relative position of the wrist over shoulder
relPos = np.diff(pos[(indices['shoulder'], indices['wrist']), :], axis=0).squeeze()
# Find all stretches when wrist is above shoulder
positiveInd = relPos > 0
starts = np.where((~positiveInd[:-1]) & (positiveInd[1:]))[0]
ends = np.where((positiveInd[:-1]) & (~positiveInd[1:]))[0] + 1
# Account for cases where hand starts or ends above shoulder
if positiveInd[0]:
starts = np.insert(starts, 0, 0)
if positiveInd[-1]:
ends = np.append(ends, len(relPos))
positiveStretches = list(zip(starts, ends))
# Ensure stretches are valid:
# 1. punch duration is within time limits
# 2. high confidence
# 3. other wrist is below other shoulder
for start, end in positiveStretches:
duration = (end - start) / sampleFreq
if duration < punch_duration_min or duration > punch_duration_max:
continue
# Require minimum confidence of wrist and shoulder to be
# above 'confThresh' of the maximum of the minimum confidence
# values.
# Gaps of 'maxConfGap' or fewer frames of low confidence are allowed.
conf_wrist = conf[indices['wrist']]
conf_shoulder = conf[indices['shoulder']]
high_conf_indices = \
find_longest_confidence_stretch_in_range_with_gaps(
[conf_wrist, conf_shoulder], confThresh, maxConfGap,
rangeList=[start, end])
# Check if the high confidence region covers the entire stretch
if (
high_conf_indices is None or
high_conf_indices[0] > start or
high_conf_indices[1] < end
):
continue
other_relPos = np.diff(pos[(indices['other_shoulder'], indices['other_wrist']), :], axis=0).squeeze()
other_relPos_stretch = other_relPos[start:end]
if np.any(other_relPos_stretch >= 0):
continue
# If all checks passed, add to valid stretches
stretch_relPos = relPos[start:end]
stretch_maxpos = np.max(stretch_relPos)
valid_stretches.append({
'crossings': [start, end],
'maxPos': stretch_maxpos,
'hand': side
})
# Use the side with the higher punch. Do not use if there is
# another valid punch with a similar height (maxPosSimilarityThresh)
# on the same arm.
if valid_stretches:
max_pos_idx = np.argmax([s['maxPos'] for s in valid_stretches])
max_pos_hand = valid_stretches[max_pos_idx]['hand']
max_pos_val = valid_stretches[max_pos_idx]['maxPos']
other_max_pos_val = np.array([s['maxPos'] for i, s in enumerate(valid_stretches) if i != max_pos_idx and s['hand'] == max_pos_hand])
if other_max_pos_val.size and np.any(other_max_pos_val / max_pos_val > maxPosSimilarityThresh):
cam_punch_list.append(None)
else:
cam_punch_list.append(valid_stretches[max_pos_idx])
else:
cam_punch_list.append(None)
# across all cameras check if:
# 1. there is a punch in all trials
# 2. it's the same hand each time.
# 3. confidence is good across the widest range of indices of crossings
isTrialPunch = all(cam_punch is not None for cam_punch in cam_punch_list)