JustinePP commited on
Commit
d277e62
·
verified ·
1 Parent(s): a94c5c8

Create deepface_template_utils.py

Browse files
Files changed (1) hide show
  1. deepface_template_utils.py +82 -0
deepface_template_utils.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import numpy as np
4
+ from deepface import DeepFace
5
+ import cv2
6
+
7
+
8
+ def auto_rotate_if_needed(image_path):
9
+ img = cv2.imread(image_path)
10
+ if img is None:
11
+ raise ValueError(f"Image non lisible : {image_path}")
12
+
13
+ h, w = img.shape[:2]
14
+
15
+ # 1. Si image couchée → pivoter verticalement
16
+ if w > h:
17
+ img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
18
+
19
+ # 2. Si image à l’envers (tête en bas), corriger :
20
+ # On peut ici forcer une rotation supplémentaire si nécessaire
21
+ # 💡 OPTION : ajouter une vérification automatique plus intelligente avec un modèle plus tard
22
+ img = cv2.rotate(img, cv2.ROTATE_180) # Pour le cas à l’envers
23
+
24
+ # 3. Écraser l'image modifiée
25
+ cv2.imwrite(image_path, img)
26
+ return image_path
27
+
28
+ def auto_rotate_folder(folder_path):
29
+ for filename in os.listdir(folder_path):
30
+ if filename.lower().endswith((".jpg", ".jpeg", ".png")):
31
+ full_path = os.path.join(folder_path, filename)
32
+ auto_rotate_if_needed(full_path)
33
+
34
+ def auto_rotate_all(folders):
35
+ """
36
+ Corrige l'orientation des images dans une liste de dossiers,
37
+ y compris leurs sous-dossiers.
38
+ """
39
+ for folder_path in folders:
40
+ print(f"\n🔁 Correction des images dans : {folder_path}")
41
+ for root, _, files in os.walk(folder_path):
42
+ for filename in files:
43
+ if filename.lower().endswith((".jpg", ".jpeg", ".png")):
44
+ full_path = os.path.join(root, filename)
45
+ try:
46
+ auto_rotate_if_needed(full_path)
47
+ except Exception as e:
48
+ print(f"⚠️ Erreur sur {filename} : {e}")
49
+
50
+
51
+
52
+
53
+ def create_template_from_folder(folder_path, model_name="ArcFace"):
54
+ embeddings = []
55
+ for filename in os.listdir(folder_path):
56
+ if filename.lower().endswith((".jpg", ".jpeg", ".png")):
57
+ img_path = os.path.join(folder_path, filename)
58
+ try:
59
+ print(f"📷 Traitement : {filename}")
60
+ auto_rotate_if_needed(img_path)
61
+ reps = DeepFace.represent(img_path=img_path, model_name=model_name, enforce_detection=True)
62
+ embeddings.append(reps[0]["embedding"])
63
+ except Exception as e:
64
+ print(f"⚠️ Erreur sur {filename} : {e}")
65
+ if not embeddings:
66
+ raise RuntimeError("❌ Aucun embedding valide extrait.")
67
+ return np.mean(np.array(embeddings), axis=0)
68
+
69
+ def save_template(template_array, output_path):
70
+ with open(output_path, "w") as f:
71
+ json.dump(template_array.tolist(), f)
72
+ print(f"✅ Template sauvegardé dans : {output_path}")
73
+
74
+ def load_template(input_path):
75
+ with open(input_path, "r") as f:
76
+ return np.array(json.load(f))
77
+
78
+ def verify_against_template(image_path, template_array, threshold=0.5, model_name="ArcFace"):
79
+ reps = DeepFace.represent(img_path=image_path, model_name=model_name, enforce_detection=True)
80
+ embedding = np.array(reps[0]["embedding"])
81
+ similarity = np.dot(template_array, embedding) / (np.linalg.norm(template_array) * np.linalg.norm(embedding))
82
+ return similarity >= threshold, similarity