-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmp_sort_pose.py
More file actions
5594 lines (4829 loc) · 259 KB
/
mp_sort_pose.py
File metadata and controls
5594 lines (4829 loc) · 259 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 math
import shutil
import statistics
import os
from turtle import distance
import cv2
import pandas as pd
import mediapipe as mp
from mediapipe.framework.formats import landmark_pb2
from google.protobuf import text_format
import hashlib
import time
import json
import random
import numpy as np
import sys
import ast
from collections import Counter
from pandas.core.frame import dataclasses_to_dicts
from sklearn.neighbors import NearestNeighbors
import re
import random
from cv2 import dnn_superres
import pymongo
import pickle
import traceback
from skimage.metrics import structural_similarity as ssim
from sqlalchemy import text
from deap import base, creator, tools, algorithms
class SortPose:
# """Sort image files based on head pose"""
def __init__(self, motion=None, face_height_output=None, image_edge_multiplier=None, EXPAND=False, ONE_SHOT=False, JUMP_SHOT=False, HSV_CONTROL=None, VERBOSE=True,INPAINT=False, SORT_TYPE="128d", OBJ_CLS_ID = None,UPSCALE_MODEL_PATH=None, LMS_DIMENSIONS=2,TSP_SORT=False, USE_HEAD_POSE=False, config=None):
# allow construction via a single config dict for safer parameter passing
# keep backward-compatible positional signature; if `config` is provided
# it will override individual parameters
if config is not None and isinstance(config, dict):
# map config keys to local parameter variables (use existing values as defaults)
motion = config.get('motion', motion)
face_height_output = config.get('face_height_output', face_height_output)
image_edge_multiplier = config.get('image_edge_multiplier', image_edge_multiplier)
EXPAND = config.get('EXPAND', EXPAND)
ONE_SHOT = config.get('ONE_SHOT', ONE_SHOT)
JUMP_SHOT = config.get('JUMP_SHOT', JUMP_SHOT)
HSV_CONTROL = config.get('HSV_CONTROL', HSV_CONTROL)
VERBOSE = config.get('VERBOSE', VERBOSE)
INPAINT = config.get('INPAINT', INPAINT)
SORT_TYPE = config.get('SORT_TYPE', SORT_TYPE)
OBJ_CLS_ID = config.get('OBJ_CLS_ID', OBJ_CLS_ID)
UPSCALE_MODEL_PATH = config.get('UPSCALE_MODEL_PATH', UPSCALE_MODEL_PATH)
LMS_DIMENSIONS = config.get('LMS_DIMENSIONS', LMS_DIMENSIONS)
TSP_SORT = config.get('TSP_SORT', TSP_SORT)
USE_HEAD_POSE = config.get('USE_HEAD_POSE', USE_HEAD_POSE)
self.DO_HSV_KNN = config.get('DO_HSV_KNN', False)
if image_edge_multiplier is None:
image_edge_multiplier = [1.5,2.6,2,2.6] # default values if none provided
# After applying config overrides, ensure required core params are present
if motion is None or face_height_output is None:
raise TypeError("SortPose.__init__() requires 'motion' and 'face_height_output' either as positional args or inside the 'config' dict")
# need to refactor this for GPU
self.mp_face_detection = mp.solutions.face_detection
self.mp_drawing = mp.solutions.drawing_utils
self.get_bg_segment=mp.solutions.selfie_segmentation.SelfieSegmentation()
self.VERBOSE = VERBOSE
self.KNN_SORT_DICT = {
"128d": "128d",
"planar": "planar",
"planar_body": "planar_body",
"planar_hands": "planar_hands",
"planar_hands_USE_ALL": "planar_hands",
"body3D": "body3D",
"ArmsPoses3D": "body3D",
"obj_bbox": "obj",
"object_fusion": "object_fusion"
}
self.KNN_COLS = {
"128d": ("face_encodings68", "dist_enc1"),
"planar": ("face_landmarks", "dist_enc1"),
"planar_hands": ("hand_landmarks", "dist_enc1"),
"planar_body": ("body_landmarks_array", "dist_enc1"),
"body3D": ("body_landmarks_array", "dist_enc1"),
"HSV": ("hsvll", "dist_HSV"),
"obj": ("obj_bbox_list", "dist_obj"),
"object_fusion": ("obj_bbox_fusion_list", "dist_obj_fusion")
}
#maximum allowable distance between encodings (this accounts for dHSV)
self.MAXFACEDIST = .8
self.MINFACEDIST = .5 #TK
self.MAXBODYDIST = 1.5
self.MINBODYDIST = .15
self.FACE_DUPE_DIST = .06
self.BODY_DUPE_DIST = .04
self.HSV_DELTA_MAX = .5
self.HSVMULTIPLIER = 3
self.NORM_BODY_MULTIPLIER = 4
self.BRUTEFORCE = False
self.LMS_DIMENSIONS = LMS_DIMENSIONS
if self.VERBOSE: print("init LMS_DIMENSIONS",self.LMS_DIMENSIONS)
self.CUTOFF = 3000 # DOES factor if ONE_SHOT and TSP_SORT
self.ORIGIN = 0
self.this_nose_bridge_dist = self.NOSE_BRIDGE_DIST = None # to be set in first loop, and sort.this_nose_bridge_dist each time
self.USE_HEAD_POSE = USE_HEAD_POSE
self.MIN_DYN_BBOX_DIM = [1.0,1.0,1.0,1.0] # controls how closely AUTO_EDGE_CROP can get
self.DYN_BBOX_FROM_IMAGE_DIMS = True # if True, use image dimensions to calculate dynamic multiplier rather than body landmarks
self.DYN_BBOX_ROUND_TO = 0.25 # round to nearest 0.5 bbox for crop dimensions
self.DYN_BBOX_PCT = 50 # percentile for dynamic bbox calculation
self.DYN_BBOX_ROUND_CANONICAL = True # if True, it will round to canonical ratios
self.DYN_BBOX_CANONICAL_RATIOS = [(2,1),(3,2), (4,3), (5,4), (7,6), (1,1), (6,7), (4,5), (3,4), (2,3), (1,2)] # these are the canonical ratios that dynamic bboxes will round to if DYN_BBOX_ROUND_CANONICAL is True
self.CHECK_DESC_DIST = 30
self.SORT_TYPE = SORT_TYPE
self.TSP_SORT = TSP_SORT
self.MIN_COL_SUM_MULTIPLIER = 5 # this determines which columns are "small" under MULTIPOLICY
if self.SORT_TYPE == "128d":
self.MIND = self.MINFACEDIST * 1.5
self.MAXD = self.MAXFACEDIST * 1.3
self.MULTIPLIER = self.HSVMULTIPLIER
self.DUPED = self.FACE_DUPE_DIST
self.HSV_DELTA_MAX = self.HSV_DELTA_MAX * 1.5
elif self.SORT_TYPE is not None and ((self.SORT_TYPE == "planar") or ("obj_bbox" in self.SORT_TYPE)):
self.MIND = self.MINBODYDIST * 1.5
self.MAXD = self.MAXBODYDIST
self.MULTIPLIER = self.HSVMULTIPLIER * (self.MINBODYDIST / self.MINFACEDIST)
self.DUPED = self.BODY_DUPE_DIST
if "obj_bbox" in self.SORT_TYPE:
self.MAXD = 200 # override max distance for obj_bbox bc it much bigger
elif self.SORT_TYPE == "planar_hands_USE_ALL":
# designed to take everything
self.MIND = 1000
self.MAXD = 1000
self.MULTIPLIER = 1
self.DUPED = 1
self.FACE_DIST_TEST = -1
self.CHECK_DESC_DIST = -1
self.HSV_DELTA_MAX = 1000
self.FACE_DUPE_DIST = -1
self.BODY_DUPE_DIST = -1
else:
self.MIND = self.MINBODYDIST
self.MAXD = self.MAXBODYDIST * 4
self.MULTIPLIER = self.HSVMULTIPLIER * (self.MINBODYDIST / self.MINFACEDIST)
self.DUPED = self.BODY_DUPE_DIST
self.FACE_DIST_TEST = .02
self.CHECK_DESC_DIST = 45
if self.SORT_TYPE == "ArmsPoses3D":
self.MAXD = self.MAXBODYDIST * 300
self.INPAINT=INPAINT
if self.INPAINT:
from simple_lama_inpainting import SimpleLama
self.INPAINT_MODEL=SimpleLama()
# self.MAX_IMAGE_EDGE_MULTIPLIER=[1.5,2.6,2,2.6] #maximum of the elements
self.knn = NearestNeighbors(metric='euclidean', algorithm='ball_tree')
# if edge_multiplier_name:self.edge_multiplier_name=edge_multiplier_name
# maximum allowable scale up
self.resize_max = 55.99 # effectively turning this off
self.resize_increment = 345
self.USE_INCREMENTAL_RESIZE = True
self.image_edge_multiplier = image_edge_multiplier
self.face_height_output = face_height_output
self.EXPAND = EXPAND
self.EXPAND_SIZE = (25000,25000) # full body
# self.EXPAND_SIZE = (10000,10000) # regular
# self.EXPAND_SIZE = (6400,6400)
if self.EXPAND_SIZE[0] == 25000:
self.EXISTING_CROPABLE_DIM = 8288
else:
self.EXISTING_CROPABLE_DIM = None
print(f" XXX ERROR XXX NEED TO SET EXISTING_CROPABLE_DIM for {self.EXPAND_SIZE[0]}")
self.TARGET_SIZE = (384, 384) # Size to temporarily resize images for SSIM comparison
self.BGCOLOR = [255,255,255]
self.ONE_SHOT = ONE_SHOT
self.JUMP_SHOT = JUMP_SHOT
self.SHOT_CLOCK = 0
self.SHOT_CLOCK_MAX = 10
# self.BODY_LMS = list(range(13, 23)) # 0 is nose, 13-22 are left and right hands and elbows
# this was set to 13,23 as of July 2025, prior to assigning clusters on BodyPoses3D
self.BODY_LMS = list(range(33)) # 0 is nose, 13-22 are left and right hands and elbows
## clustering parameters
self.query_face = True # set to true. Clusturing code will set some to false
self.query_hands = True
self.query_body = True
self.query_head_pose = True
self.cluster_medians = None
self.hands_medians = None
# # self.BODY_LMS = [0,15,16,19,20,21,22] # 0 is nose, 13-22 are left and right hands and elbows
# self.POINTERS = [16,20,15,19] # 0 is nose, 13-22 are left and right hands and elbows
# self.THUMBS = [16,22,15,21] # 0 is nose, 13-22 are left and right hands and elbows
# self.BODY_LMS = [20,19] # 0 is nose, 13-22 are left and right hands and elbows
# self.SUBSET_LANDMARKS = [13,14,19,20] # this should match what is in Clustering
self.ELBOW_HAND = [i for i in range(13,22)]
self.HAND_LMS = self.make_subset_landmarks(15,22)
# self.RIGHT_HAND_LMS = self.make_subset_landmarks(16,18,20,22)
# forearm
self.FOREARM_LMS = self.make_subset_landmarks(13,16)
self.FINGER_LMS = self.make_subset_landmarks(19,20)
self.THUMB_POINTER_LMS = self.make_subset_landmarks(19,22)
self.WRIST_LMS = self.make_subset_landmarks(15,16)
self.ANKLES_LMS = self.make_subset_landmarks(27,28)
self.HAND_LMS_POINTER = self.make_subset_landmarks(8,8)
self.ARMS_HEAD_LMS = self.make_subset_landmarks(11,22)
# adding pointer finger tip
# self.SUBSET_LANDMARKS.extend(self.FINGER_LMS) # this should match what is in Clustering
# only use wrist and finger
# Hands Positions/Gestures
self.HANDS_POSITIONS_LMS = self.make_subset_landmarks(0,20)
if self.SORT_TYPE == "fingertips_positions":
# just fingertips
self.CLUSTER_TYPE = "fingertips_positions" # fingertips_positions
self.SUBSET_LANDMARKS = self.HAND_LMS_POINTER
self.SORT_TYPE = "planar_hands"
elif self.SORT_TYPE is not None and "hands" in self.SORT_TYPE:
# catches any hands
self.CLUSTER_TYPE = "planar_hands"
self.SUBSET_LANDMARKS = self.HAND_LMS
elif self.SORT_TYPE == "ArmPoses3D":
# use 3D sorting with a smaller set of landmarks (head, shoulders and arms)
# self.CLUSTER_TYPE = "BodyPoses3D"
self.SUBSET_LANDMARKS = self.ARMS_HEAD_LMS
print("using ArmPoses3D cluster type, ", self.SUBSET_LANDMARKS)
else:
self.CLUSTER_TYPE = "BodyPoses" # defaults
self.SUBSET_LANDMARKS = self.BODY_LMS
print("using BodyPoses cluster type, ", self.SUBSET_LANDMARKS)
# TBD for DEFAULT LMS SUBSET
# print("final set of subset landmarks", self.SUBSET_LANDMARKS)
# self.SUBSET_LANDMARKS = self.choose_hand(self.HAND_LMS,"right")
self.OBJ_CLS_ID = OBJ_CLS_ID
# self.BODY_LMS = [15]
#____________________TSP SORT________________
if self.TSP_SORT==True:
if self.VERBOSE:print("using travelling salesman sorting")
self.SKIP_FRAC = 35/100 # fraction of entries that can be skipped to optimize for distance
self.POP_SIZE =200 # larger size leads to more accurate results but more time taken
self.SEED=42 # Seed for reproducible sort
#____________________TSP SORT________________
# place to save bad images
self.not_make_face = []
self.same_img = []
self.face_pair_result_cache = {}
self.face_pair_cache_engine = None
self.trust_face_pair_cache = True # set False to force re-test, ignoring cached results
self.reset_face_pair_stats()
# for testing shoulders for image background
self.SHOULDER_THRESH = 0.75
self.nose_2d = None
self.nose_3d = None
#UPSCALING PARAMS
if UPSCALE_MODEL_PATH:
self.upscale_model= self.set_upscale_model(UPSCALE_MODEL_PATH)
# luminosity parameters
if HSV_CONTROL:
print("using HSV_CONTROL settings, ", HSV_CONTROL)
self.LUM_MIN = HSV_CONTROL['LUM_MIN']
self.LUM_MAX = HSV_CONTROL['LUM_MAX']
self.SAT_MIN = HSV_CONTROL['SAT_MIN']
self.SAT_MAX = HSV_CONTROL['SAT_MAX']
self.HUE_MIN = HSV_CONTROL['HUE_MIN']
self.HUE_MAX = HSV_CONTROL['HUE_MAX']
self.HSV_WEIGHT = HSV_CONTROL['HSV_WEIGHT']
self.d128_WEIGHT = HSV_CONTROL['d128_WEIGHT']
self.LUM_WEIGHT = HSV_CONTROL['LUM_WEIGHT']
# set some defaults, looking forward
self.XLOW = -20
self.XHIGH = 1
self.YLOW = -4
self.YHIGH = 4
self.ZLOW = -3
self.ZHIGH = 3
self.MINCROP = 1
self.MAXRESIZE = .5
self.MINMOUTHGAP = 0
self.MAXMOUTHGAP = 4
self.FRAMERATE = 15
self.SORT = 'face_y'
self.SECOND_SORT = 'face_x'
self.ROUND = 0
if motion['side_to_side'] == True:
self.XLOW = -20
self.XHIGH = 1
self.YLOW = -30
self.YHIGH = 30
self.ZLOW = -1
self.ZHIGH = 1
self.MINCROP = 1
self.MAXRESIZE = .5
self.MAXMOUTHGAP = 4
self.FRAMERATE = 15
self.SORT = 'face_y'
self.SECOND_SORT = 'face_x'
# self.SORT = 'mouth_gap'
self.ROUND = 0
elif motion['forward_smile'] == True:
# self.XLOW = -33
# self.XHIGH = -27
self.XLOW = -33
self.XHIGH = -27
self.YLOW = -2
self.YHIGH = 2
self.ZLOW = -2
self.ZHIGH = 2
self.MINCROP = 1
self.MAXRESIZE = .5
self.FRAMERATE = 15
self.SECOND_SORT = 'face_x'
self.MINMOUTHGAP = 0
self.MAXMOUTHGAP = 40
self.SORT = 'mouth_gap'
self.ROUND = 1
elif motion['forward_wider'] == True:
print("setting XYZ for forward_wider")
# self.XLOW = -33
# self.XHIGH = -27
self.XLOW = -40
self.XHIGH = -20
self.YLOW = -5
self.YHIGH = 5
self.ZLOW = -5
self.ZHIGH = 5
self.MINCROP = 1
self.MAXRESIZE = .5
self.FRAMERATE = 15
self.SECOND_SORT = 'face_x'
self.MINMOUTHGAP = 0
self.MAXMOUTHGAP = 40
self.SORT = 'mouth_gap'
self.ROUND = 1
elif motion['laugh'] == True:
self.XLOW = 5
self.XHIGH = 40
self.YLOW = -4
self.YHIGH = 4
self.ZLOW = -3
self.ZHIGH = 3
self.MINCROP = 1
self.MAXRESIZE = .5
self.FRAMERATE = 15
self.SECOND_SORT = 'face_x'
self.MAXMOUTHGAP = 20
self.SORT = 'mouth_gap'
self.ROUND = 1
elif motion['forward_nosmile'] == True:
self.XLOW = -15
self.XHIGH = 5
self.YLOW = -4
self.YHIGH = 4
self.ZLOW = -3
self.ZHIGH = 3
self.MINCROP = 1
self.MAXRESIZE = .3
self.FRAMERATE = 15
self.SECOND_SORT = 'face_y'
self.MAXMOUTHGAP = 2
self.SORT = 'face_x'
self.ROUND = 1
elif motion['static_pose'] == True:
self.XLOW = -20
self.XHIGH = 1
self.YLOW = -4
self.YHIGH = 4
self.ZLOW = -3
self.ZHIGH = 3
self.MINCROP = 1
self.MAXRESIZE = .5
self.FRAMERATE = 15
self.SECOND_SORT = 'mouth_gap'
self.MAXMOUTHGAP = 10
self.SORT = 'face_x'
self.ROUND = 1
elif motion['simple'] == True:
self.XLOW = -20
self.XHIGH = 1
self.YLOW = -4
self.YHIGH = 4
self.ZLOW = -3
self.ZHIGH = 3
self.MINCROP = 1
self.MAXRESIZE = .5
self.FRAMERATE = 15
self.SECOND_SORT = 'mouth_gap'
self.MAXMOUTHGAP = 10
self.SORT = 'face_x'
self.ROUND = 1
elif motion['use_all'] == True:
self.XLOW = -180
self.XHIGH = 180
self.YLOW = -180
self.YHIGH = 180
self.ZLOW = -180
self.ZHIGH = 180
self.MINCROP = 1
self.MAXRESIZE = .5
self.FRAMERATE = 15
self.SECOND_SORT = 'mouth_gap'
self.MAXMOUTHGAP = 1000
self.SORT = 'face_x'
self.ROUND = 1
def get_sort_column_mapping(self, SORT_TYPE, CLUSTER1=None):
"""
Centralized mapping of SORT_TYPE to (sort_column, source_col) for data preprocessing.
Handles all pose and object sorting types.
Args:
SORT_TYPE: The type of sorting (e.g., '128d', 'body3D', 'planar_hands', 'object_fusion')
CLUSTER1: Optional cluster type for disambiguating multi-column cases
Returns:
Tuple of (sort_column, source_col) where:
- sort_column: Column name or list name for the main sorting feature
- source_col: Column name from database (may be None for pre-computed lists)
"""
if SORT_TYPE in ["body3D", "ArmsPoses3D"]:
# 3D body poses
return ("body_landmarks_3D", "body_landmarks_3D")
elif SORT_TYPE == "planar_body":
# Planar body sorting, with special case for hand positions
if CLUSTER1 == "HandsPositions":
return ("hand_landmarks", "hand_landmarks")
else:
return ("body_landmarks_array", "body_landmarks_normalized")
elif SORT_TYPE in ["planar_hands", "planar_hands_USE_ALL", "fingertips_positions"]:
# Hand-based sorting
return ("hand_landmarks", "hand_landmarks")
elif SORT_TYPE == "128d":
# Face encoding sorting
return ("face_encodings68", "face_encodings68")
elif "obj_bbox" in SORT_TYPE:
# Arms/Object fusion precomputes a fixed-length vector in obj_bbox_list.
if CLUSTER1 == "ArmsPoses3D_ObjectFusion":
return ("obj_bbox_list", None)
# Object bounding box (non-fusion)
return ("bbox_norm", "bbox_norm")
elif "fusion" in SORT_TYPE.lower():
# Object fusion (combines hand position, face pose, and detections)
return ("obj_bbox_fusion_list", None)
else:
# Default fallback
if self.VERBOSE:
print(f"Warning: Unknown SORT_TYPE '{SORT_TYPE}', defaulting to 128d")
return ("face_encodings68", "face_encodings68")
def set_output_dims(self):
if self.image_edge_multiplier == [1.3,1.85,2.4,1.85]:
print("setting face_height_output to 1.925/1.85")
self.face_height_output = self.face_height_output*(1.925/1.85)
self.output_dims = (1920,1920)
else:
# self.face_height_output = face_height_output
# takes base image size and multiplies by avg of multiplier
print("setting output dims based on image_edge_multiplier",self.image_edge_multiplier)
print(f"face height is based on: self.face_height_output {self.face_height_output} * avg of {self.image_edge_multiplier[0]} and {self.image_edge_multiplier[2]} for height, and {self.image_edge_multiplier[1]} and {self.image_edge_multiplier[3]} for width")
# print(f"the averages are: height: {(self.image_edge_multiplier[1]+self.image_edge_multiplier[3])/2}, width: {(self.image_edge_multiplier[0]+self.image_edge_multiplier[2])/2}")
self.output_dims = (
int(self.face_height_output * (abs(self.image_edge_multiplier[1]) + abs(self.image_edge_multiplier[3])) / 2),
int(self.face_height_output * (abs(self.image_edge_multiplier[0]) + abs(self.image_edge_multiplier[2])) / 2),
)
# # alternative way to set output dims. Multiply sum of multipliers
# self.output_dims = (int(self.face_height_output*((self.image_edge_multiplier[1]+self.image_edge_multiplier[3]))),int(self.face_height_output*((self.image_edge_multiplier[0]+self.image_edge_multiplier[2]))))
self.MAX_IMAGE_EDGE_MULTIPLIER = self.image_edge_multiplier #testing
print("output_dims",self.output_dims)
def set_counters(self,ROOT,cluster_no,start_img_name,start_site_image_id,hsv_cluster=None,pose_no=None,mkdir=True):
self.negmargin_count = 0
self.toosmall_count = 0
self.outfolder = os.path.join(ROOT,"cluster"+str(cluster_no)+"_"+str(time.time()))
if mkdir and not os.path.exists(self.outfolder):
print("making outfolder",self.outfolder)
os.mkdir(self.outfolder)
self.counter_dict = {
"counter": 1,
"good_count": 0,
"isnot_face_count": 0,
"cropfail_count": 0,
"failed_dist_count": 0,
"inpaint_count":0,
"outfolder": self.outfolder,
"first_run": True,
"start_img_name":start_img_name,
"start_site_image_id":start_site_image_id,
"last_image":None,
"last_image_id":None,
"last_description":None,
"last_image_enc":None,
"last_image_hsv":None,
"last_image_lum":None,
"cluster_no":cluster_no,
"hsv_no":hsv_cluster,
"pose_no":pose_no
}
# def ensure_lms_list(self, lms):
# # convert NormalizedLandmarkList to list of tuples
# if isinstance(lms, landmark_pb2.NormalizedLandmarkList):
# return [(lm.x, lm.y, lm.z) for lm in lms.landmark]
def compute_skip_threshold(self):
"""
Given a symmetric distance matrix and a desired number of skips,
return the distance threshold above which exactly `max_skip` pairwise
distances lie.
Parameters
----------
dist_matrix : np.ndarray, shape (n, n)
Symmetric matrix of pairwise distances, with zeros on the diagonal.
max_skip : int
The number of distances you want to skip (the top `max_skip` largest).
Returns
-------
float
The distance cutoff so that exactly `max_skip` distances are larger.
"""
# 1) Extract upper-triangle distances (excluding diagonal)
triu_idxs = np.triu_indices_from(self.dist_matrix, k=1)
dists = self.dist_matrix[triu_idxs]
# 2) Sort distances ascending
dists_sorted = np.sort(dists)
total = len(dists_sorted)
# 3) The cutoff is at the (total - max_skip)th value
# If max_skip >= total, return max distance
if self.MAX_SKIP >= total:
return dists_sorted[-1]
cutoff_index = total - self.MAX_SKIP
if self.VERBOSE:print("cutoff_index",cutoff_index)
return float(dists_sorted[cutoff_index])
def evaluate_tsp(self,ind):
route = list(ind)
skip_cnt = 0
for _ in range(int(self.MAX_SKIP)):
overheads = []
for j in range(1, len(route)-1):
p, c, n = route[j-1], route[j], route[j+1]
incl = self.dist_matrix[p,c] + self.dist_matrix[c,n]
skip = self.dist_matrix[p,n]
overheads.append((incl-skip, j))
if not overheads:
break
max_oh, idx = max(overheads, key=lambda x: x[0])
if max_oh > self.SKIP_THRESHOLD:
route.pop(idx)
skip_cnt += 1
else:
break
total = sum(self.dist_matrix[route[i], route[i+1]] for i in range(len(route)-1))
return (total + skip_cnt * self.SKIP_PENALTY,)
def cxFixedEndsSimpleSwap(self,ind1, ind2):
"""Swap a random slice only within ind[1:-1], keeping endpoints fixed."""
a, b = sorted(random.sample(range(1, self.N_POINTS-1), 2))
ind1[a:b], ind2[a:b] = ind2[a:b], ind1[a:b]
return ind1, ind2
def mutFixedEndsShuffle(self,ind, indpb):
"""Shuffle only inside ind[1:-1], keeping endpoints fixed."""
sub = ind[1:-1]
tools.mutShuffleIndexes(sub, indpb=indpb)
ind[1:-1] = sub
return (ind,)
def set_TSP_sort(self,df,START_IDX=None,END_IDX=None):
#____SETTING UP DISTANCE MATRIX_______
df_array = df.values
df_diffs = df_array[:, None, :] - df_array[None, :, :]
self.dist_matrix = np.sqrt((df_diffs**2).sum(axis=2))
self.N_POINTS=self.dist_matrix.shape[0]
if self.VERBOSE:print("Number of Points",self.N_POINTS)
if START_IDX == None: START_IDX=0
if END_IDX == None: END_IDX=self.N_POINTS-1
#______CALC OPTIMAL SKIP DISTANCE____________
self.MAX_SKIP=int(np.floor(self.SKIP_FRAC*self.N_POINTS))
self.SKIP_THRESHOLD = self.compute_skip_threshold()
self.SKIP_PENALTY = self.SKIP_THRESHOLD # penalty per skipped point (tweak as needed)
print(f"Optimal SKIP_THRESHOLD for skipping {self.MAX_SKIP} distances: {self.SKIP_THRESHOLD:.3f}")
# ─── DEAP SETUP ───────────────────────────────────────────────────────────
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMin)
self.toolbox = base.Toolbox()
self.toolbox.register("evaluate", self.evaluate_tsp)
self.toolbox.register("mate", self.cxFixedEndsSimpleSwap)
self.toolbox.register("mutate", self.mutFixedEndsShuffle, indpb=0.05)
self.toolbox.register("select", tools.selTournament, tournsize=3)
# Individual: full route with fixed endpoints
self.toolbox.register(
"individual",
tools.initIterate,
creator.Individual,
lambda: [START_IDX]
+ random.sample([i for i in range(self.N_POINTS) if i not in (START_IDX, END_IDX)], self.N_POINTS-2)
+ [END_IDX]
)
self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual)
#___________SETTING UP SORTING___________________
random.seed(42)
self.pop = self.toolbox.population(n=200)
self.hof = tools.HallOfFame(1)
self.stats = tools.Statistics(lambda ind: ind.fitness.values)
self.stats.register("min", np.min)
self.stats.register("avg", np.mean)
return
def do_TSP_SORT(self,raw_df):
self.pop, log = algorithms.eaSimple(self.pop, self.toolbox,
cxpb=0.7, mutpb=0.2,
ngen=40, stats=self.stats,
halloffame=self.hof, verbose=self.VERBOSE)
best = self.hof[0]
if self.VERBOSE:
print("Best route:", best)
print("Best fitness:", self.evaluate_tsp(best)[0])
sorted_df = raw_df.iloc[best].reset_index(drop=True)
return sorted_df
def set_cluster_medians(self,cluster_medians):
self.cluster_medians = cluster_medians
def cols_to_list(self, row, col_list):
merged_list = []
for col_name in col_list:
value = row[col_name]
if isinstance(value, list):
merged_list.extend(value)
else:
merged_list.append(value)
return merged_list
def make_segment(self, df):
print(len(df))
if self.USE_HEAD_POSE:
# xyz = ['face_x', 'face_y', 'face_z']
xyz = ['pitch', 'yaw', 'roll']
df["xyz"] = df.apply(lambda row: self.cols_to_list(row, xyz), axis=1)
# drop any rows with missing xyz data
df_clean = df[df['xyz'].apply(lambda x: not any(np.isnan(x)))]
print(f" finding median Dropped {len(df) - len(df_clean)} rows with NaN values")
# print("df with xyz columns (after removing NaNs), will find median of 3D points")
# print(df_clean[['xyz']].to_string())
if len(df_clean) == 0:
print("No valid data after removing NaNs in head pose angles. Returning empty DataFrame.")
return None
median_xyz = self.get_median_value(df_clean, "xyz")
print(" ~~~ median_xyz: ", median_xyz)
if self.SORT_TYPE != "object_fusion":
# set XYZ HIGH and LOW based on median
margin_dict = {'pitch': 15, 'yaw': 8, 'roll': 8}
low_high_dict = {}
for angle in xyz:
low_high_dict[angle] = (median_xyz[xyz.index(angle)] - margin_dict[angle], median_xyz[xyz.index(angle)] + margin_dict[angle])
print(" low_high_dict: ", low_high_dict)
# use low_high_dict to filter
for angle in xyz:
df = df.loc[((df[angle] < low_high_dict[angle][1]) & (df[angle] > low_high_dict[angle][0]))]
print(f"after filtering dynamically by {angle}, len(df): {len(df)}")
else:
print(" object_fusion sorting, skipping dynamic head pose filtering")
else:
# use the defaults set in __init__
df = df.loc[((df['face_y'] < self.YHIGH) & (df['face_y'] > self.YLOW))]
print(f"after filtering by face_y, len(df): {len(df)}")
df = df.loc[((df['face_x'] < self.XHIGH) & (df['face_x'] > self.XLOW))]
print(f"after filtering by face_x, len(df): {len(df)}")
df = df.loc[((df['face_z'] < self.ZHIGH) & (df['face_z'] > self.ZLOW))]
print(f"after filtering by face_z, len(df): {len(df)}")
if self.LUM_MIN:
df = df.loc[((df['lum'] < self.LUM_MAX) & (df['lum'] > self.LUM_MIN))]
if self.SAT_MIN:
df = df.loc[((df['sat'] < self.SAT_MAX) & (df['sat'] > self.SAT_MIN))]
if self.HUE_MIN:
df = df.loc[((df['hue'] < self.HUE_MAX) & (df['hue'] > self.HUE_MIN))]
print(f"after filtering by hue, len(df): {len(df)}")
# removing cropX for now. Need to add that back into the data
# df = df.loc[df['cropX'] >= self.MINCROP]
# print(df.size)
# COMMENTING OUT MOUTHGAP as it is functioning as a minimum. Needs refactoring
df = df.loc[df['mouth_gap'] >= self.MINMOUTHGAP]
df = df.loc[df['mouth_gap'] <= self.MAXMOUTHGAP]
# df = df.loc[df['mouth_gap'] <= MAXMOUTHGAP]
print(f"after filtering by mouth_gap, len(df): {len(df)}")
# df = df.loc[df['resize'] < MAXRESIZE]
print(df)
return df
def createList(self,segment):
r1 = segment[self.SORT].min()
r2 = segment[self.SORT].max()
print("startAngle, endAngle")
print(r1, r2)
# divides angles based off of ROUND
divisor = eval(f"1e{self.ROUND}")
# Testing if range r1 and r2
# are equal
if (r1 == r2):
return r1
else:
# Create empty list
res = []
# loop to append successors to
# list until r2 is reached.
while(r1 < r2+1 ):
res.append(round(r1,self.ROUND))
r1 += 1/divisor
# print(r1 )
self.angle_list = res
return res
def is_face(self, image):
# For static images:
IMAGE_FILES = []
with self.mp_face_detection.FaceDetection(model_selection=1,
min_detection_confidence=0.75
) as face_detection:
# image = cv2.imread(file)
# Convert the BGR image to RGB and process it with MediaPipe Face Detection.
results = face_detection.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# Draw face detections of each face.
if not results.detections:
is_face = False
else:
is_face = True
print("returning is_face ", is_face)
return is_face
#get distance beetween encodings
def get_d(self, enc1, enc2):
enc1=np.array(enc1)
# print("enc1")
# print(enc1)
# # this is currently an np.array, not 128d list
# print(enc1[0])
enc2=np.array(enc2)
# print("enc2")
# print(enc2)
d=np.linalg.norm(enc1 - enc2, axis=0)
return d
def simplest_order(self, segment):
img_array = []
delta_array = []
#simple ordering, second sort, because this is the...?
rotation = segment.sort_values(by=self.SORT)
i = 0
for index, row in rotation.iterrows():
print(row['face_x'], row['face_y'], row['imagename'])
#I don't know what this does or why
delta_array.append(row['mouth_gap'])
try:
img = cv2.imread(row['imagename'])
height, width, layers = img.shape
size = (width, height)
# test to see if this is actually an face, to get rid of blank ones/bad ones
# this may not be necessary
img_array.append(img)
i+=1
except:
print('failed:',row['imagename'])
# print("delta_array")
# print(delta_array)
return img_array, size
def get_cv2size(self, site_specific_root_folder, filename_or_imagedata):
#IF filename_or_imagedata IS STRING:
img = cv2.imread(os.path.join(site_specific_root_folder,filename_or_imagedata))
#ELIF filename_or_imagedata IS NDARRAY:
#img = filename_or_imagedata
size = (img.shape[0], img.shape[1])
return size
# this doesn't seem to work
# but it might be relevant later
def cv2_safeopen_size(self, ROOT, filename_or_imagedata):
print('attempting safeopen')
if (len(filename_or_imagedata.split('/'))>1):
# has path
print('about to try')
try:
img = cv2.imread(filename_or_imagedata)
except:
print('could not read image path ',filename_or_imagedata)
elif (len(filename_or_imagedata.split('.'))==1):
# is filename
print('about to try')
try:
img = cv2.imread(os.path.join(ROOT,filename_or_imagedata))
except:
print('could not read image ',filename_or_imagedata)
else:
# is imagedata
img = filename_or_imagedata
print('was image data')
size = (img.shape[0], img.shape[1])
return img, size
# test if new and old make a face, calls is_face
def test_pair(self, last_img, img):
print(img.shape,"@@@@@@@@@@@@@@@@@@@@")
print(last_img.shape,"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
try:
height, width, layers = img.shape
size = (width, height)
# print('loaded img 1')
last_height, last_width, last_layers = last_img.shape
last_size = (last_width, last_height)
# print('loaded img 2')
# Check if dimensions match
if size != last_size:
print(f'Image dimensions do not match. Resizing for blend test: current={size}, previous={last_size}')
# Normalize both images to a shared size for robust pair testing.
# Use the smaller dimensions to avoid heavy upscaling artifacts.
target_width = min(size[0], last_size[0])
target_height = min(size[1], last_size[1])
if target_width <= 0 or target_height <= 0:
print('Invalid target dimensions for blend test. Skipping blending.')
return False
img = cv2.resize(img, (target_width, target_height), interpolation=cv2.INTER_AREA)
last_img = cv2.resize(last_img, (target_width, target_height), interpolation=cv2.INTER_AREA)
size = (target_width, target_height)
last_size = (target_width, target_height)
# code for face detection and blending
if self.is_face(img):
# print('new file is face')
blend = cv2.addWeighted(img, 0.5, last_img, 0.5, 0.0)
# foopath = os.path.join("/Users/michaelmandiberg/Documents/projects-active/facemap_production/blends", "foobar_"+str(random.random())+".jpg")
# cv2.imwrite(foopath, blend)
# print('blended faces')
blended_face = self.is_face(blend)
# print('blended is_face', blended_face)
if blended_face:
# if self.VERBOSE: print('test_pair: is_face True! adding it')
return True
else:
print('test_pair: skipping this one')
return False
else:
print('test_pair: new_file is not a face:')
return False
except Exception as e:
print('test_pair failed while processing image pair')
print('Error:', str(e))
return False
def set_face_pair_cache_engine(self, engine):
self.face_pair_cache_engine = engine
def reset_face_pair_stats(self):
self.face_pair_stats = {
"pass": 0,
"fail": 0,
"cache_pass": 0,
"cache_fail": 0,
"computed_pass": 0,
"computed_fail": 0,
}
def print_face_pair_stats(self, label="face pair cycle"):
stats = getattr(self, "face_pair_stats", None)
if not stats:
print(f"[{label}] no face pair stats available")
return
print(
f"[{label}] pass={stats['pass']} fail={stats['fail']} "
f"cache_pass={stats['cache_pass']} cache_fail={stats['cache_fail']} "
f"computed_pass={stats['computed_pass']} computed_fail={stats['computed_fail']}"
)
def canonicalize_face_pair(self, image_id_a, image_id_b):
try:
image_id_a = int(image_id_a)
image_id_b = int(image_id_b)
except (TypeError, ValueError):
return None
if image_id_a == image_id_b:
return None
return tuple(sorted((image_id_a, image_id_b)))
def get_face_pair_cache_result(self, image_id_a, image_id_b):
print(f"will I trust face pair? {self.trust_face_pair_cache}")
if not self.trust_face_pair_cache:
return None
pair_key = self.canonicalize_face_pair(image_id_a, image_id_b)
if pair_key is None:
return None
if pair_key in self.face_pair_result_cache:
return self.face_pair_result_cache[pair_key]
if self.face_pair_cache_engine is None:
return None
lookup_sql = text(
"SELECT result FROM FacePairTestCache "
"WHERE image_id_lo = :image_id_lo AND image_id_hi = :image_id_hi"
)
with self.face_pair_cache_engine.connect() as connection:
row = connection.execute(
lookup_sql,
{
"image_id_lo": pair_key[0],
"image_id_hi": pair_key[1],
},
).mappings().first()
if row and row["result"] in ("pass", "fail"):
self.face_pair_result_cache[pair_key] = row["result"]
return row["result"]
return None
def store_face_pair_cache_result(self, image_id_a, image_id_b, result):
if result not in ("pass", "fail"):
return
pair_key = self.canonicalize_face_pair(image_id_a, image_id_b)
if pair_key is None:
return
self.face_pair_result_cache[pair_key] = result
if self.face_pair_cache_engine is None:
return
upsert_sql = text(
"INSERT INTO FacePairTestCache (image_id_lo, image_id_hi, result) "
"VALUES (:image_id_lo, :image_id_hi, :result) "
"ON DUPLICATE KEY UPDATE "
"result = VALUES(result), updated_at = CURRENT_TIMESTAMP"
)
with self.face_pair_cache_engine.begin() as connection:
connection.execute(
upsert_sql,