-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdetect_multiple_faces.py
More file actions
2553 lines (2185 loc) · 122 KB
/
detect_multiple_faces.py
File metadata and controls
2553 lines (2185 loc) · 122 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
from multiprocessing import Lock, Process, Queue, current_process
import time
import queue # imported for using queue.Empty exception
import csv
import os
import hashlib
import cv2
import math
import pickle
import sys # can delete for production
from sys import platform
import json
import base64
import gc
import traceback
import threading
import sys
import re
import types # Import types for SimpleNamespace
import numpy as np
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
from mediapipe.framework.formats import landmark_pb2 # Needed for NormalizedLandmarkList and LandmarkList
from mediapipe.framework.formats import classification_pb2 # Needed for ClassificationList and Classification
import pandas as pd
from ultralytics import YOLO
from sqlalchemy import create_engine, text, MetaData, Table, Column, Numeric, Integer, VARCHAR, Boolean, DECIMAL, BLOB, JSON, String, Date, ForeignKey, update, select
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
# my ORM
from my_declarative_base import Base, Images, WanderingImages, NMLImages, Keywords, Counters, SegmentTable, SegmentBig_isnotface, ImagesKeywords, ImagesBackground, Encodings, PhoneBbox, Detections, Column, Integer, String, Date, Boolean, DECIMAL, BLOB, ForeignKey, JSON
from sqlalchemy.exc import OperationalError
from sqlalchemy.pool import NullPool
from sqlalchemy.dialects import mysql
import pymongo
from pymongo.errors import DuplicateKeyError
from mp_pose_est import SelectPose
from mp_db_io import DataIO
from mp_sort_pose import SortPose
from tools_yolo import YOLOTools
from tools_clustering import ToolsClustering
#####new imports #####
from mediapipe.python.solutions.drawing_utils import _normalized_to_pixel_coordinates
import dlib
import face_recognition_models
# outputfolder = os.path.join(ROOT,folder+"_output_febmulti")
SAVE_ORIG = False
DRAW_BOX = False
MINSIZE = 500
SLEEP_TIME=0
VERBOSE = False
QUIET = False
# only for triage
sortfolder ="getty_test"
#use in some clean up for getty
http="https://media.gettyimages.com/photos/"
# am I looking on RAID/SSD for a folder? If not, will pull directly from SQL
# if so, also change the site_name_id etc around line 930
IS_FOLDER = True
# these only matter if SQL (not folder)
DO_OVER = True
FIND_NO_IMAGE = True
FIND_MISSING_BBOX_ONLY = False # use this to skip everything but the bbox
REDO_MISSING_MONGO = True # use this to find missing faces when mysql bool == 1
REDO_MISSING_BODIES = True # use this to find missing bodies when mysql bool == 1
# OVERRIDE_PATH will force it to look in a specific folder
OVERRIDE_PATH = False
# OVERRIDE_PATH = "/Volumes/SSD4/images_getty"
OVERRIDE_TOPIC = False
# OVERRIDE_TOPIC = [16, 17, 18, 23, 24, 45, 53]
# further restricts to a specific subfolder
SHUTTER_SSD_OVERRIDE = False
if SHUTTER_SSD_OVERRIDE:
OVERRIDE_PATH = "/Volumes/SSD4green/images_shutterstock"
SHUTTERFOLDER = "C/C"
REPROCESS_MISSING_MONGO_DATA_OVERRIDE = True
'''
Oct 13, got up to 109217155
switching to topic targeted
'''
'''
1 getty 3D
2 shutterstock 3D
3 adobe
4 istock
5 pexels - all wandering?
6 unsplash
7 pond5 - all wandering?
8 123rf
9 alamy
10 visualchinagroup - already done?
11 picxy 3D
12 pixerf 3D (all too small)
13 imagesbazaar 3D
14 indiapicturebudget 3D
15 iwaria 3D
16 nappy 3D
17 picha 3D
18 afripics - where are these?
'''
# I think this only matters for IS_FOLDER mode, and the old SQL way
SITE_NAME_ID = 2
# 2, shutter. 4, istock
# 7 pond5, 8 123rf
POSE_ID = 0
# folder doesn't matter if IS_FOLDER is False. Declared FAR below.
# for sites with files spread over several SSDs, you can add addtional folders
# you will also have to add the MAIN_FOLDER2 variable below, etc
# MAIN_FOLDER1 = "/Volumes/LaCie/images_adobe_also"
# MAIN_FOLDER2 = "/Volumes/OWC5/images_adobe"
# MAIN_FOLDER3 = "/Volumes/SSD4_Green/images_adobe"
# MAIN_FOLDER4 = "/Volumes/SSD4_Green/images_123rf"
# MAIN_FOLDER5 = "/Volumes/SSD2/images_123rf"
# #testing locally with two
MAIN_FOLDER1 = "/Volumes/LaCie/segment_images_no_images/images_shutterstock"
# MAIN_FOLDER1 = "/Volumes/LaCie/segment_images_no_images/images_shutterstock"
# MAIN_FOLDERS = [MAIN_FOLDER1, MAIN_FOLDER2]
MAIN_FOLDERS = [MAIN_FOLDER1]
# MAIN_FOLDERS = [MAIN_FOLDER1, MAIN_FOLDER2, MAIN_FOLDER3, MAIN_FOLDER4, MAIN_FOLDER5]
BATCH_SIZE = 5000 # Define how many from each folder in each batch
LIMIT = 1000
#temp hack to go 1 subfolder at a time
THESE_FOLDER_PATHS = ["9/9C", "9/9D", "9/9E", "9/9F", "9/90", "9/91", "9/92", "9/93", "9/94", "9/95", "9/96", "9/97", "9/98", "9/99"]
# MAIN_FOLDER = "/Volumes/SSD4/adobeStockScraper_v3/images"
# MAIN_FOLDER = "/Users/michaelmandiberg/Documents/projects-active/facemap_production/gettyimages/newimages"
# CSV_FOLDERCOUNT_NAME = "folder_countout.csv"
CSV_FOLDERCOUNT_NAMES = ["folder_countout1.csv", "folder_countout2.csv"]
IS_SSD=False
# set BODY to true, set SSD to false, set TOPIC_ID
# for silence, start at 103893643
# for HDD topic, start at 28714744
BODYLMS = True
HANDLMS = True
REDO_BODYLMS_3D = False # this makes it skip hands and YOLO
if REDO_BODYLMS_3D: HANDLMS = False # if doing 3D redo, don't do hands
TOPIC_ID = None
# TOPIC_ID = [24, 29] # adding a TOPIC_ID forces it to work from SegmentBig_isface, currently at 7412083
SEGMENT = 0 # topic_id set to 0 or False if using HelperTable or not using a segment
# HelperTable_name = "SegmentHelper_nov2025_faces_without_bbox" # set to False if not using a HelperTable
HelperTable_name = False
# SegmentTable_name = 'SegmentOct20'
SegmentTable_name = 'SegmentBig_isface'
# if HelperTable_name, set start point
START_IMAGE_ID = 0
# HelperTable_name = "SegmentHelper_nov2025_SQL_only_still_faces"
# class HelperTable(Base):
# __tablename__ = HelperTable_name
# seg_image_id=Column(Integer,primary_key=True, autoincrement=True)
# image_id = Column(Integer, primary_key=True, autoincrement=True)
if BODYLMS is True or HANDLMS is True:
# for SQL, it needs SegmentTable_name to be SegmentOct20 or SegmentBig_isface
# THIS NEEDS TO BE REFACTORED FOR GPU
get_background_mp = mp.solutions.selfie_segmentation
get_bg_segment = get_background_mp.SelfieSegmentation()
############# Reencodings #############
FROM =f"{SegmentTable_name} seg1"
if SegmentTable_name == 'SegmentOct20':
SELECT = "DISTINCT seg1.image_id, seg1.site_name_id, seg1.contentUrl, seg1.imagename, seg1.site_image_id, seg1.mongo_body_landmarks, seg1.mongo_face_landmarks, seg1.bbox"
elif SegmentTable_name == 'SegmentBig_isface' or SegmentTable_name == 'SegmentBig_isnotface':
# segmentbig does not have mongo booleans
SELECT = "DISTINCT seg1.image_id, seg1.site_name_id, seg1.contentUrl, seg1.imagename, seg1.site_image_id, e.mongo_body_landmarks, e.mongo_face_landmarks, e.bbox"
FROM += " JOIN Encodings e ON seg1.image_id = e.image_id"
# FROM ="Encodings e"
if BODYLMS or (BODYLMS and HANDLMS):
QUERY = " "
if SegmentTable_name == 'SegmentOct20':
if REDO_BODYLMS_3D:
QUERY += " seg1.mongo_body_landmarks IS NOT NULL and seg1.mongo_body_landmarks_3D IS NULL"
else:
QUERY = " seg1.mongo_body_landmarks IS NULL "
elif SegmentTable_name == 'SegmentBig_isface':
if REPROCESS_MISSING_MONGO_DATA_OVERRIDE:
# this is a placeholder that will always return true, bc the main filter is in the helper table
QUERY = " seg1.image_id IS NOT NULL "
elif REDO_BODYLMS_3D:
QUERY += " e.mongo_body_landmarks IS NOT NULL and e.mongo_body_landmarks_3D IS NULL"
else:
QUERY = " e.mongo_body_landmarks IS NULL "
# if doing both BODYLMS and HANDLMS, query as if BODY, and also do HAND on those image_ids
if TOPIC_ID:
# FROM = " SegmentBig_isface seg1 "
FROM += " LEFT JOIN ImagesTopics it ON seg1.image_id = it.image_id"
SUBQUERY = f" AND it.topic_id IN {tuple(TOPIC_ID)} "
else:
SUBQUERY = " "
if HelperTable_name:
FROM += f" INNER JOIN {HelperTable_name} ht ON seg1.image_id = ht.image_id "
QUERY += f" AND seg1.image_id > {START_IMAGE_ID}"
elif HANDLMS:
QUERY = " seg1.mongo_hand_landmarks IS NULL and seg1.no_image IS NULL"
# SUBQUERY = " "
# temp for testing one pose at a time
if POSE_ID:
SUBQUERY = f" AND seg1.image_id IN (SELECT ip.image_id FROM ImagesPoses128 ip WHERE ip.cluster_id = {POSE_ID})"
else:
SUBQUERY = f" AND seg1.image_id IN (SELECT ip.image_id FROM ImagesPoses128 ip)"
# SUBQUERY = f"(SELECT seg1.image_id FROM {SegmentTable_name} seg1 WHERE face_x > -33 AND face_x < -27 AND face_y > -2 AND face_y < 2 AND face_z > -2 AND face_z < 2)"
# SUBQUERY = f"(SELECT seg1.image_id FROM {SegmentTable_name} seg1 WHERE face_x > -33 AND face_x < -27 AND face_y > -2 AND face_y < 2 AND face_z > -2 AND face_z < 2)"
elif SEGMENT:
QUERY = " "
FROM = f"{SegmentTable_name} seg1 LEFT JOIN ImagesTopics it ON seg1.image_id = it.image_id"
# SUBQUERY = f" seg1.mongo_body_landmarks IS NULL AND face_x > -33 AND face_x < -27 AND face_y > -2 AND face_y < 2 AND face_z > -2 AND face_z < 2 AND it.topic_id = {SEGMENT}"
SUBQUERY = f" seg1.mongo_body_landmarks IS NULL AND it.topic_id = {SEGMENT}"
elif HelperTable_name:
FROM += f" INNER JOIN {HelperTable_name} ht ON seg1.image_id = ht.image_id LEFT JOIN ImagesTopics it ON seg1.image_id = it.image_id"
QUERY = "e.body_landmarks IS NULL AND seg1.site_name_id NOT IN (1,4)"
SUBQUERY = ""
WHERE = f"{QUERY} {SUBQUERY}"
else:
############ KEYWORD SELECT #############
SELECT = "DISTINCT i.image_id, i.site_name_id, i.contentUrl, i.imagename, e.encoding_id, i.site_image_id, e.face_landmarks, e.bbox"
# FROM ="Images i JOIN ImagesKeywords ik ON i.image_id = ik.image_id JOIN Keywords k on ik.keyword_id = k.keyword_id LEFT JOIN Encodings e ON i.image_id = e.image_id"
FROM ="Images i LEFT JOIN Encodings e ON i.image_id = e.image_id"
# gettytest3
# WHERE = "e.face_encodings68 IS NULL AND e.face_encodings IS NOT NULL"
# production
# WHERE = "e.is_face IS TRUE AND e.face_encodings68 IS NULL"
if DO_OVER and FIND_NO_IMAGE:
# find images with missing files
# find all images that have not been processed, and have not been declared no image
WHERE = f"e.encoding_id IS NULL AND i.no_image IS NULL AND e.two_noses is NULL AND i.site_name_id = {SITE_NAME_ID}"
elif DO_OVER and not FIND_NO_IMAGE:
# find all images that have been processed, but have no face found, and aren't no_image or two_noses
# WHERE = f"e.encoding_id IS NOT NULL AND e.is_face = 0 AND e.mongo_encodings is NULL AND e.two_noses is NULL AND i.no_image IS NULL AND i.site_name_id = {SITE_NAME_ID}"
# find all images that have been processed, have encodings, but no bbox to reprocess
WHERE = f"e.encoding_id IS NOT NULL AND e.bbox IS NULL AND e.mongo_encodings =1 AND e.is_body IS NULL AND e.two_noses is NULL AND i.no_image IS NULL AND i.site_name_id = {SITE_NAME_ID}"
else:
WHERE = f"e.encoding_id IS NULL AND i.site_name_id = {SITE_NAME_ID}"
if OVERRIDE_TOPIC:
FROM += " LEFT JOIN ImagesTopics_isnotface it ON i.image_id = it.image_id"
WHERE += f" AND it.topic_id IN {tuple(OVERRIDE_TOPIC)} "
# WHERE += f" AND i.topic_id = {OVERRIDE_TOPIC}"
WHERE += f" AND i.image_id > {START_IMAGE_ID}" if START_IMAGE_ID else ""
WHERE += f" AND i.no_image IS NULL"
QUERY = WHERE
SUBQUERY = ""
# AND i.age_id NOT IN (1,2,3,4)
IS_SSD= False
#########################################
## Gettytest3
# WHERE = "e.face_encodings IS NULL AND e.bbox IS NOT NULL"
##########################################
############# FROM A SEGMENT #############
# SegmentTable_name = 'June20segment123straight'
# FROM ="Images i LEFT JOIN Encodings e ON i.image_id = e.image_id"
# QUERY = "e.face_encodings68 IS NULL AND e.bbox IS NOT NULL AND e.image_id IN"
# # QUERY = "e.image_id IN"
# SUBQUERY = f"(SELECT seg1.image_id FROM {SegmentTable_name} seg1 )"
# WHERE = f"{QUERY} {SUBQUERY}"
# IS_SSD=True
##########################################
# platform specific credentials
io = DataIO(IS_SSD)
db = io.db
ROOT = io.ROOT
# GPU OVERRIDE =
# overriding DB for testing
# io.db["name"] = "gettytest3"
yo = YOLOTools()
# --- Initialize MediaPipe objects with GPU delegate ---
NML_GITHUB = "/Users/michaelmandiberg/Documents/GitHub/takingstock/"
HOME_GITHUB = "/Users/michaelmandiberg/Documents/GitHub/facemap/"
ULTRA_GITHUB = "/Users/michael.mandiberg/Documents/GitHub/takingstock/"
# check to see which one exists
if os.path.exists(NML_GITHUB):
ROOT_GITHUB = NML_GITHUB
elif os.path.exists(HOME_GITHUB):
ROOT_GITHUB = HOME_GITHUB
IS_ULTRA = False
elif os.path.exists(ULTRA_GITHUB):
ROOT_GITHUB = ULTRA_GITHUB
IS_ULTRA = True
io.NUMBER_OF_PROCESSES = 20
io.NUMBER_OF_PROCESSES_GPU = 60
io.NUMBER_OF_PROCESSES = io.NUMBER_OF_PROCESSES_GPU
FACE_DETECTOR_MODEL_PATH = os.path.join(ROOT_GITHUB, 'models', 'blaze_face_short_range.tflite')
FACE_LANDMARKER_MODEL_PATH = os.path.join(ROOT_GITHUB, 'models', 'face_landmarker.task')
HAND_LANDMARKER_MODEL_PATH = os.path.join(ROOT_GITHUB, 'models', 'hand_landmarker.task')
POSE_LANDMARKER_MODEL_PATH = os.path.join(ROOT_GITHUB, 'models', 'pose_landmarker_full.task')
# Base options for GPU
base_options_detector_gpu = python.BaseOptions(
delegate=python.BaseOptions.Delegate.GPU,
model_asset_path=FACE_DETECTOR_MODEL_PATH
)
# Face Detector options
face_detector_options = vision.FaceDetectorOptions(
base_options=base_options_detector_gpu,
running_mode=vision.RunningMode.IMAGE, # Specifies the input data type (IMAGE, VIDEO, or LIVE_STREAM)
min_detection_confidence=0.7 # Minimum confidence score for a face to be considered detected
)
# # Face Landmarker options (formerly Face Mesh)
base_options_landmarker_gpu = python.BaseOptions(
delegate=python.BaseOptions.Delegate.GPU,
model_asset_path=FACE_LANDMARKER_MODEL_PATH
)
face_landmarker_options = vision.FaceLandmarkerOptions(
base_options=base_options_landmarker_gpu,
running_mode=vision.RunningMode.IMAGE, # Or .VIDEO, .LIVE_STREAM
)
# Hand Landmarker options
base_options_hand_gpu = python.BaseOptions(
delegate=python.BaseOptions.Delegate.GPU,
model_asset_path=HAND_LANDMARKER_MODEL_PATH
)
hand_landmarker_options = vision.HandLandmarkerOptions(
base_options=base_options_hand_gpu,
running_mode=vision.RunningMode.IMAGE,
num_hands=2,
min_hand_detection_confidence=0.4,
min_hand_presence_confidence=0.5, # Corresponds to min_detection_confidence in old API
min_tracking_confidence=0.5
)
# Base options for GPU delegate for PoseLandmarker
base_options_pose_gpu = python.BaseOptions(
delegate=python.BaseOptions.Delegate.GPU,
model_asset_path=POSE_LANDMARKER_MODEL_PATH
)
pose_landmarker_options = vision.PoseLandmarkerOptions(
base_options=base_options_pose_gpu,
running_mode=vision.RunningMode.IMAGE,
min_pose_detection_confidence=0.5,
min_pose_presence_confidence=0.5,
min_tracking_confidence=0.5,
output_segmentation_masks=False # Set to True if you need segmentation masks
)
# Create the detector and landmarker objects outside the loop for efficiency
face_detector = vision.FaceDetector.create_from_options(face_detector_options)
face_landmarker = vision.FaceLandmarker.create_from_options(face_landmarker_options)
hand_landmarker = vision.HandLandmarker.create_from_options(hand_landmarker_options)
pose_landmarker = vision.PoseLandmarker.create_from_options(pose_landmarker_options)
#not currently in use, so commented out
# mp_drawing = mp.solutions.drawing_utils
# drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)
####### new imports and models ########
face_recognition_model = face_recognition_models.face_recognition_model_location()
face_encoder = dlib.face_recognition_model_v1(face_recognition_model)
YOLO_MODEL = YOLO("yolov8m.pt") #MEDIUM
SMALL_MODEL = False
NUM_JITTERS= 1
###############
OBJ_CLS_LIST=[67,63,26,27,32] ##
OBJ_CLS_NAME={0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat'\
, 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat'\
, 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe'\
, 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard'\
, 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard'\
, 38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl'\
, 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza'\
, 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet'\
, 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster'\
, 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier'\
, 79: 'toothbrush'}
## CREATING POSE OBJECT FOR SELFIE SEGMENTATION
## none of these are used in this script ##
## just to initialize the object ##
# image_edge_multiplier = [1.5,1.5,2,1.5] # bigger portrait
# image_edge_multiplier_sm = [1.2, 1.2, 1.6, 1.2] # standard portrait
image_edge_multiplier_sm = [2.2, 2.2, 2.6, 2.2] # standard portrait
face_height_output = 500
motion = {"side_to_side": False, "forward_smile": True, "laugh": False, "forward_nosmile": False, "static_pose": False, "simple": False}
EXPAND = False
ONE_SHOT = True # take all files, based off the very first sort order.
JUMP_SHOT = False # jump to random file if can't find a run
cfg = {
'motion': motion,
'face_height_output': face_height_output,
'image_edge_multiplier': image_edge_multiplier_sm,
'EXPAND': EXPAND,
'ONE_SHOT': ONE_SHOT,
'JUMP_SHOT': JUMP_SHOT,
'HSV_CONTROL': None,
'VERBOSE': VERBOSE
}
sort = SortPose(config=cfg)
start = time.time()
def init_session():
# init session
global engine, Session, session
if IS_ULTRA:
# regular brew installed mysql
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(db=db['name'], user=db['user'], pw=db['pass']), pool_pre_ping=True, pool_recycle=600, poolclass=NullPool)
# engine = create_engine("mysql+pymysql://{user}:{pw}@{host}/{db}"
# .format(host=db['host'], db=db['name'], user=db['user'], pw=db['pass']), poolclass=NullPool)
else:
# macbook pro with unix socket
engine = create_engine("mysql+pymysql://{user}:{pw}@/{db}?unix_socket={socket}".format(
user=db['user'], pw=db['pass'], db=db['name'], socket=db['unix_socket']
), pool_pre_ping=True, pool_recycle=600, poolclass=NullPool)
# metadata = MetaData(engine)
metadata = MetaData() # apparently don't pass engine
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
def close_session():
session.close()
engine.dispose()
def collect_the_garbage():
if 'image' in locals():
del image
gc.collect()
if VERBOSE: print("garbage collected")
def init_mongo():
# init session
# global engine, Session, session
global mongo_client, mongo_db, mongo_collection, bboxnormed_collection, body_world_collection, mongo_hand_collection
mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
mongo_db = mongo_client["stock"]
mongo_collection = mongo_db["encodings"]
bboxnormed_collection = mongo_db["body_landmarks_norm"]
body_world_collection = mongo_db["body_world_landmarks"]
mongo_hand_collection = mongo_db["hand_landmarks"]
def close_mongo():
mongo_client.close()
# not sure if I'm using this
class Object:
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
def print_get_split(split):
now = time.time()
duration = now - split
print(duration)
return now
def ensure_image_cv2(image):
# convert image back to numpy array if it's a mediapipe image
if isinstance(image, mp.Image):
image = image.numpy_view()
# Ensure image is 3-channel (RGB) and uint8 for dlib
if image.shape[2] == 4:
image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
image = image.astype(np.uint8)
return image
def ensure_image_mp(image):
# convert image back to mediapipe image if it's a numpy array
if isinstance(image, np.ndarray):
image = mp.Image(image_format=mp.ImageFormat.SRGBA, data=cv2.cvtColor(image, cv2.COLOR_BGR2RGBA))
return image
def save_image_elsewhere(image, path):
#saves a CV2 image elsewhere -- used in setting up test segment of images
oldfolder = "newimages"
newfolder = "testimages"
outpath = path.replace(oldfolder, newfolder)
try:
print(outpath)
cv2.imwrite(outpath, image)
print("wrote")
except:
print("save_image_elsewhere couldn't write")
def save_image_by_path(image, sort, name):
global sortfolder
def mkExist(outfolder):
isExist = os.path.exists(outfolder)
if not isExist:
os.mkdir(outfolder)
sortfolder_path = os.path.join(ROOT,sortfolder)
outfolder = os.path.join(sortfolder_path,sort)
outpath = os.path.join(outfolder, name)
mkExist(sortfolder)
mkExist(outfolder)
try:
print(outpath)
cv2.imwrite(outpath, image)
except:
print("save_image_by_path couldn't write")
def insertignore(dataframe,table):
# creating column list for insertion
cols = "`,`".join([str(i) for i in dataframe.columns.tolist()])
# Insert DataFrame recrds one by one.
for i,row in dataframe.iterrows():
sql = "INSERT IGNORE INTO `"+table+"` (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
engine.connect().execute(sql, tuple(row))
def insertignore_df(dataframe,table_name, engine):
# Convert the DataFrame to a SQL table using pandas' to_sql method
with engine.connect() as connection:
dataframe.to_sql(name=table_name, con=connection, if_exists='append', index=False)
def insertignore_dict(dict_data,table_name):
# # creating column list for insertion
# # cols = "`,`".join([str(i) for i in dataframe.columns.tolist()])
# cols = "`,`".join([str(i) for i in list(dict.keys())])
# tup = tuple(list(dict.values()))
# sql = "INSERT IGNORE INTO `"+table+"` (`" +cols + "`) VALUES (" + "%s,"*(len(tup)-1) + "%s)"
# engine.connect().execute(sql, tup)
# Create a SQLAlchemy Table object representing the target table
target_table = Table(table_name, metadata, extend_existing=True, autoload_with=engine)
# Insert the dictionary data into the table using SQLAlchemy's insert method
with engine.connect() as connection:
connection.execute(target_table.insert(), dict_data)
def selectORM(session, FILTER, LIMIT):
query = session.query(Images.image_id, Images.site_name_id, Images.contentUrl, Images.imagename,
Encodings.encoding_id, Images.site_image_id, Encodings.face_landmarks, Encodings.bbox)\
.join(ImagesKeywords, Images.image_id == ImagesKeywords.image_id)\
.join(Keywords, ImagesKeywords.keyword_id == Keywords.keyword_id)\
.outerjoin(Encodings, Images.image_id == Encodings.image_id)\
.filter(*FILTER)\
.limit(LIMIT)
results = query.all()
results_dict = [dict(row) for row in results]
return results_dict
def selectSQL(start_id):
init_session()
if start_id:
# if FROM contains "seg1" or "segment", then assign SegmentTable_name to image_id
if "seg1" in FROM or "segment" in FROM:
image_id_table = SegmentTable_name
else:
image_id_table = "i"
selectsql = f"SELECT {SELECT} FROM {FROM} WHERE {QUERY} AND {image_id_table}.image_id > {start_id} {SUBQUERY} LIMIT {str(LIMIT)};"
else:
selectsql = f"SELECT {SELECT} FROM {FROM} WHERE {WHERE} LIMIT {str(LIMIT)};"
print("actual SELECT is: ",selectsql)
result = engine.connect().execute(text(selectsql))
resultsjson = ([dict(row) for row in result.mappings()])
close_session()
return(resultsjson)
def slice_mp_image(image, bbox):
slice_np = image.numpy_view()[bbox["top"]:bbox["bottom"], bbox["left"]:bbox["right"]]
# Create a new mediapipe.Image from the cropped numpy array
slice_np_uint8 = slice_np.astype(np.uint8)
slice_mp_image = mp.Image(image_format=image.image_format, data=slice_np_uint8)
return slice_mp_image
def get_bbox(faceDet, height, width):
bbox = {}
bbox_obj = faceDet.location_data.relative_bounding_box
xy_min = _normalized_to_pixel_coordinates(bbox_obj.xmin, bbox_obj.ymin, width,height)
xy_max = _normalized_to_pixel_coordinates(bbox_obj.xmin + bbox_obj.width, bbox_obj.ymin + bbox_obj.height,width,height)
if xy_min and xy_max:
# TOP AND BOTTOM WERE FLIPPED
# both in xy_min assign, and in face_mesh.process(image[np crop])
left,top =xy_min
right,bottom = xy_max
bbox={"left":left,"right":right,"top":top,"bottom":bottom}
else:
print("no results???")
return(bbox)
def convert_landmarker_to_facemesh(landmarker_result: vision.FaceLandmarkerResult):
"""
Converts a mediapipe.tasks.python.vision.FaceLandmarkerResult object
to mimic the structure of the results object from the older
mp.solutions.face_mesh.FaceMesh().process() method.
Args:
landmarker_result (vision.FaceLandmarkerResult): The result object
from face_landmarker.detect().
Returns:
types.SimpleNamespace: A mock results object with 'multi_face_landmarks',
'multi_face_blendshapes', and 'multi_face_transformations'
attributes, structured like the old API.
"""
# Create a mock results object
results = types.SimpleNamespace()
results.multi_face_landmarks = []
results.multi_face_blendshapes = []
results.multi_face_transformations = []
if landmarker_result.face_landmarks:
for face_lms_list in landmarker_result.face_landmarks:
# Create a NormalizedLandmarkList for each face
normalized_landmark_list = landmark_pb2.NormalizedLandmarkList()
# Convert each item to a NormalizedLandmark protobuf message
for lm in face_lms_list:
normalized_landmark = landmark_pb2.NormalizedLandmark()
normalized_landmark.x = lm.x
normalized_landmark.y = lm.y
normalized_landmark.z = lm.z
if hasattr(lm, "visibility"):
normalized_landmark.visibility = lm.visibility
if hasattr(lm, "presence"):
normalized_landmark.presence = lm.presence
normalized_landmark_list.landmark.append(normalized_landmark)
results.multi_face_landmarks.append(normalized_landmark_list)
if landmarker_result.face_blendshapes:
for blendshapes_list in landmarker_result.face_blendshapes:
# Create a ClassificationList (which is how blendshapes were structured in old API)
classification_list = classification_pb2.ClassificationList()
for category in blendshapes_list:
# Create a Classification object for each blendshape category
classification = classification_pb2.Classification(
index=category.index,
score=category.score,
label=category.category_name # Use category_name as label
)
classification_list.classification.append(classification)
# The old API's multi_face_blendshapes was a list of ClassificationList objects
results.multi_face_blendshapes.append(classification_list)
if landmarker_result.facial_transformation_matrixes:
# The transformation matrices are already numpy arrays in the new API,
# and the old API also expected a list of numpy arrays.
results.multi_face_transformations = landmarker_result.facial_transformation_matrixes
return results
def find_face(image, df):
# image is SRGBA mp.Image (for mp task GPU implementation)
image = ensure_image_mp(image)
# find_face_start = time.time()
number_of_detections = 0
is_face = False
is_face_no_lms = None
# Perform face detection
detection_result = face_detector.detect(image)
if detection_result.detections:
number_of_detections = len(detection_result.detections)
if not QUIET: print("---------------- >>>>>>>>>>>>>>>>> number_of_detections", number_of_detections)
# Assuming you take the first detected face for simplicity
faceDet = detection_result.detections[0]
# The bounding box format from FaceDetector is different.
# You'll need to convert it to your bbox format if `get_bbox` expects something specific.
bbox_mp = faceDet.bounding_box
bbox = {
"left": bbox_mp.origin_x,
"top": bbox_mp.origin_y,
"right": bbox_mp.origin_x + bbox_mp.width,
"bottom": bbox_mp.origin_y + bbox_mp.height
}
if bbox and not FIND_MISSING_BBOX_ONLY:
# this is the regular version, where we want landmarks too
# take just the bbox slice of the mp.Image and detect on that slice
mp_image_face = slice_mp_image(image, bbox)
landmarker_result = face_landmarker.detect(mp_image_face)
bbox_json = json.dumps(bbox, indent = 4)
#read any image containing a face
if landmarker_result.face_landmarks:
#construct pose object to solve pose
is_face = True
pose = SelectPose(image)
results = convert_landmarker_to_facemesh(landmarker_result)
#get landmarks
faceLms = pose.get_face_landmarks(results,bbox)
#calculate base data from landmarks
pose.calc_face_data(faceLms)
# get angles, using r_vec property stored in class
# angles are meta. there are other meta --- size and resize or something.
pose.model_points = pose.get_model_points_corrected()
results = pose.calculate_face_pose_final(bbox, faceLms)
mouth_gap = pose.get_mouth_data(faceLms)
if is_face:
encodings = calc_encodings(image, faceLms,bbox) ## changed parameters
if not QUIET: print(">> find_face SPLIT >> calc_encodings")
if not QUIET: print("face pose XYZ results:", len(results))
df.at['1', 'pitch'] = results["pitch"]
df.at['1', 'yaw'] = results["yaw"]
df.at['1', 'roll'] = results["roll"]
df.at['1', 'mouth_gap'] = mouth_gap
df.at['1', 'face_landmarks'] = pickle.dumps(faceLms)
df.at['1', 'bbox'] = bbox_json
if SMALL_MODEL is True:
df.at['1', 'face_encodings'] = pickle.dumps(encodings)
else:
df.at['1', 'face_encodings68'] = pickle.dumps(encodings)
else:
if not QUIET: print("+++++++++++++++++ YES FACE but NO FACE LANDMARKS +++++++++++++++++++++")
image_id = df.at['1', 'image_id']
is_face_no_lms = True
elif FIND_MISSING_BBOX_ONLY:
# only looking for bbox, so if we found a face, we have a bbox
is_face = True
bbox_json = json.dumps(bbox, indent = 4)
df.at['1', 'bbox'] = bbox_json
else:
if not QUIET: print("+++++++++++++++++ NO BBOX DETECTED +++++++++++++++++++++")
else:
if not QUIET: print("+++++++++++++++++ NO FACE DETECTED +++++++++++++++++++++")
number_of_detections = 0
image_id = df.at['1', 'image_id']
no_image_name = f"no_face_landmarks_{image_id}.jpg"
is_face_no_lms = False
is_face = False
df.at['1', 'is_face'] = is_face
df.at['1', 'is_face_no_lms'] = is_face_no_lms
return df, number_of_detections
def calc_encodings(image, faceLms,bbox):## changed parameters and rebuilt
image = ensure_image_cv2(image)
def get_dlib_all_points(landmark_points):
raw_landmark_set = []
for index in landmark_points: ######### CORRECTION: landmark_points_5_3 is the correct one for sure
# print(faceLms[index].x)
# second attempt, tries to project faceLms from bbox origin
x = int(faceLms.landmark[index].x * width + bbox["left"])
y = int(faceLms.landmark[index].y * height + bbox["top"])
landmark_point=dlib.point([x,y])
raw_landmark_set.append(landmark_point)
dlib_all_points=dlib.points(raw_landmark_set)
return dlib_all_points
# print("all_points", all_points)
# print(bbox)
# second attempt, tries to project faceLms from bbox origin
width = (bbox["right"]-bbox["left"])
height = (bbox["bottom"]-bbox["top"])
landmark_points_68 = [162,234,93,58,172,136,149,148,152,377,378,365,397,
288,323,454,389,71,63,105,66,107,336,296,334,293,
301,168,197,5,4,75,97,2,326,305,33,160,158,133,
153,144,362,385,387,263,373,380,61,39,37,0,267,
269,291,405,314,17,84,181,78,82,13,312,308,317,
14,87]
landmark_points_5 = [ 263, #left eye away from centre
362, #left eye towards centre
33, #right eye away from centre
133, #right eye towards centre
2 #bottom of nose tip
]
if SMALL_MODEL is True:landmark_points=landmark_points_5
else:landmark_points=landmark_points_68
dlib_all_points68 = get_dlib_all_points(landmark_points_68)
# ymin ("top") would be y value for top left point.
bbox_rect= dlib.rectangle(left=bbox["left"], top=bbox["top"], right=bbox["right"], bottom=bbox["bottom"])
if (dlib_all_points68 is None) or (bbox is None):return
full_object_detection68=dlib.full_object_detection(bbox_rect,dlib_all_points68)
encodings68=face_encoder.compute_face_descriptor(image, full_object_detection68, num_jitters=NUM_JITTERS)
encodings = encodings68
return np.array(encodings).tolist()
def convert_landmarker_to_bodyLms(detection_result: vision.PoseLandmarkerResult):
"""
Converts a mediapipe.tasks.python.vision.PoseLandmarkerResult object
to mimic the structure of the results object (bodyLms) from the older
mp.solutions.pose.Pose().process() method.
Args:
detection_result (vision.PoseLandmarkerResult): The result object
from pose_landmarker.detect().
Returns:
types.SimpleNamespace: A mock results object with 'pose_landmarks' and
'pose_world_landmarks' attributes, structured like the old API.
"""
bodyLms = types.SimpleNamespace()
bodyLms.pose_landmarks = [] # Initialize as a list
bodyLms.pose_world_landmarks = [] # Initialize as a list
# segmentation_mask is not included as enable_segmentation was False in old code
if detection_result.pose_landmarks:
normalized_landmark_list = landmark_pb2.NormalizedLandmarkList()
# Iterate and append each landmark individually to avoid TypeError
for lm in detection_result.pose_landmarks[0]:
new_lm = landmark_pb2.NormalizedLandmark(x=lm.x, y=lm.y, z=lm.z, visibility=lm.visibility, presence=lm.presence)
normalized_landmark_list.landmark.append(new_lm)
bodyLms.pose_landmarks.append(normalized_landmark_list) # Append the protobuf object to the list
if detection_result.pose_world_landmarks:
world_landmark_list = landmark_pb2.LandmarkList()
# Iterate and append each landmark individually to avoid TypeError
for lm in detection_result.pose_world_landmarks[0]:
new_lm = landmark_pb2.Landmark(x=lm.x, y=lm.y, z=lm.z, visibility=lm.visibility, presence=lm.presence)
world_landmark_list.landmark.append(new_lm)
bodyLms.pose_world_landmarks.append(world_landmark_list) # Append the protobuf object to the list
return bodyLms
def convert_landmarker_to_handLms(detection_result: vision.HandLandmarkerResult):
"""
Converts a mediapipe.tasks.python.vision.HandLandmarkerResult object
to mimic the structure of the results object from the older
mp.solutions.hands.Hands().process() method.
Args:
detection_result (vision.HandLandmarkerResult): The result object
from hand_landmarker.detect().
Returns:
types.SimpleNamespace: A mock results object with 'multi_hand_landmarks',
'multi_hand_world_landmarks', and 'multi_handedness'
attributes, structured like the old API.
"""
results = types.SimpleNamespace()
results.multi_hand_landmarks = []
results.multi_hand_world_landmarks = []
results.multi_handedness = []
if detection_result.hand_landmarks:
for idx, hand_lms_list in enumerate(detection_result.hand_landmarks):
# Convert hand_landmarks (List[NormalizedLandmark]) to NormalizedLandmarkList
normalized_landmark_list = landmark_pb2.NormalizedLandmarkList()
# Iterate and append each landmark individually to avoid TypeError
for lm in hand_lms_list:
new_lm = landmark_pb2.NormalizedLandmark(x=lm.x, y=lm.y, z=lm.z, visibility=lm.visibility, presence=lm.presence)
normalized_landmark_list.landmark.append(new_lm)
results.multi_hand_landmarks.append(normalized_landmark_list)
# Convert hand_world_landmarks (List[Landmark]) to LandmarkList
if detection_result.hand_world_landmarks and idx < len(detection_result.hand_world_landmarks):
world_landmark_list = landmark_pb2.LandmarkList()
# Iterate and append each landmark individually to avoid TypeError
for lm in detection_result.hand_world_landmarks[idx]:
new_lm = landmark_pb2.Landmark(x=lm.x, y=lm.y, z=lm.z, visibility=lm.visibility, presence=lm.presence)
world_landmark_list.landmark.append(new_lm)
results.multi_hand_world_landmarks.append(world_landmark_list)
else:
results.multi_hand_world_landmarks.append(landmark_pb2.LandmarkList())
# Convert handedness (List[Category]) to ClassificationList
if detection_result.handedness and idx < len(detection_result.handedness):
classification_list = classification_pb2.ClassificationList()
# Iterate and append each category individually to avoid TypeError
for category in detection_result.handedness[idx]:
classification = classification_pb2.Classification(
index=category.index,
score=category.score,
label=category.category_name
)
classification_list.classification.append(classification)
results.multi_handedness.append(classification_list)
else:
results.multi_handedness.append(classification_pb2.ClassificationList())
return results
def find_body(image):
if VERBOSE: print("find_body")
mp_image = ensure_image_mp(image) # Ensure image is in the correct format for MediaPipe
is_body = body_landmarks = body_world_landmarks = None # Initialize world_landmarks
try:
# Process the image to detect pose landmarks
detection_result = pose_landmarker.detect(mp_image)
# PoseLandmarkerResult has 'pose_landmarks' and 'pose_world_landmarks' directly
# These are List[NormalizedLandmark] and List[Landmark] respectively,
# where each list contains the 33 landmarks for the detected pose.
# If no pose is detected, these lists will be empty.
if detection_result.pose_landmarks:
# print("got bodyLms", detection_result )
is_body = True
# The pose_landmarks and pose_world_landmarks are already lists of landmarks
# for the *single* detected pose (or the first one if multiple were allowed).
# If you configured num_poses > 1, you'd iterate detection_result.pose_landmarks
# and detection_result.pose_world_landmarks as lists of lists.
# With default num_poses=1, they are directly the list of 33 landmarks.
body_landmarks = detection_result.pose_landmarks[0] # Access the first (and likely only) pose
body_world_landmarks = detection_result.pose_world_landmarks[0] # Access the first (and likely only) pose
else:
if VERBOSE: print("No body detected.")
except Exception as e:
print(f"[find_body] An error occurred: {e}")
return is_body, body_landmarks, body_world_landmarks
def find_hands(image, pose):
def extract_hand_landmarks_new_api(detection_result):
"""
Extracts hand landmarks and related data from the new MediaPipe HandLandmarkerResult.
This function produces a data structure similar to the old API's output.
Args:
detection_result (mediapipe.tasks.python.vision.HandLandmarkerResult):
The result object from hand_landmarker.detect().
Returns:
list: A list of dictionaries, where each dictionary contains:
- "image_landmarks": List of (x, y, z) tuples for image coordinates.