shoolinidetectfaces / simple_facerec.py
visharxd's picture
Upload folder using huggingface_hub
e171b2d verified
import face_recognition
import cv2
import os
import glob
import numpy as np
class SimpleFacerec:
def __init__(self):
self.known_face_encodings = []
self.known_face_names = []
# Resize frame for a faster speed
self.frame_resizing = 0.25
def load_encoding_images(self, images_path):
"""
Load encoding images from path
:param images_path: Path to directory containing images
:return: None
"""
# Ensure the path exists
if not os.path.exists(images_path):
print(f"Error: Path {images_path} does not exist.")
return
# Load Images with error handling
images_path = glob.glob(os.path.join(images_path, "*.*"))
print(f"{len(images_path)} images found.")
# Store image encoding and names
for img_path in images_path:
try:
# Read image with error handling
img = cv2.imread(img_path)
# Check if image is successfully read
if img is None:
print(f"Error: Could not read image {img_path}")
continue
# Convert to RGB
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Get the filename only from the initial file path
basename = os.path.basename(img_path)
(filename, ext) = os.path.splitext(basename)
# Get face encodings
face_encodings = face_recognition.face_encodings(rgb_img)
# Check if any faces found in the image
if not face_encodings:
print(f"No face found in {img_path}")
continue
# Get encoding of the first face
img_encoding = face_encodings[0]
# Store file name and file encoding
self.known_face_encodings.append(img_encoding)
self.known_face_names.append(filename)
except Exception as e:
print(f"Error processing {img_path}: {e}")
print(f"{len(self.known_face_encodings)} encoding images loaded successfully")
def detect_known_faces(self, frame):
# Check if frame is empty
if frame is None:
return [], []
# Resize frame
small_frame = cv2.resize(frame, (0, 0), fx=self.frame_resizing, fy=self.frame_resizing)
# Convert the image from BGR color to RGB color
rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
# Find faces and encodings
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
# Check if we have any known face encodings
if not self.known_face_encodings:
face_names.append("Unknown")
continue
# Compare faces
matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding)
name = "Unknown"
# Use the known face with the smallest distance
face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = self.known_face_names[best_match_index]
face_names.append(name)
# Adjust face locations
face_locations = np.array(face_locations)
face_locations = face_locations / self.frame_resizing
return face_locations.astype(int), face_names