import os import cv2 import pandas as pd from deepface import DeepFace from datetime import datetime, timedelta # ✅ Set proper Windows paths using raw strings base_save_path = r"C:\Users\caspe\Desktop\Database" db_path = base_save_path # same folder for images excel_output_path = os.path.join(base_save_path, "output_most_similar.xlsx") # Ensure the base path exists os.makedirs(base_save_path, exist_ok=True) # Track last capture times last_capture_times = {} current_frame = None last_recognized_name = None # ✅ Face recognition loop def recognize_faces(): global current_frame, last_recognized_name # ✅ Use your own image here test_image_path = r"C:\Users\caspe\Desktop\Facesdb\00000001.jpg" if not os.path.exists(test_image_path): print("❌ Please upload a face image to:", test_image_path) return frame = cv2.imread(test_image_path) current_frame = frame.copy() try: faces = DeepFace.extract_faces(frame, enforce_detection=False) except Exception as e: print("Face extraction failed:", e) return if not faces: print("⚠️ No face detected.") return for face in faces: temp_image_path = r"C:\Users\caspe\Desktop\Facesdb\temp_image.jpg" cv2.imwrite(temp_image_path, frame) try: dfs = DeepFace.find( img_path=temp_image_path, db_path=db_path, enforce_detection=True, model_name="ArcFace" ) except Exception as e: print(f"❌ DeepFace.find failed: {e}") continue result_list = [] for result in dfs: for index, row in result.iterrows(): result_list.append(row) df = pd.DataFrame(result_list).reset_index(drop=True) current_time = datetime.now() if not df.empty: most_similar = df.loc[df['distance'].idxmin()] most_similar_path = most_similar['identity'] name = os.path.splitext(os.path.basename(most_similar_path))[0] last_recognized_name = name current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S') current_time_for_filename = current_time.strftime('%Y-%m-%d %H-%M-%S') if name not in last_capture_times or (current_time - last_capture_times[name]) >= timedelta(seconds=30): last_capture_times[name] = current_time person_folder = os.path.join(base_save_path, name) os.makedirs(person_folder, exist_ok=True) matched_image_filename = f"{current_time_for_filename}.jpg" matched_image_path = os.path.join(person_folder, matched_image_filename) cv2.imwrite(matched_image_path, frame) # ✅ Show matched image in a window cv2.imshow(f"Matched: {name}", frame) cv2.waitKey(3000) # show for 3 seconds cv2.destroyAllWindows() result_data = pd.DataFrame([{ 'Most Similar Name': name, 'Match': 'True', 'Checked At': current_time_str, 'Image File': matched_image_filename }]) if os.path.exists(excel_output_path): existing_data = pd.read_excel(excel_output_path) updated_data = pd.concat([existing_data, result_data], ignore_index=True) updated_data.to_excel(excel_output_path, index=False) else: result_data.to_excel(excel_output_path, index=False) log_file_path = os.path.join(person_folder, "log.txt") with open(log_file_path, 'a', encoding='utf-8') as log_file: log_file.write(f"[✅] Recognized at {current_time_str} | Image: {matched_image_filename}\n") print(f"✅ Match found: {name} — saved at {matched_image_path}") else: print(f"🕒 {name} was recognized recently, skipping save.") else: print("❌ No match found in DB.") # ✅ Run it in PyCharm if __name__ == "__main__": recognize_faces() # ✅ Show final match results print("\n🔍 Running standalone DeepFace.find for testing...\n") try: result = DeepFace.find( img_path=r"C:\Users\caspe\Desktop\Facesdb\00000001.jpg", db_path=r"C:\Users\caspe\Desktop\Database", model_name="ArcFace", enforce_detection=False ) if result and isinstance(result, list) and not result[0].empty: top_match = result[0].sort_values("distance").iloc[0] name = os.path.basename(top_match["identity"]) print(f"✅ Top Match: {name} — Distance: {top_match['distance']:.4f}") # ✅ Show matched image in a window matched_img = cv2.imread(top_match["identity"]) if matched_img is not None: cv2.imshow(f"Top Match: {name}", matched_img) cv2.waitKey(3000) cv2.destroyAllWindows() else: print("⚠️ Could not load matched image for display.") else: print("❌ No matches found.") except Exception as e: print(f"❌ DeepFace.find test failed: {e}")