hello everyone,I am facing problem in my program i want it to detect and recognise faces from a bunch of images and give output which contain all the matching images of the detected face.
but this program is not giving any matched faces when the stored_album contains all photos that has detected face .
please help me to find its solution.

code

import os, cv2, numpy as np, requests, pandas as pd
from deepface import DeepFace
import mediapipe as mp

── Config ──────────────────────────────────────────────────

STORED_DIR = "stored_faces"
MATCHED_DIR = "matched_faces"
IP_WEBCAM_URL = "http://192.168.194.192:8080/shot.jpg"

MODEL_NAME = "SFace"

THRESHOLDS = [0.6, 0.65, 0.7, 0.75]

CONFIDENCE = 0.6

os.makedirs(MATCHED_DIR, exist_ok=True)

── MediaPipe Detector ─────────────────────────────────────

mp_fd = mp.solutions.face_detection
detector = mp_fd.FaceDetection(min_detection_confidence=CONFIDENCE)

def has_face(frame):
"""Return True if MediaPipe finds a face in frame."""
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
return bool(detector.process(rgb).detections)

def auto_rotate_if_landscape(frame):
h, w = frame.shape[:2]
if w > h:
return cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
return frame

── Capture Frame ───────────────────────────────────────────

def capture_frame():
"""Capture a single frame from webcam or IP Webcam (press 'c' to capture, 'q' to quit)."""
print("1) Webcam\n2) Mobile (IP Webcam)\n3) Quit")
choice = input("Choice: ").strip()

if choice == "1":
    cap = cv2.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        if not ret:
            print("❌ Cannot read from webcam.")
            break
        cv2.imshow("Webcam – press 'c' to capture, 'q' to quit", frame)
        key = cv2.waitKey(1) & 0xFF
        if key == ord('c'):
            cap.release(); cv2.destroyAllWindows()
            return frame
        elif key == ord('q'):
            cap.release(); cv2.destroyAllWindows()
            return None

elif choice == "2":
    # Live IP Webcam preview loop
    while True:
        try:
            resp = requests.get(IP_WEBCAM_URL, timeout=5)
            img_arr = np.frombuffer(resp.content, np.uint8)
            frame = cv2.imdecode(img_arr, cv2.IMREAD_COLOR)
        except Exception as e:
            print(f"❌ Failed to fetch from IP webcam: {e}")
            return None

        # auto‑rotate if needed
        frame = auto_rotate_if_landscape(frame)
        cv2.imshow("IP Webcam – press 'c' to capture, 'q' to quit", frame)
        key = cv2.waitKey(1) & 0xFF
        if key == ord('c'):
            cv2.destroyAllWindows()
            return frame
        elif key == ord('q'):
            cv2.destroyAllWindows()
            return None

elif choice == "3":
    return None

else:
    print("Invalid choice. Please select 1, 2, or 3.")
    return None

── Recognition & Saving ────────────────────────────────────

def recognize_and_save(frame, user):
"""Find matches for the frame under each threshold and save the best."""
if not has_face(frame):
print("❌ No face detected."); return

tmp = "tmp_capture.jpg"
cv2.imwrite(tmp, frame)

# DeepFace.find handles embedding + search under the hood :contentReference[oaicite:11]{index=11}
results = DeepFace.find(
    img_path=tmp,
    db_path=STORED_DIR,
    model_name=MODEL_NAME,
    distance_metric="euclidean_l2",
    enforce_detection=False
)
os.remove(tmp)

# Unpack if returned as [DataFrame] :contentReference[oaicite:12]{index=12}
df = results[0] if isinstance(results, list) else results
df["distance"] = pd.to_numeric(df["distance"], errors="coerce")

for thresh in THRESHOLDS:
    subset = df[df["distance"] < thresh]
    print(f"\n🔍 Threshold {thresh} → {len(subset)} match(es)")
    if not subset.empty:
        out_dir = os.path.join(MATCHED_DIR, user)
        os.makedirs(out_dir, exist_ok=True)
        for path in subset["identity"].tolist():
            fname = os.path.basename(path)
            img = cv2.imread(path)
            cv2.imwrite(os.path.join(out_dir, fname), img)
        print(f"✅ Saved {len(subset)} images to '{out_dir}'")
        return

print("❌ No matches below any threshold.")

── Main Loop ───────────────────────────────────────────────

def main():
while True:
frame = capture_frame()
if frame is None:
print("Exiting."); break

name = input("Enter your name/label: ").strip()
    if name:
        recognize_and_save(frame, name)

    if input("Again? (y/n): ").lower() != 'y':
        print("Goodbye!"); break

if name == "main":
main()