Spaces:
Sleeping
Sleeping
File size: 3,365 Bytes
edbe38f 07afc9e 541290e 07afc9e d277e62 | 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 | import os
# Utilise un dossier temporaire où on a le droit d'écriture
deepface_home = "/tmp/.deepface"
os.environ['DEEPFACE_HOME'] = deepface_home
os.makedirs(deepface_home, exist_ok=True)
import json
import numpy as np
from deepface import DeepFace
import cv2
def auto_rotate_if_needed(image_path):
img = cv2.imread(image_path)
if img is None:
raise ValueError(f"Image non lisible : {image_path}")
h, w = img.shape[:2]
# 1. Si image couchée → pivoter verticalement
if w > h:
img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
# 2. Si image à l’envers (tête en bas), corriger :
# On peut ici forcer une rotation supplémentaire si nécessaire
# 💡 OPTION : ajouter une vérification automatique plus intelligente avec un modèle plus tard
img = cv2.rotate(img, cv2.ROTATE_180) # Pour le cas à l’envers
# 3. Écraser l'image modifiée
cv2.imwrite(image_path, img)
return image_path
def auto_rotate_folder(folder_path):
for filename in os.listdir(folder_path):
if filename.lower().endswith((".jpg", ".jpeg", ".png")):
full_path = os.path.join(folder_path, filename)
auto_rotate_if_needed(full_path)
def auto_rotate_all(folders):
"""
Corrige l'orientation des images dans une liste de dossiers,
y compris leurs sous-dossiers.
"""
for folder_path in folders:
print(f"\n🔁 Correction des images dans : {folder_path}")
for root, _, files in os.walk(folder_path):
for filename in files:
if filename.lower().endswith((".jpg", ".jpeg", ".png")):
full_path = os.path.join(root, filename)
try:
auto_rotate_if_needed(full_path)
except Exception as e:
print(f"⚠️ Erreur sur {filename} : {e}")
def create_template_from_folder(folder_path, model_name="ArcFace"):
embeddings = []
for filename in os.listdir(folder_path):
if filename.lower().endswith((".jpg", ".jpeg", ".png")):
img_path = os.path.join(folder_path, filename)
try:
print(f"📷 Traitement : {filename}")
auto_rotate_if_needed(img_path)
reps = DeepFace.represent(img_path=img_path, model_name=model_name, enforce_detection=True)
embeddings.append(reps[0]["embedding"])
except Exception as e:
print(f"⚠️ Erreur sur {filename} : {e}")
if not embeddings:
raise RuntimeError("❌ Aucun embedding valide extrait.")
return np.mean(np.array(embeddings), axis=0)
def save_template(template_array, output_path):
with open(output_path, "w") as f:
json.dump(template_array.tolist(), f)
print(f"✅ Template sauvegardé dans : {output_path}")
def load_template(input_path):
with open(input_path, "r") as f:
return np.array(json.load(f))
def verify_against_template(image_path, template_array, threshold=0.5, model_name="ArcFace"):
reps = DeepFace.represent(img_path=image_path, model_name=model_name, enforce_detection=True)
embedding = np.array(reps[0]["embedding"])
similarity = np.dot(template_array, embedding) / (np.linalg.norm(template_array) * np.linalg.norm(embedding))
return similarity >= threshold, similarity
|