-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdetect_multiple_faces.py
1920 lines (1572 loc) · 78.1 KB
/
detect_multiple_faces.py
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 numpy as np
import mediapipe as mp
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, Keywords, Counters, SegmentTable, SegmentBig_isnotface, ImagesKeywords, ImagesBackground, Encodings, PhoneBbox, 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
#####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 = True
# 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 = False
DO_OVER = True
FIND_NO_IMAGE = False
OVERRIDE_PATH = "/Volumes/SSD4/images_getty"
'''
Oct 13, got up to 109217155
switching to topic targeted
'''
'''
1 getty
2 shutterstock
3 adobe
4 istock
5 pexels
6 unsplash
7 pond5
8 123rf
9 alamy - WIP
10 visualchinagroup - done
11 picxy - done
12 pixerf - done
13 imagesbazaar - done
14 indiapicturebudget - done
15 iwaria - done
16 nappy - done
17 picha - done
18 afripics
'''
# I think this only matters for IS_FOLDER mode, and the old SQL way
SITE_NAME_ID = 1
# 2, shutter. 4, istock
# 7 pond5, 8 123rf
POSE_ID = 0
# folder doesn't matter if IS_FOLDER is False. Declared FAR below.
# MAIN_FOLDER = "/Volumes/RAID18/images_pond5"
MAIN_FOLDER = "/Volumes/SSD4/images_getty"
# MAIN_FOLDER = "/Volumes/SSD4green/images_shutterstock"
# MAIN_FOLDER = "/Users/michaelmandiberg/Documents/projects-active/facemap_production/images_picha"
# MAIN_FOLDER = "/Users/michaelmandiberg/Documents/projects-active/facemap_production/afripics_v2/images"
# MAIN_FOLDER = "/Volumes/SSD4/images_getty_reDL"
BATCH_SIZE = 1000 # Define how many from each folder in each batch
LIMIT = 10000
#temp hack to go 1 subfolder at a time
# THESE_FOLDER_PATHS = ["8/8A", "8/8B","8/8C", "8/8D", "8/8E", "8/8F", "8/80", "8/81", "8/82", "8/83", "8/84", "8/85", "8/86", "8/87", "8/88", "8/89"]
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_PATH = os.path.join(MAIN_FOLDER, "folder_countout.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 = False
HANDLMS = False
TOPIC_ID = None
# TOPIC_ID = [24, 29] # adding a TOPIC_ID forces it to work from SegmentBig_isface, currently at 7412083
DO_INVERSE = True
SEGMENT = 0 # topic_id set to 0 or False if using HelperTable or not using a segment
HelperTable_name = "SegmentHelper_nov23_T37_forwardish" # set to False if not using a HelperTable
# HelperTable_name = False
# SegmentTable_name = 'SegmentOct20'
SegmentTable_name = 'SegmentBig_isnotface'
# if HelperTable_name, set start point
START_IMAGE_ID = 0
if BODYLMS is True or HANDLMS is True:
# prep for image background object
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):
if SegmentTable_name == 'SegmentOct20':
QUERY = " seg1.mongo_body_landmarks IS NULL and seg1.no_image IS NULL"
elif SegmentTable_name == 'SegmentBig_isface':
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})"
if DO_INVERSE:
SUBQUERY = f" AND seg1.image_id NOT IN (SELECT ip.image_id FROM ImagesPoses128 ip)"
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 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}"
else:
WHERE = f"e.encoding_id IS NULL AND i.site_name_id = {SITE_NAME_ID}"
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
NUMBER_OF_PROCESSES = io.NUMBER_OF_PROCESSES
# overriding DB for testing
# io.db["name"] = "gettytest3"
#creating my objects
mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=1, static_image_mode=True)
mp_pose = mp.solutions.pose
mp_drawing = mp.solutions.drawing_utils
drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)
mp_hands = mp.solutions.hands
####### new imports and models ########
mp_face_detection = mp.solutions.face_detection #### added face detection
face_detection = mp_face_detection.FaceDetection(min_detection_confidence=0.7)
# predictor_path = "shape_predictor_68_face_landmarks.dat"
# sp = dlib.shape_predictor(predictor_path)
# # dlib hack
# face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat"
# facerec = dlib.face_recognition_model_v1(face_rec_model_path)
# detector = dlib.get_frontal_face_detector()
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 = False # take all files, based off the very first sort order.
JUMP_SHOT = False # jump to random file if can't find a run
sort = SortPose(motion, face_height_output, image_edge_multiplier_sm,EXPAND, ONE_SHOT, JUMP_SHOT, None, VERBOSE)
start = time.time()
def init_session():
# init session
global engine, Session, session
# engine = create_engine("mysql+pymysql://{user}:{pw}@{host}/{db}"
# .format(host=db['host'], db=db['name'], user=db['user'], pw=db['pass']), poolclass=NullPool)
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']
), 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()
print("garbage collected")
def init_mongo():
# init session
# global engine, Session, session
global mongo_client, mongo_db, mongo_collection, bboxnormed_collection, mongo_hand_collection
# engine = create_engine("mysql+pymysql://{user}:{pw}@{host}/{db}"
# .format(host=db['host'], db=db['name'], user=db['user'], pw=db['pass']), poolclass=NullPool)
# 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']
# ), poolclass=NullPool)
# # metadata = MetaData(engine)
# metadata = MetaData() # apparently don't pass engine
# Session = sessionmaker(bind=engine)
# session = Session()
# Base = declarative_base()
mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
mongo_db = mongo_client["stock"]
mongo_collection = mongo_db["encodings"]
bboxnormed_collection = mongo_db["body_landmarks_norm"]
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 get_hash_folders(filename):
m = hashlib.md5()
m.update(filename.encode('utf-8'))
d = m.hexdigest()
# csvWriter1.writerow(["https://upload.wikimedia.org/wikipedia/commons/"+d[0]+'/'+d[0:2]+'/'+filename])
return d[0], d[0:2]
def read_csv(csv_file):
with open(csv_file, encoding="utf-8", newline="") as in_file:
reader = csv.reader(in_file, delimiter=",")
next(reader) # Header row
for row in reader:
yield row
def print_get_split(split):
now = time.time()
duration = now - split
print(duration)
return now
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 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 retro_bbox(image):
height, width, _ = image.shape
with mp.solutions.face_detection.FaceDetection(model_selection=1, min_detection_confidence=0.7) as face_det:
results_det=face_det.process(image) ## [:,:,::-1] is the shortcut for converting BGR to RGB
# is_face = False
bbox_json = None
if results_det.detections:
faceDet=results_det.detections[0]
bbox = get_bbox(faceDet, height, width)
if bbox:
bbox_json = json.dumps(bbox, indent = 4)
else:
print("no results???")
return bbox_json
def find_face(image, df):
# image is RGB
find_face_start = time.time()
height, width, _ = image.shape
with mp.solutions.face_detection.FaceDetection(model_selection=1, min_detection_confidence=0.7) as face_det:
# print(">> find_face SPLIT >> with mp.solutions constructed")
# ff_split = print_get_split(find_face_start)
results_det=face_det.process(image) ## [:,:,::-1] is the shortcut for converting BGR to RGB
# print(">> find_face SPLIT >> face_det.process(image)")
# ff_split = print_get_split(ff_split)
'''
0 type model: When we will select the 0 type model then our face detection model will be able to detect the
faces within the range of 2 meters from the camera.
1 type model: When we will select the 1 type model then our face detection model will be able to detect the
faces within the range of 5 meters. Though the default value is 0.
'''
is_face = False
if results_det.detections:
faceDet=results_det.detections[0]
number_of_detections = len(results_det.detections)
print("---------------- >>>>>>>>>>>>>>>>> number_of_detections", number_of_detections)
bbox = get_bbox(faceDet, height, width)
# print(">> find_face SPLIT >> get_bbox()")
# ff_split = print_get_split(ff_split)
if bbox:
with mp.solutions.face_mesh.FaceMesh(static_image_mode=True,
refine_landmarks=False,
max_num_faces=1,
min_detection_confidence=0.5
) as face_mesh:
# Convert the BGR image to RGB and cropping it around face boundary and process it with MediaPipe Face Mesh.
# crop_img = img[y:y+h, x:x+w]
# print(">> find_face SPLIT >> const face_mesh")
# ff_split = print_get_split(ff_split)
results = face_mesh.process(image[bbox["top"]:bbox["bottom"],bbox["left"]:bbox["right"]])
# print(">> find_face SPLIT >> face_mesh.process")
# ff_split = print_get_split(ff_split)
#read any image containing a face
if results.multi_face_landmarks:
#construct pose object to solve pose
is_face = True
pose = SelectPose(image)
#get landmarks
faceLms = pose.get_face_landmarks(results, image,bbox)
# print(">> find_face SPLIT >> got lms")
# ff_split = print_get_split(ff_split)
#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.
angles = pose.rotationMatrixToEulerAnglesToDegrees()
mouth_gap = pose.get_mouth_data(faceLms)
##### calculated face detection results
# old version, encodes everything
# print(">> find_face SPLIT >> done face calcs")
# ff_split = print_get_split(ff_split)
if is_face:
# # new version, attempting to filter the amount that get encoded
# if is_face and -20 < angles[0] < 10 and np.abs(angles[1]) < 4 and np.abs(angles[2]) < 3 :
# Calculate Face Encodings if is_face = True
# print("in encodings conditional")
# turning off to debug
encodings = calc_encodings(image, faceLms,bbox) ## changed parameters
print(">> find_face SPLIT >> calc_encodings")
# ff_split = print_get_split(ff_split)
# # image is currently BGR so converting back to RGB
# image_rgb = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# # gets bg hue and lum without bbox
# hue,sat,val,lum, lum_torso=sort.get_bg_hue_lum(image_rgb)
# print("HSV", hue, sat, val)
# gets bg hue and lum with bbox
# hue_bb,sat_bb, val_bb, lum_bb, lum_torso_bb =sort.get_bg_hue_lum(image,bbox,faceLms)
# print("HSV", hue_bb,sat_bb, val_bb)
# quit()
# print(encodings)
# exit()
# #df.at['1', 'is_face'] = is_face
# # debug
# else:
# print("bad angles")
# print(angles[0])
# print(angles[1])
# print(angles[2])
#df.at['1', 'is_face_distant'] = is_face_distant
bbox_json = json.dumps(bbox, indent = 4)
df.at['1', 'face_x'] = angles[0]
df.at['1', 'face_y'] = angles[1]
df.at['1', 'face_z'] = angles[2]
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:
print("+++++++++++++++++ NO FACE DETECTED +++++++++++++++++++++")
number_of_detections = 0
df.at['1', 'is_face'] = is_face
# print(">> find_face SPLIT >> prepped dataframe")
# ff_split = print_get_split(ff_split)
return df, number_of_detections
def calc_encodings(image, faceLms,bbox):## changed parameters and rebuilt
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.landmark[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_points = get_dlib_all_points(landmark_points)
# temp test hack
# dlib_all_points5 = get_dlib_all_points(landmark_points_5)
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_points is None) or (bbox is None):return
# full_object_detection=dlib.full_object_detection(bbox_rect,dlib_all_points)
# encodings=face_encoder.compute_face_descriptor(image, full_object_detection, num_jitters=NUM_JITTERS)
if (dlib_all_points68 is None) or (bbox is None):return
# full_object_detection5=dlib.full_object_detection(bbox_rect,dlib_all_points5)
# encodings5=face_encoder.compute_face_descriptor(image, full_object_detection5, num_jitters=NUM_JITTERS)
# encodings5j=face_encoder.compute_face_descriptor(image, full_object_detection5, num_jitters=3)
# encodings5v2=facerec.compute_face_descriptor(image, full_object_detection5, num_jitters=NUM_JITTERS)
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)
# encodings68j=face_encoder.compute_face_descriptor(image, full_object_detection68, num_jitters=3)
# encodings68v2=facerec.compute_face_descriptor(image, full_object_detection68, num_jitters=NUM_JITTERS)
# # hack of full dlib
# dets = detector(image, 1)
# for k, d in enumerate(dets):
# print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
# k, d.left(), d.top(), d.right(), d.bottom()))
# # Get the landmarks/parts for the face in box d.
# shape = sp(image, d)
# # print("shape")
# # print(shape.pop())
# face_descriptor = facerec.compute_face_descriptor(image, shape)
# # print(face_descriptor)
# encD=np.array(face_descriptor)
encodings = encodings68
# enc1=np.array(encodings5)
# enc2=np.array(encodings68)
# d=np.linalg.norm(enc1 - enc2, axis=0)
# # distance = pose.get_d(encodings5, encodings68)
# print("distance between 5 and 68 ")
# print(d)
# d=np.linalg.norm(encD - enc2, axis=0)
# # distance = pose.get_d(encodings5, encodings68)
# print("distance between dlib and mp hack - 68 ")
# print(d)
# # enc12=np.array(encodings5v2)
# # enc22=np.array(encodings68v2)
# # d=np.linalg.norm(enc12 - enc22, axis=0)
# # # distance = pose.get_d(encodings5, encodings68)
# # print("distance between 5v2 and 68v2 ")
# # print(d)
# enc1j=np.array(encodings5j)
# enc2j=np.array(encodings68j)
# d=np.linalg.norm(enc1j - enc2j, axis=0)
# # distance = pose.get_d(encodings5, encodings68)
# print("distance between 5j and 68j ")
# print(d)
# d=np.linalg.norm(enc1j - enc1, axis=0)
# # distance = pose.get_d(encodings5, encodings68)
# print("distance between 5 and 5j ")
# print(d)
# d=np.linalg.norm(enc2j - enc2, axis=0)
# # distance = pose.get_d(encodings5, encodings68)
# print("distance between 68 and 68j ")
# print(d)
# # d=np.linalg.norm(enc2 - enc22, axis=0)
# # # distance = pose.get_d(encodings5, encodings68)
# # print("distance between 68v and 68v2 ")
# # print(d)
# print(len(encodings))
return np.array(encodings).tolist()
def find_body(image):
if VERBOSE: print("find_body")
with mp_pose.Pose(
static_image_mode=True, min_detection_confidence=0.5) as pose:
# for idx, file in enumerate(file_list):
try:
# image = cv2.imread(file)
image_height, image_width, _ = image.shape
# Convert the BGR image to RGB before processing.
bodyLms = pose.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
if VERBOSE: print("bodyLms, ", bodyLms)
if VERBOSE: print("bodyLms.pose_landmarks, ", bodyLms.pose_landmarks)
# bodyLms = results.pose_landmarks.landmark
if not bodyLms.pose_landmarks:
is_body = False
body_landmarks = None
else:
is_body = True
body_landmarks = bodyLms.pose_landmarks
except:
print(f"[find_body]this item failed: {image}")
return is_body, body_landmarks
def find_hands(image, pose):
#print("find_body")
with mp_hands.Hands(
static_image_mode=True, # If True, hand detection will be performed every frame.
max_num_hands=2, # Detect a maximum of 2 hands.
min_detection_confidence=0.4, # Minimum confidence to detect hands.
min_tracking_confidence=0.5 # Minimum confidence for hand landmarks tracking.
) as hands_detector:
try:
# Assuming image is in BGR format, as typically used in OpenCV.
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Process the image to detect hand landmarks.
detection_result = hands_detector.process(image_rgb)
if not detection_result.multi_handedness:
# print(" >>>>> No hands detected:", )
return None, None
else:
hand_landmarks_list = pose.extract_hand_landmarks(detection_result)
# print(f"Detected hands: {hand_landmarks_list}")
return True, hand_landmarks_list
except:
print(f"[find_hands] this item failed: {image}")
return None, None
# # Extract the hand landmarks and handedness.
# hand_landmarks_list = detection_result.multi_hand_landmarks
# handedness_list = detection_result.multi_handedness
# # If hands are detected
# if hand_landmarks_list:
# for hand_landmarks, handedness in zip(hand_landmarks_list, handedness_list):
# print(f"Handedness: {handedness.classification[0].label}")
# for idx, landmark in enumerate(hand_landmarks.landmark):
# print(f"Landmark {idx}: (x={landmark.x}, y={landmark.y}, z={landmark.z})")
def capitalize_directory(path):
dirname, filename = os.path.split(path)
parts = dirname.split('/')
capitalized_parts = [part if i < len(parts) - 2 else part.upper() for i, part in enumerate(parts)]
capitalized_dirname = '/'.join(capitalized_parts)
return os.path.join(capitalized_dirname, filename)
# this was for reprocessing the missing bbox
def process_image_bbox(task):
# df = pd.DataFrame(columns=['image_id','bbox'])
# print("task is: ",task)
encoding_id = task[0]
cap_path = capitalize_directory(task[1])
try:
image = cv2.imread(cap_path)
# this is for when you need to move images into a testing folder structure
# save_image_elsewhere(image, task)
except:
print(f"[process_image]this item failed, even after uppercasing: {task}")
# print("processing: ")
# print(encoding_id)
if image is not None and image.shape[0]>MINSIZE and image.shape[1]>MINSIZE:
# Do FaceMesh
bbox_json = retro_bbox(image)
# print(bbox_json)
if bbox_json:
for _ in range(io.max_retries):
try:
update_sql = f"UPDATE Encodings SET bbox = '{bbox_json}' WHERE encoding_id = {encoding_id};"
engine.connect().execute(text(update_sql))
print("bboxxin:")
print(encoding_id)
break # Transaction succeeded, exit the loop
except OperationalError as e:
print(e)
time.sleep(io.retry_delay)
else:
print("no bbox")
else:
print('toooooo smallllll')
# I should probably assign no_good here...?
# store data
def process_image_enc_only(task):
# print("process_image_enc_only")
encoding_id = task[0]
faceLms = task[2]
bbox = io.unstring_json(task[3])
cap_path = capitalize_directory(task[1])
print(cap_path)
try:
image = cv2.imread(cap_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
except:
print(f"[process_image]this item failed: {task}")
if image is not None and image.shape[0]>MINSIZE and image.shape[1]>MINSIZE:
face_encodings = calc_encodings(image, faceLms,bbox)
else:
print('toooooo smallllll')
pickled_encodings = pickle.dumps(face_encodings)
df = pd.DataFrame(columns=['encoding_id'])
df.at['1', 'encoding_id'] = encoding_id
# df.at['1', 'face_encodings'] = pickled_encodings
# set name of df and table column, based on model and jitters
# df_table_column = "face_encodings"
# if SMALL_MODEL is not True:
# df_table_column = df_table_column+"68"
# if NUM_JITTERS > 1:
# df_table_column = df_table_column+"_J"+str(NUM_JITTERS)
# df.at['1', df_table_column] = pickled_encodings
# sql = """
# UPDATE Encodings SET df_table_column = :df_table_column
# WHERE encoding_id = :encoding_id
# """
# else:
if SMALL_MODEL is True and NUM_JITTERS == 1:
df.at['1', 'face_encodings'] = pickled_encodings
sql = """
UPDATE Encodings SET face_encodings = :face_encodings
WHERE encoding_id = :encoding_id
"""
elif SMALL_MODEL is False and NUM_JITTERS == 1:
print("updating face_encodings68")
df.at['1', 'face_encodings68'] = pickled_encodings
sql = """
UPDATE Encodings SET face_encodings68 = :face_encodings68
WHERE encoding_id = :encoding_id
"""
elif SMALL_MODEL is True and NUM_JITTERS == 3:
df.at['1', 'face_encodings_J3'] = pickled_encodings
sql = """
UPDATE Encodings SET face_encodings_J3 = :face_encodings_J3
WHERE encoding_id = :encoding_id
"""
elif SMALL_MODEL is False and NUM_JITTERS == 3:
df.at['1', 'face_encodings68_J3'] = pickled_encodings
sql = """
UPDATE Encodings SET face_encodings68_J3 = :face_encodings68_J3
WHERE encoding_id = :encoding_id
"""
elif SMALL_MODEL is True and NUM_JITTERS == 5:
df.at['1', 'face_encodings_J5'] = pickled_encodings
sql = """
UPDATE Encodings SET face_encodings_J5 = :face_encodings_J5
WHERE encoding_id = :encoding_id
"""
elif SMALL_MODEL is False and NUM_JITTERS == 5:
df.at['1', 'face_encodings68_J5'] = pickled_encodings
sql = """
UPDATE Encodings SET face_encodings68_J5 = :face_encodings68_J5
WHERE encoding_id = :encoding_id
"""
try:
with engine.begin() as conn:
params = df.to_dict("records")
conn.execute(text(sql), params)
print("updated:",str(encoding_id))
except OperationalError as e:
print(e)
def process_image_find_body_subroutine(image_id, image, bbox):
is_body = body_landmarks = face_height = nose_pixel_pos = None
# Check if body landmarks are already in the normalized collection
existing_norm = bboxnormed_collection.find_one({"image_id": image_id})
if existing_norm:
print(f"Normalized landmarks already exist for image_id: {image_id}")
is_body = True