test.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. #
  5. # Copyright © 2024 StrayWarrior <i@straywarrior.com>
  6. import os
  7. import face_recognition
  8. from PIL import Image
  9. def load_known_faces(known_faces_dir):
  10. known_face_encodings = []
  11. known_face_names = []
  12. for filename in os.listdir(known_faces_dir):
  13. if filename.endswith(".jpg") or filename.endswith(".png"):
  14. image_path = os.path.join(known_faces_dir, filename)
  15. image = face_recognition.load_image_file(image_path)
  16. face_encoding = face_recognition.face_encodings(image)[0]
  17. known_face_encodings.append(face_encoding)
  18. known_face_names.append(os.path.splitext(filename)[0])
  19. return known_face_encodings, known_face_names
  20. def find_faces_in_images(image_dir, known_face_encodings, known_face_names):
  21. results = {}
  22. for filename in os.listdir(image_dir):
  23. if filename.endswith(".jpg") or filename.endswith(".png"):
  24. image_path = os.path.join(image_dir, filename)
  25. image = face_recognition.load_image_file(image_path)
  26. face_locations = face_recognition.face_locations(image)
  27. face_encodings = face_recognition.face_encodings(image, face_locations)
  28. found_faces = []
  29. for face_encoding in face_encodings:
  30. matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
  31. name = "Unknown"
  32. if True in matches:
  33. first_match_index = matches.index(True)
  34. name = known_face_names[first_match_index]
  35. found_faces.append(name)
  36. if found_faces:
  37. results[filename] = found_faces
  38. return results
  39. def main():
  40. known_faces_dir = "known_faces" # Directory with images of known faces
  41. image_dir = "images_to_check" # Directory with images to check
  42. known_face_encodings, known_face_names = load_known_faces(known_faces_dir)
  43. results = find_faces_in_images(image_dir, known_face_encodings, known_face_names)
  44. for image_name, found_faces in results.items():
  45. print(f"In {image_name}, found faces: {', '.join(found_faces)}")
  46. if __name__ == "__main__":
  47. main()